repo_name
stringclasses
5 values
pr_number
int64
1.52k
15.5k
pr_title
stringlengths
8
143
pr_description
stringlengths
0
10.2k
author
stringlengths
3
18
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
11
10.2k
filepath
stringlengths
6
220
before_content
stringlengths
0
597M
after_content
stringlengths
0
597M
label
int64
-1
1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/test/java/com/ctrip/framework/apollo/portal/AbstractIntegrationTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal; import com.ctrip.framework.apollo.SkipAuthorizationConfiguration; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.RestTemplate; import javax.annotation.PostConstruct; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = { PortalApplication.class, SkipAuthorizationConfiguration.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public abstract class AbstractIntegrationTest { protected RestTemplate restTemplate = (new TestRestTemplate()).getRestTemplate(); @PostConstruct private void postConstruct() { System.setProperty("spring.profiles.active", "test"); restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); } @Value("${local.server.port}") int port; protected String url(String path) { return "http://localhost:" + port + path; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal; import com.ctrip.framework.apollo.SkipAuthorizationConfiguration; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.RestTemplate; import javax.annotation.PostConstruct; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = { PortalApplication.class, SkipAuthorizationConfiguration.class }, webEnvironment = WebEnvironment.RANDOM_PORT) public abstract class AbstractIntegrationTest { protected RestTemplate restTemplate = (new TestRestTemplate()).getRestTemplate(); @PostConstruct private void postConstruct() { System.setProperty("spring.profiles.active", "test"); restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); } @Value("${local.server.port}") int port; protected String url(String path) { return "http://localhost:" + port + path; } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./scripts/apollo-on-kubernetes/kubernetes/apollo-env-prod/service-apollo-config-server-prod.yaml
# # Copyright 2021 Apollo Authors # # Licensed 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. # --- # configmap for apollo-config-server-prod kind: ConfigMap apiVersion: v1 metadata: namespace: sre name: configmap-apollo-config-server-prod data: application-github.properties: | spring.datasource.url = jdbc:mysql://service-mysql-for-apollo-prod-env.sre:3306/ProdApolloConfigDB?characterEncoding=utf8 spring.datasource.username = FillInCorrectUser spring.datasource.password = FillInCorrectPassword eureka.service.url = http://statefulset-apollo-config-server-prod-0.service-apollo-meta-server-prod:8080/eureka/,http://statefulset-apollo-config-server-prod-1.service-apollo-meta-server-prod:8080/eureka/,http://statefulset-apollo-config-server-prod-2.service-apollo-meta-server-prod:8080/eureka/ --- kind: Service apiVersion: v1 metadata: namespace: sre name: service-apollo-meta-server-prod labels: app: service-apollo-meta-server-prod spec: ports: - protocol: TCP port: 8080 targetPort: 8080 selector: app: pod-apollo-config-server-prod type: ClusterIP clusterIP: None sessionAffinity: ClientIP --- kind: Service apiVersion: v1 metadata: namespace: sre name: service-apollo-config-server-prod labels: app: service-apollo-config-server-prod spec: ports: - protocol: TCP port: 8080 targetPort: 8080 nodePort: 30005 selector: app: pod-apollo-config-server-prod type: NodePort sessionAffinity: ClientIP --- kind: StatefulSet apiVersion: apps/v1 metadata: namespace: sre name: statefulset-apollo-config-server-prod labels: app: statefulset-apollo-config-server-prod spec: serviceName: service-apollo-meta-server-prod replicas: 3 selector: matchLabels: app: pod-apollo-config-server-prod updateStrategy: type: RollingUpdate template: metadata: labels: app: pod-apollo-config-server-prod spec: affinity: podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 100 podAffinityTerm: labelSelector: matchExpressions: - key: app operator: In values: - pod-apollo-config-server-prod topologyKey: kubernetes.io/hostname volumes: - name: volume-configmap-apollo-config-server-prod configMap: name: configmap-apollo-config-server-prod items: - key: application-github.properties path: application-github.properties containers: - image: apollo-config-server:v1.0.0 securityContext: privileged: true imagePullPolicy: IfNotPresent name: container-apollo-config-server-prod ports: - protocol: TCP containerPort: 8080 volumeMounts: - name: volume-configmap-apollo-config-server-prod mountPath: /apollo-config-server/config/application-github.properties subPath: application-github.properties env: - name: APOLLO_CONFIG_SERVICE_NAME value: "service-apollo-config-server-prod.sre" readinessProbe: tcpSocket: port: 8080 initialDelaySeconds: 10 periodSeconds: 5 livenessProbe: tcpSocket: port: 8080 initialDelaySeconds: 120 periodSeconds: 10 dnsPolicy: ClusterFirst restartPolicy: Always
# # Copyright 2021 Apollo Authors # # Licensed 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. # --- # configmap for apollo-config-server-prod kind: ConfigMap apiVersion: v1 metadata: namespace: sre name: configmap-apollo-config-server-prod data: application-github.properties: | spring.datasource.url = jdbc:mysql://service-mysql-for-apollo-prod-env.sre:3306/ProdApolloConfigDB?characterEncoding=utf8 spring.datasource.username = FillInCorrectUser spring.datasource.password = FillInCorrectPassword eureka.service.url = http://statefulset-apollo-config-server-prod-0.service-apollo-meta-server-prod:8080/eureka/,http://statefulset-apollo-config-server-prod-1.service-apollo-meta-server-prod:8080/eureka/,http://statefulset-apollo-config-server-prod-2.service-apollo-meta-server-prod:8080/eureka/ --- kind: Service apiVersion: v1 metadata: namespace: sre name: service-apollo-meta-server-prod labels: app: service-apollo-meta-server-prod spec: ports: - protocol: TCP port: 8080 targetPort: 8080 selector: app: pod-apollo-config-server-prod type: ClusterIP clusterIP: None sessionAffinity: ClientIP --- kind: Service apiVersion: v1 metadata: namespace: sre name: service-apollo-config-server-prod labels: app: service-apollo-config-server-prod spec: ports: - protocol: TCP port: 8080 targetPort: 8080 nodePort: 30005 selector: app: pod-apollo-config-server-prod type: NodePort sessionAffinity: ClientIP --- kind: StatefulSet apiVersion: apps/v1 metadata: namespace: sre name: statefulset-apollo-config-server-prod labels: app: statefulset-apollo-config-server-prod spec: serviceName: service-apollo-meta-server-prod replicas: 3 selector: matchLabels: app: pod-apollo-config-server-prod updateStrategy: type: RollingUpdate template: metadata: labels: app: pod-apollo-config-server-prod spec: affinity: podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 100 podAffinityTerm: labelSelector: matchExpressions: - key: app operator: In values: - pod-apollo-config-server-prod topologyKey: kubernetes.io/hostname volumes: - name: volume-configmap-apollo-config-server-prod configMap: name: configmap-apollo-config-server-prod items: - key: application-github.properties path: application-github.properties containers: - image: apollo-config-server:v1.0.0 securityContext: privileged: true imagePullPolicy: IfNotPresent name: container-apollo-config-server-prod ports: - protocol: TCP containerPort: 8080 volumeMounts: - name: volume-configmap-apollo-config-server-prod mountPath: /apollo-config-server/config/application-github.properties subPath: application-github.properties env: - name: APOLLO_CONFIG_SERVICE_NAME value: "service-apollo-config-server-prod.sre" readinessProbe: tcpSocket: port: 8080 initialDelaySeconds: 10 periodSeconds: 5 livenessProbe: tcpSocket: port: 8080 initialDelaySeconds: 120 periodSeconds: 10 dnsPolicy: ClusterFirst restartPolicy: Always
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-adminservice/src/test/java/com/ctrip/framework/apollo/adminservice/controller/ControllerExceptionTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.adminservice.controller; import com.ctrip.framework.apollo.biz.service.AdminService; import com.ctrip.framework.apollo.biz.service.AppService; import com.ctrip.framework.apollo.common.dto.AppDTO; import com.ctrip.framework.apollo.common.entity.App; import com.ctrip.framework.apollo.common.exception.NotFoundException; import com.ctrip.framework.apollo.common.exception.ServiceException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import java.util.ArrayList; import java.util.List; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ControllerExceptionTest { private AppController appController; @Mock private AppService appService; @Mock private AdminService adminService; @Before public void setUp() { appController = new AppController(appService, adminService); } @Test(expected = NotFoundException.class) public void testFindNotExists() { when(appService.findOne(any(String.class))).thenReturn(null); appController.get("unexist"); } @Test(expected = NotFoundException.class) public void testDeleteNotExists() { when(appService.findOne(any(String.class))).thenReturn(null); appController.delete("unexist", null); } @Test public void testFindEmpty() { when(appService.findAll(any(Pageable.class))).thenReturn(new ArrayList<>()); Pageable pageable = PageRequest.of(0, 10); List<AppDTO> appDTOs = appController.find(null, pageable); Assert.assertNotNull(appDTOs); Assert.assertEquals(0, appDTOs.size()); appDTOs = appController.find("", pageable); Assert.assertNotNull(appDTOs); Assert.assertEquals(0, appDTOs.size()); } @Test public void testFindByName() { Pageable pageable = PageRequest.of(0, 10); List<AppDTO> appDTOs = appController.find("unexist", pageable); Assert.assertNotNull(appDTOs); Assert.assertEquals(0, appDTOs.size()); } @Test(expected = ServiceException.class) public void createFailed() { AppDTO dto = generateSampleDTOData(); when(appService.findOne(any(String.class))).thenReturn(null); when(adminService.createNewApp(any(App.class))) .thenThrow(new ServiceException("create app failed")); appController.create(dto); } private AppDTO generateSampleDTOData() { AppDTO dto = new AppDTO(); dto.setAppId("someAppId"); dto.setName("someName"); dto.setOwnerName("someOwner"); dto.setOwnerEmail("someOwner@ctrip.com"); dto.setDataChangeLastModifiedBy("test"); dto.setDataChangeCreatedBy("test"); return dto; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.adminservice.controller; import com.ctrip.framework.apollo.biz.service.AdminService; import com.ctrip.framework.apollo.biz.service.AppService; import com.ctrip.framework.apollo.common.dto.AppDTO; import com.ctrip.framework.apollo.common.entity.App; import com.ctrip.framework.apollo.common.exception.NotFoundException; import com.ctrip.framework.apollo.common.exception.ServiceException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import java.util.ArrayList; import java.util.List; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ControllerExceptionTest { private AppController appController; @Mock private AppService appService; @Mock private AdminService adminService; @Before public void setUp() { appController = new AppController(appService, adminService); } @Test(expected = NotFoundException.class) public void testFindNotExists() { when(appService.findOne(any(String.class))).thenReturn(null); appController.get("unexist"); } @Test(expected = NotFoundException.class) public void testDeleteNotExists() { when(appService.findOne(any(String.class))).thenReturn(null); appController.delete("unexist", null); } @Test public void testFindEmpty() { when(appService.findAll(any(Pageable.class))).thenReturn(new ArrayList<>()); Pageable pageable = PageRequest.of(0, 10); List<AppDTO> appDTOs = appController.find(null, pageable); Assert.assertNotNull(appDTOs); Assert.assertEquals(0, appDTOs.size()); appDTOs = appController.find("", pageable); Assert.assertNotNull(appDTOs); Assert.assertEquals(0, appDTOs.size()); } @Test public void testFindByName() { Pageable pageable = PageRequest.of(0, 10); List<AppDTO> appDTOs = appController.find("unexist", pageable); Assert.assertNotNull(appDTOs); Assert.assertEquals(0, appDTOs.size()); } @Test(expected = ServiceException.class) public void createFailed() { AppDTO dto = generateSampleDTOData(); when(appService.findOne(any(String.class))).thenReturn(null); when(adminService.createNewApp(any(App.class))) .thenThrow(new ServiceException("create app failed")); appController.create(dto); } private AppDTO generateSampleDTOData() { AppDTO dto = new AppDTO(); dto.setAppId("someAppId"); dto.setName("someName"); dto.setOwnerName("someOwner"); dto.setOwnerEmail("someOwner@ctrip.com"); dto.setDataChangeLastModifiedBy("test"); dto.setDataChangeCreatedBy("test"); return dto; } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./scripts/apollo-on-kubernetes/kubernetes/apollo-env-dev/service-mysql-for-apollo-dev-env.yaml
# # Copyright 2021 Apollo Authors # # Licensed 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. # --- # 为外部 mysql 服务设置 service kind: Service apiVersion: v1 metadata: namespace: sre name: service-mysql-for-apollo-dev-env labels: app: service-mysql-for-apollo-dev-env spec: ports: - protocol: TCP port: 3306 targetPort: 3306 type: ClusterIP sessionAffinity: None --- kind: Endpoints apiVersion: v1 metadata: namespace: sre name: service-mysql-for-apollo-dev-env subsets: - addresses: - ip: your-mysql-addresses ports: - protocol: TCP port: 3306
# # Copyright 2021 Apollo Authors # # Licensed 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. # --- # 为外部 mysql 服务设置 service kind: Service apiVersion: v1 metadata: namespace: sre name: service-mysql-for-apollo-dev-env labels: app: service-mysql-for-apollo-dev-env spec: ports: - protocol: TCP port: 3306 targetPort: 3306 type: ClusterIP sessionAffinity: None --- kind: Endpoints apiVersion: v1 metadata: namespace: sre name: service-mysql-for-apollo-dev-env subsets: - addresses: - ip: your-mysql-addresses ports: - protocol: TCP port: 3306
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/resources/static/views/component/confirm-dialog.html
<div class="modal fade" id="{{dialogId}}" tabindex="-1" role="dialog"> <!-- ~ Copyright 2021 Apollo Authors ~ ~ Licensed 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. ~ --> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header panel-primary"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">{{title}}</h4> </div> <div class="modal-body {{extraClass}}" ng-bind-html="detailAsHtml"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal" ng-show="showCancelBtn" ng-click="cancel()">{{'Common.Cancel' | translate }}</button> <button type="button" class="btn btn-danger" data-dismiss="modal" ng-click="confirm()"> {{confirmBtnText}} </button> </div> </div> </div> </div>
<div class="modal fade" id="{{dialogId}}" tabindex="-1" role="dialog"> <!-- ~ Copyright 2021 Apollo Authors ~ ~ Licensed 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. ~ --> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header panel-primary"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">{{title}}</h4> </div> <div class="modal-body {{extraClass}}" ng-bind-html="detailAsHtml"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal" ng-show="showCancelBtn" ng-click="cancel()">{{'Common.Cancel' | translate }}</button> <button type="button" class="btn btn-danger" data-dismiss="modal" ng-click="confirm()"> {{confirmBtnText}} </button> </div> </div> </div> </div>
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./scripts/sql/delta/v151-v160/apolloconfigdb-v151-v160.sql
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- # delta schema to upgrade apollo config db from v1.5.1 to v1.6.0 Use ApolloConfigDB; CREATE TABLE `AccessKey` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Secret` varchar(128) NOT NULL DEFAULT '' COMMENT 'Secret', `IsEnabled` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: enabled, 0: disabled', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(32) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(32) NOT NULL DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='访问密钥';
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- # delta schema to upgrade apollo config db from v1.5.1 to v1.6.0 Use ApolloConfigDB; CREATE TABLE `AccessKey` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Secret` varchar(128) NOT NULL DEFAULT '' COMMENT 'Secret', `IsEnabled` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: enabled, 0: disabled', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(32) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(32) NOT NULL DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='访问密钥';
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-common/src/test/java/com/ctrip/framework/apollo/common/utils/InputValidatorTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.common.utils; import static org.junit.Assert.*; import org.junit.Test; public class InputValidatorTest { @Test public void testValidClusterName() throws Exception { checkClusterName("some.cluster-_name.123", true); checkClusterName("some.cluster-_name.123.yml", true); checkClusterName("some.&.name", false); checkClusterName("", false); checkClusterName(null, false); } @Test public void testValidAppNamespaceName() throws Exception { checkAppNamespaceName("some.cluster-_name.123", true); checkAppNamespaceName("some.&.name", false); checkAppNamespaceName("", false); checkAppNamespaceName(null, false); checkAppNamespaceName("some.name.json", false); checkAppNamespaceName("some.name.yml", false); checkAppNamespaceName("some.name.yaml", false); checkAppNamespaceName("some.name.xml", false); checkAppNamespaceName("some.name.properties", false); } private void checkClusterName(String name, boolean valid) { assertEquals(valid, InputValidator.isValidClusterNamespace(name)); } private void checkAppNamespaceName(String name, boolean valid) { assertEquals(valid, InputValidator.isValidAppNamespace(name)); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.common.utils; import static org.junit.Assert.*; import org.junit.Test; public class InputValidatorTest { @Test public void testValidClusterName() throws Exception { checkClusterName("some.cluster-_name.123", true); checkClusterName("some.cluster-_name.123.yml", true); checkClusterName("some.&.name", false); checkClusterName("", false); checkClusterName(null, false); } @Test public void testValidAppNamespaceName() throws Exception { checkAppNamespaceName("some.cluster-_name.123", true); checkAppNamespaceName("some.&.name", false); checkAppNamespaceName("", false); checkAppNamespaceName(null, false); checkAppNamespaceName("some.name.json", false); checkAppNamespaceName("some.name.yml", false); checkAppNamespaceName("some.name.yaml", false); checkAppNamespaceName("some.name.xml", false); checkAppNamespaceName("some.name.properties", false); } private void checkClusterName(String name, boolean valid) { assertEquals(valid, InputValidator.isValidClusterNamespace(name)); } private void checkAppNamespaceName(String name, boolean valid) { assertEquals(valid, InputValidator.isValidAppNamespace(name)); } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-common/src/main/java/com/ctrip/framework/apollo/common/dto/GrayReleaseRuleItemDTO.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.common.dto; import com.google.common.collect.Sets; import java.util.Set; import static com.google.common.base.MoreObjects.toStringHelper; /** * @author Jason Song(song_s@ctrip.com) */ public class GrayReleaseRuleItemDTO { public static final String ALL_IP = "*"; private String clientAppId; private Set<String> clientIpList; public GrayReleaseRuleItemDTO(String clientAppId) { this(clientAppId, Sets.newHashSet()); } public GrayReleaseRuleItemDTO(String clientAppId, Set<String> clientIpList) { this.clientAppId = clientAppId; this.clientIpList = clientIpList; } public String getClientAppId() { return clientAppId; } public Set<String> getClientIpList() { return clientIpList; } public boolean matches(String clientAppId, String clientIp) { return appIdMatches(clientAppId) && ipMatches(clientIp); } private boolean appIdMatches(String clientAppId) { return this.clientAppId.equalsIgnoreCase(clientAppId); } private boolean ipMatches(String clientIp) { return this.clientIpList.contains(ALL_IP) || clientIpList.contains(clientIp); } @Override public String toString() { return toStringHelper(this).add("clientAppId", clientAppId) .add("clientIpList", clientIpList).toString(); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.common.dto; import com.google.common.collect.Sets; import java.util.Set; import static com.google.common.base.MoreObjects.toStringHelper; /** * @author Jason Song(song_s@ctrip.com) */ public class GrayReleaseRuleItemDTO { public static final String ALL_IP = "*"; private String clientAppId; private Set<String> clientIpList; public GrayReleaseRuleItemDTO(String clientAppId) { this(clientAppId, Sets.newHashSet()); } public GrayReleaseRuleItemDTO(String clientAppId, Set<String> clientIpList) { this.clientAppId = clientAppId; this.clientIpList = clientIpList; } public String getClientAppId() { return clientAppId; } public Set<String> getClientIpList() { return clientIpList; } public boolean matches(String clientAppId, String clientIp) { return appIdMatches(clientAppId) && ipMatches(clientIp); } private boolean appIdMatches(String clientAppId) { return this.clientAppId.equalsIgnoreCase(clientAppId); } private boolean ipMatches(String clientIp) { return this.clientIpList.contains(ALL_IP) || clientIpList.contains(clientIp); } @Override public String toString() { return toStringHelper(this).add("clientAppId", clientAppId) .add("clientIpList", clientIpList).toString(); } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./docs/zh/community/thank-you.md
# 致谢 <hr /> <img src="en/images/community/jetbrains.svg" alt="jetbrains" style="height: 80px; margin-right: 20px"> <img src="en/images/community/intellij-idea.svg" alt="intellij-idea" style="width: 75px" > Apollo 团队使用 [IntelliJ IDEA](https://www.jetbrains.com/idea/) 开发开源项目,非常感谢 [JetBrains](https://www.jetbrains.com/) 赞助许可证。 <hr /> <img src="en/images/community/docsify.svg" alt="docsify" style="height: 80px"> Apollo 团队使用 [docsify](https://docsify.js.org/) 生成文档站点。
# 致谢 <hr /> <img src="en/images/community/jetbrains.svg" alt="jetbrains" style="height: 80px; margin-right: 20px"> <img src="en/images/community/intellij-idea.svg" alt="intellij-idea" style="width: 75px" > Apollo 团队使用 [IntelliJ IDEA](https://www.jetbrains.com/idea/) 开发开源项目,非常感谢 [JetBrains](https://www.jetbrains.com/) 赞助许可证。 <hr /> <img src="en/images/community/docsify.svg" alt="docsify" style="height: 80px"> Apollo 团队使用 [docsify](https://docsify.js.org/) 生成文档站点。
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-common/pom.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright 2021 Apollo Authors ~ ~ Licensed 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. ~ --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo</artifactId> <version>${revision}</version> <relativePath>../pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>apollo-common</artifactId> <name>Apollo Common</name> <properties> <github.path>${project.artifactId}</github.path> </properties> <dependencies> <dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-core</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons</artifactId> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- logback dependencies--> <dependency> <groupId>org.codehaus.janino</groupId> <artifactId>janino</artifactId> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> </dependency> <!-- Micrometer core dependecy --> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-core</artifactId> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency> </dependencies> </project>
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright 2021 Apollo Authors ~ ~ Licensed 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. ~ --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo</artifactId> <version>${revision}</version> <relativePath>../pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>apollo-common</artifactId> <name>Apollo Common</name> <properties> <github.path>${project.artifactId}</github.path> </properties> <dependencies> <dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-core</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons</artifactId> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- logback dependencies--> <dependency> <groupId>org.codehaus.janino</groupId> <artifactId>janino</artifactId> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> </dependency> <!-- Micrometer core dependecy --> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-core</artifactId> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency> </dependencies> </project>
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/NamespaceGrayDelReleaseDTO.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.openapi.dto; import java.util.Set; public class NamespaceGrayDelReleaseDTO extends NamespaceReleaseDTO { private Set<String> grayDelKeys; public Set<String> getGrayDelKeys() { return grayDelKeys; } public void setGrayDelKeys(Set<String> grayDelKeys) { this.grayDelKeys = grayDelKeys; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.openapi.dto; import java.util.Set; public class NamespaceGrayDelReleaseDTO extends NamespaceReleaseDTO { private Set<String> grayDelKeys; public Set<String> getGrayDelKeys() { return grayDelKeys; } public void setGrayDelKeys(Set<String> grayDelKeys) { this.grayDelKeys = grayDelKeys; } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-client/src/test/resources/spring/yaml/case2.yml
# # Copyright 2021 Apollo Authors # # Licensed 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. # batch: 2000
# # Copyright 2021 Apollo Authors # # Licensed 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. # batch: 2000
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-demo/src/main/resources/application.yml
# # Copyright 2021 Apollo Authors # # Licensed 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. # apollo: bootstrap: enabled: true eagerLoad: enabled: true # will inject 'application' and 'TEST1.apollo' namespaces in bootstrap phase namespaces: application,TEST1.apollo,application.yaml
# # Copyright 2021 Apollo Authors # # Licensed 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. # apollo: bootstrap: enabled: true eagerLoad: enabled: true # will inject 'application' and 'TEST1.apollo' namespaces in bootstrap phase namespaces: application,TEST1.apollo,application.yaml
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ApolloThreadFactory.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.core.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; public class ApolloThreadFactory implements ThreadFactory { private static Logger log = LoggerFactory.getLogger(ApolloThreadFactory.class); private final AtomicLong threadNumber = new AtomicLong(1); private final String namePrefix; private final boolean daemon; private static final ThreadGroup threadGroup = new ThreadGroup("Apollo"); public static ThreadGroup getThreadGroup() { return threadGroup; } public static ThreadFactory create(String namePrefix, boolean daemon) { return new ApolloThreadFactory(namePrefix, daemon); } public static boolean waitAllShutdown(int timeoutInMillis) { ThreadGroup group = getThreadGroup(); Thread[] activeThreads = new Thread[group.activeCount()]; group.enumerate(activeThreads); Set<Thread> alives = new HashSet<>(Arrays.asList(activeThreads)); Set<Thread> dies = new HashSet<>(); log.info("Current ACTIVE thread count is: {}", alives.size()); long expire = System.currentTimeMillis() + timeoutInMillis; while (System.currentTimeMillis() < expire) { classify(alives, dies, new ClassifyStandard<Thread>() { @Override public boolean satisfy(Thread thread) { return !thread.isAlive() || thread.isInterrupted() || thread.isDaemon(); } }); if (alives.size() > 0) { log.info("Alive apollo threads: {}", alives); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException ex) { // ignore } } else { log.info("All apollo threads are shutdown."); return true; } } log.warn("Some apollo threads are still alive but expire time has reached, alive threads: {}", alives); return false; } private interface ClassifyStandard<T> { boolean satisfy(T thread); } private static <T> void classify(Set<T> src, Set<T> des, ClassifyStandard<T> standard) { Set<T> set = new HashSet<>(); for (T t : src) { if (standard.satisfy(t)) { set.add(t); } } src.removeAll(set); des.addAll(set); } private ApolloThreadFactory(String namePrefix, boolean daemon) { this.namePrefix = namePrefix; this.daemon = daemon; } public Thread newThread(Runnable runnable) { Thread thread = new Thread(threadGroup, runnable,// threadGroup.getName() + "-" + namePrefix + "-" + threadNumber.getAndIncrement()); thread.setDaemon(daemon); if (thread.getPriority() != Thread.NORM_PRIORITY) { thread.setPriority(Thread.NORM_PRIORITY); } return thread; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.core.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; public class ApolloThreadFactory implements ThreadFactory { private static Logger log = LoggerFactory.getLogger(ApolloThreadFactory.class); private final AtomicLong threadNumber = new AtomicLong(1); private final String namePrefix; private final boolean daemon; private static final ThreadGroup threadGroup = new ThreadGroup("Apollo"); public static ThreadGroup getThreadGroup() { return threadGroup; } public static ThreadFactory create(String namePrefix, boolean daemon) { return new ApolloThreadFactory(namePrefix, daemon); } public static boolean waitAllShutdown(int timeoutInMillis) { ThreadGroup group = getThreadGroup(); Thread[] activeThreads = new Thread[group.activeCount()]; group.enumerate(activeThreads); Set<Thread> alives = new HashSet<>(Arrays.asList(activeThreads)); Set<Thread> dies = new HashSet<>(); log.info("Current ACTIVE thread count is: {}", alives.size()); long expire = System.currentTimeMillis() + timeoutInMillis; while (System.currentTimeMillis() < expire) { classify(alives, dies, new ClassifyStandard<Thread>() { @Override public boolean satisfy(Thread thread) { return !thread.isAlive() || thread.isInterrupted() || thread.isDaemon(); } }); if (alives.size() > 0) { log.info("Alive apollo threads: {}", alives); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException ex) { // ignore } } else { log.info("All apollo threads are shutdown."); return true; } } log.warn("Some apollo threads are still alive but expire time has reached, alive threads: {}", alives); return false; } private interface ClassifyStandard<T> { boolean satisfy(T thread); } private static <T> void classify(Set<T> src, Set<T> des, ClassifyStandard<T> standard) { Set<T> set = new HashSet<>(); for (T t : src) { if (standard.satisfy(t)) { set.add(t); } } src.removeAll(set); des.addAll(set); } private ApolloThreadFactory(String namePrefix, boolean daemon) { this.namePrefix = namePrefix; this.daemon = daemon; } public Thread newThread(Runnable runnable) { Thread thread = new Thread(threadGroup, runnable,// threadGroup.getName() + "-" + namePrefix + "-" + threadNumber.getAndIncrement()); thread.setDaemon(daemon); if (thread.getPriority() != Thread.NORM_PRIORITY) { thread.setPriority(Thread.NORM_PRIORITY); } return thread; } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/ReleaseHistoryController.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.controller; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.portal.component.PermissionValidator; import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO; import com.ctrip.framework.apollo.portal.service.ReleaseHistoryService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Collections; import java.util.List; @RestController public class ReleaseHistoryController { private final ReleaseHistoryService releaseHistoryService; private final PermissionValidator permissionValidator; public ReleaseHistoryController(final ReleaseHistoryService releaseHistoryService, final PermissionValidator permissionValidator) { this.releaseHistoryService = releaseHistoryService; this.permissionValidator = permissionValidator; } @GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/releases/histories") public List<ReleaseHistoryBO> findReleaseHistoriesByNamespace(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "size", defaultValue = "10") int size) { if (permissionValidator.shouldHideConfigToCurrentUser(appId, env, namespaceName)) { return Collections.emptyList(); } return releaseHistoryService.findNamespaceReleaseHistory(appId, Env.valueOf(env), clusterName ,namespaceName, page, size); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.controller; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.portal.component.PermissionValidator; import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO; import com.ctrip.framework.apollo.portal.service.ReleaseHistoryService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Collections; import java.util.List; @RestController public class ReleaseHistoryController { private final ReleaseHistoryService releaseHistoryService; private final PermissionValidator permissionValidator; public ReleaseHistoryController(final ReleaseHistoryService releaseHistoryService, final PermissionValidator permissionValidator) { this.releaseHistoryService = releaseHistoryService; this.permissionValidator = permissionValidator; } @GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/releases/histories") public List<ReleaseHistoryBO> findReleaseHistoriesByNamespace(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "size", defaultValue = "10") int size) { if (permissionValidator.shouldHideConfigToCurrentUser(appId, env, namespaceName)) { return Collections.emptyList(); } return releaseHistoryService.findNamespaceReleaseHistory(appId, Env.valueOf(env), clusterName ,namespaceName, page, size); } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-core/src/test/java/com/ctrip/framework/foundation/FoundationTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.foundation; import static org.junit.Assert.assertTrue; import com.ctrip.framework.foundation.Foundation; import com.ctrip.framework.foundation.internals.provider.DefaultApplicationProvider; import com.ctrip.framework.foundation.internals.provider.DefaultServerProvider; import org.junit.Assert; import org.junit.Test; public class FoundationTest { @Test public void testApp() { assertTrue(Foundation.app() instanceof DefaultApplicationProvider); } @Test public void testServer() { assertTrue(Foundation.server() instanceof DefaultServerProvider); } @Test public void testNet() { // 获取本机IP和HostName String hostAddress = Foundation.net().getHostAddress(); String hostName = Foundation.net().getHostName(); Assert.assertNotNull("No host address detected.", hostAddress); Assert.assertNotNull("No host name resolved.", hostName); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.foundation; import static org.junit.Assert.assertTrue; import com.ctrip.framework.foundation.Foundation; import com.ctrip.framework.foundation.internals.provider.DefaultApplicationProvider; import com.ctrip.framework.foundation.internals.provider.DefaultServerProvider; import org.junit.Assert; import org.junit.Test; public class FoundationTest { @Test public void testApp() { assertTrue(Foundation.app() instanceof DefaultApplicationProvider); } @Test public void testServer() { assertTrue(Foundation.server() instanceof DefaultServerProvider); } @Test public void testNet() { // 获取本机IP和HostName String hostAddress = Foundation.net().getHostAddress(); String hostName = Foundation.net().getHostName(); Assert.assertNotNull("No host address detected.", hostAddress); Assert.assertNotNull("No host name resolved.", hostName); } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-client/src/test/resources/yaml/case4.yaml
# # Copyright 2021 Apollo Authors # # Licensed 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. # --- # document start # Comments in YAML look like this. ################ # SCALAR TYPES # ################ # Our root object (which continues for the entire document) will be a map, # which is equivalent to a dictionary, hash or object in other languages. key: value another_key: Another value goes here. a_number_value: 100 scientific_notation: 1e+12 # The number 1 will be interpreted as a number, not a boolean. if you want # it to be interpreted as a boolean, use true boolean: true null_value: null key with spaces: value # Notice that strings don't need to be quoted. However, they can be. however: 'A string, enclosed in quotes.' 'Keys can be quoted too.': "Useful if you want to put a ':' in your key." single quotes: 'have ''one'' escape pattern' double quotes: "have many: \", \0, \t, \u263A, \x0d\x0a == \r\n, and more." # Multiple-line strings can be written either as a 'literal block' (using |), # or a 'folded block' (using '>'). literal_block: | This entire block of text will be the value of the 'literal_block' key, with line breaks being preserved. The literal continues until de-dented, and the leading indentation is stripped. Any lines that are 'more-indented' keep the rest of their indentation - these lines will be indented by 4 spaces. folded_style: > This entire block of text will be the value of 'folded_style', but this time, all newlines will be replaced with a single space. Blank lines, like above, are converted to a newline character. 'More-indented' lines keep their newlines, too - this text will appear over two lines. #################### # COLLECTION TYPES # #################### # Nesting uses indentation. 2 space indent is preferred (but not required). a_nested_map: key: value another_key: Another Value another_nested_map: hello: hello # Maps don't have to have string keys. 0.25: a float key # Keys can also be complex, like multi-line objects # We use ? followed by a space to indicate the start of a complex key. ? | This is a key that has multiple lines : and this is its value # YAML also allows mapping between sequences with the complex key syntax # Some language parsers might complain # An example ? - Manchester United - Real Madrid : [2001-01-01, 2002-02-02] # Sequences (equivalent to lists or arrays) look like this # (note that the '-' counts as indentation): a_sequence: - Item 1 - Item 2 - 0.5 # sequences can contain disparate types. - Item 4 - key: value another_key: another_value - - This is a sequence - inside another sequence - - - Nested sequence indicators - can be collapsed # Since YAML is a superset of JSON, you can also write JSON-style maps and # sequences: json_map: {"key": "value"} json_seq: [3, 2, 1, "takeoff"] and quotes are optional: {key: [3, 2, 1, takeoff]} ####################### # EXTRA YAML FEATURES # ####################### # YAML also has a handy feature called 'anchors', which let you easily duplicate # content across your document. Both of these keys will have the same value: anchored_content: &anchor_name This string will appear as the value of two keys. other_anchor: *anchor_name # Anchors can be used to duplicate/inherit properties base: &base name: Everyone has same name # The regexp << is called Merge Key Language-Independent Type. It is used to # indicate that all the keys of one or more specified maps should be inserted # into the current map. foo: &foo <<: *base age: 10 bar: &bar <<: *base age: 20 # foo and bar would also have name: Everyone has same name # YAML also has tags, which you can use to explicitly declare types. explicit_string: !!str 0.5 #################### # EXTRA YAML TYPES # #################### # Strings and numbers aren't the only scalars that YAML can understand. # ISO-formatted date and datetime literals are also parsed. datetime: 2001-12-15T02:59:43.1Z datetime_with_spaces: 2001-12-14 21:59:43.10 -5 date: 2002-12-14 # YAML also has a set type, which looks like this: set: ? item1 ? item2 ? item3 or: {item1, item2, item3} # Sets are just maps with null values; the above is equivalent to: set2: item1: null item2: null item3: null ... # document end
# # Copyright 2021 Apollo Authors # # Licensed 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. # --- # document start # Comments in YAML look like this. ################ # SCALAR TYPES # ################ # Our root object (which continues for the entire document) will be a map, # which is equivalent to a dictionary, hash or object in other languages. key: value another_key: Another value goes here. a_number_value: 100 scientific_notation: 1e+12 # The number 1 will be interpreted as a number, not a boolean. if you want # it to be interpreted as a boolean, use true boolean: true null_value: null key with spaces: value # Notice that strings don't need to be quoted. However, they can be. however: 'A string, enclosed in quotes.' 'Keys can be quoted too.': "Useful if you want to put a ':' in your key." single quotes: 'have ''one'' escape pattern' double quotes: "have many: \", \0, \t, \u263A, \x0d\x0a == \r\n, and more." # Multiple-line strings can be written either as a 'literal block' (using |), # or a 'folded block' (using '>'). literal_block: | This entire block of text will be the value of the 'literal_block' key, with line breaks being preserved. The literal continues until de-dented, and the leading indentation is stripped. Any lines that are 'more-indented' keep the rest of their indentation - these lines will be indented by 4 spaces. folded_style: > This entire block of text will be the value of 'folded_style', but this time, all newlines will be replaced with a single space. Blank lines, like above, are converted to a newline character. 'More-indented' lines keep their newlines, too - this text will appear over two lines. #################### # COLLECTION TYPES # #################### # Nesting uses indentation. 2 space indent is preferred (but not required). a_nested_map: key: value another_key: Another Value another_nested_map: hello: hello # Maps don't have to have string keys. 0.25: a float key # Keys can also be complex, like multi-line objects # We use ? followed by a space to indicate the start of a complex key. ? | This is a key that has multiple lines : and this is its value # YAML also allows mapping between sequences with the complex key syntax # Some language parsers might complain # An example ? - Manchester United - Real Madrid : [2001-01-01, 2002-02-02] # Sequences (equivalent to lists or arrays) look like this # (note that the '-' counts as indentation): a_sequence: - Item 1 - Item 2 - 0.5 # sequences can contain disparate types. - Item 4 - key: value another_key: another_value - - This is a sequence - inside another sequence - - - Nested sequence indicators - can be collapsed # Since YAML is a superset of JSON, you can also write JSON-style maps and # sequences: json_map: {"key": "value"} json_seq: [3, 2, 1, "takeoff"] and quotes are optional: {key: [3, 2, 1, takeoff]} ####################### # EXTRA YAML FEATURES # ####################### # YAML also has a handy feature called 'anchors', which let you easily duplicate # content across your document. Both of these keys will have the same value: anchored_content: &anchor_name This string will appear as the value of two keys. other_anchor: *anchor_name # Anchors can be used to duplicate/inherit properties base: &base name: Everyone has same name # The regexp << is called Merge Key Language-Independent Type. It is used to # indicate that all the keys of one or more specified maps should be inserted # into the current map. foo: &foo <<: *base age: 10 bar: &bar <<: *base age: 20 # foo and bar would also have name: Everyone has same name # YAML also has tags, which you can use to explicitly declare types. explicit_string: !!str 0.5 #################### # EXTRA YAML TYPES # #################### # Strings and numbers aren't the only scalars that YAML can understand. # ISO-formatted date and datetime literals are also parsed. datetime: 2001-12-15T02:59:43.1Z datetime_with_spaces: 2001-12-14 21:59:43.10 -5 date: 2002-12-14 # YAML also has a set type, which looks like this: set: ? item1 ? item2 ? item3 or: {item1, item2, item3} # Sets are just maps with null values; the above is equivalent to: set2: item1: null item2: null item3: null ... # document end
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-biz/src/test/resources/data.sql
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- INSERT INTO AppNamespace (AppId, Name, IsPublic) VALUES ('100003171', 'application', false); INSERT INTO AppNamespace (AppId, Name, IsPublic) VALUES ('100003171', 'fx.apollo.config', true); INSERT INTO AppNamespace (AppId, Name, IsPublic) VALUES ('100003172', 'application', false); INSERT INTO AppNamespace (AppId, Name, IsPublic) VALUES ('100003172', 'fx.apollo.admin', true); INSERT INTO AppNamespace (AppId, Name, IsPublic) VALUES ('100003173', 'application', false); INSERT INTO AppNamespace (AppId, Name, IsPublic) VALUES ('100003173', 'fx.apollo.portal', true); INSERT INTO AppNamespace (AppID, Name, IsPublic) VALUES ('fxhermesproducer', 'fx.hermes.producer', true);
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- INSERT INTO AppNamespace (AppId, Name, IsPublic) VALUES ('100003171', 'application', false); INSERT INTO AppNamespace (AppId, Name, IsPublic) VALUES ('100003171', 'fx.apollo.config', true); INSERT INTO AppNamespace (AppId, Name, IsPublic) VALUES ('100003172', 'application', false); INSERT INTO AppNamespace (AppId, Name, IsPublic) VALUES ('100003172', 'fx.apollo.admin', true); INSERT INTO AppNamespace (AppId, Name, IsPublic) VALUES ('100003173', 'application', false); INSERT INTO AppNamespace (AppId, Name, IsPublic) VALUES ('100003173', 'fx.apollo.portal', true); INSERT INTO AppNamespace (AppID, Name, IsPublic) VALUES ('fxhermesproducer', 'fx.hermes.producer', true);
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface3
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/resources/static/scripts/services/SystemInfoService.js
/* * Copyright 2021 Apollo Authors * * Licensed 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. * */ appService.service('SystemInfoService', ['$resource', '$q', 'AppUtil', function ($resource, $q, AppUtil) { var system_info_resource = $resource('', {}, { load_system_info: { method: 'GET', url: AppUtil.prefixPath() + '/system-info' }, check_health: { method: 'GET', url: AppUtil.prefixPath() + '/system-info/health' } }); return { load_system_info: function () { var d = $q.defer(); system_info_resource.load_system_info({}, function (result) { d.resolve(result); }, function (result) { d.reject(result); }); return d.promise; }, check_health: function (instanceId, host) { var d = $q.defer(); system_info_resource.check_health({ instanceId: instanceId }, function (result) { d.resolve(result); }, function (result) { d.reject(result); }); return d.promise; } } }]);
/* * Copyright 2021 Apollo Authors * * Licensed 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. * */ appService.service('SystemInfoService', ['$resource', '$q', 'AppUtil', function ($resource, $q, AppUtil) { var system_info_resource = $resource('', {}, { load_system_info: { method: 'GET', url: AppUtil.prefixPath() + '/system-info' }, check_health: { method: 'GET', url: AppUtil.prefixPath() + '/system-info/health' } }); return { load_system_info: function () { var d = $q.defer(); system_info_resource.load_system_info({}, function (result) { d.resolve(result); }, function (result) { d.reject(result); }); return d.promise; }, check_health: function (instanceId, host) { var d = $q.defer(); system_info_resource.check_health({ instanceId: instanceId }, function (result) { d.resolve(result); }, function (result) { d.reject(result); }); return d.promise; } } }]);
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/repository/RoleRepository.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.repository; import com.ctrip.framework.apollo.portal.entity.po.Role; import java.util.List; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; /** * @author Jason Song(song_s@ctrip.com) */ public interface RoleRepository extends PagingAndSortingRepository<Role, Long> { /** * find role by role name */ Role findTopByRoleName(String roleName); @Query("SELECT r.id from Role r where (r.roleName = CONCAT('Master+', ?1) " + "OR r.roleName like CONCAT('ModifyNamespace+', ?1, '+%') " + "OR r.roleName like CONCAT('ReleaseNamespace+', ?1, '+%') " + "OR r.roleName = CONCAT('ManageAppMaster+', ?1))") List<Long> findRoleIdsByAppId(String appId); @Query("SELECT r.id from Role r where (r.roleName = CONCAT('ModifyNamespace+', ?1, '+', ?2) " + "OR r.roleName = CONCAT('ReleaseNamespace+', ?1, '+', ?2))") List<Long> findRoleIdsByAppIdAndNamespace(String appId, String namespaceName); @Modifying @Query("UPDATE Role SET IsDeleted=1, DataChange_LastModifiedBy = ?2 WHERE Id in ?1") Integer batchDelete(List<Long> roleIds, String operator); }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.repository; import com.ctrip.framework.apollo.portal.entity.po.Role; import java.util.List; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; /** * @author Jason Song(song_s@ctrip.com) */ public interface RoleRepository extends PagingAndSortingRepository<Role, Long> { /** * find role by role name */ Role findTopByRoleName(String roleName); @Query("SELECT r.id from Role r where (r.roleName = CONCAT('Master+', ?1) " + "OR r.roleName like CONCAT('ModifyNamespace+', ?1, '+%') " + "OR r.roleName like CONCAT('ReleaseNamespace+', ?1, '+%') " + "OR r.roleName = CONCAT('ManageAppMaster+', ?1))") List<Long> findRoleIdsByAppId(String appId); @Query("SELECT r.id from Role r where (r.roleName = CONCAT('ModifyNamespace+', ?1, '+', ?2) " + "OR r.roleName = CONCAT('ReleaseNamespace+', ?1, '+', ?2))") List<Long> findRoleIdsByAppIdAndNamespace(String appId, String namespaceName); @Modifying @Query("UPDATE Role SET IsDeleted=1, DataChange_LastModifiedBy = ?2 WHERE Id in ?1") Integer batchDelete(List<Long> roleIds, String operator); }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./doc/images/app-permission-entry.png
PNG  IHDRgO9MsJ iCCPICC ProfileHT̤ZBޑN5A: %A (""X**EւX- , Xxyߜo|on=G(LeHd\QLS4n%017=>EqxZ!ˋMK禠|3\(M:C8(Eh(YY=3'$ QG=ZgfrQ eS/@eGnr>F))|eщfDÉ.Ld#%Y< 4) " td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0 (] 0C1㧵~Z<u%O? K1M>b ^˃Ͻ2Y7^EۧSc<kgWnf'n @,=W^5Mj; @`u(֜K 0^9^ @Ϊ^#@JJ1 @U gUO @ g͘z  @ @fL @@Ykp @@iYi3^ @j58 @4᬴S/ PpV PpVڌZ@8zz (M7oM{ @f׌6_ @dp[33 @), Y@8 ; @@J@8Kh#@d2 R: @#@6 @@f,3 @), Y@8 ; @@J@8Kh#@d2 R: @#@6 @@f,3 @), Y7MYv:IENDB`
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenGrayReleaseRuleDTO.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.openapi.dto; import java.util.Set; public class OpenGrayReleaseRuleDTO extends BaseDTO{ private String appId; private String clusterName; private String namespaceName; private String branchName; private Set<OpenGrayReleaseRuleItemDTO> ruleItems; public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getNamespaceName() { return namespaceName; } public void setNamespaceName(String namespaceName) { this.namespaceName = namespaceName; } public String getBranchName() { return branchName; } public void setBranchName(String branchName) { this.branchName = branchName; } public Set<OpenGrayReleaseRuleItemDTO> getRuleItems() { return ruleItems; } public void setRuleItems(Set<OpenGrayReleaseRuleItemDTO> ruleItems) { this.ruleItems = ruleItems; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.openapi.dto; import java.util.Set; public class OpenGrayReleaseRuleDTO extends BaseDTO{ private String appId; private String clusterName; private String namespaceName; private String branchName; private Set<OpenGrayReleaseRuleItemDTO> ruleItems; public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getClusterName() { return clusterName; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public String getNamespaceName() { return namespaceName; } public void setNamespaceName(String namespaceName) { this.namespaceName = namespaceName; } public String getBranchName() { return branchName; } public void setBranchName(String branchName) { this.branchName = branchName; } public Set<OpenGrayReleaseRuleItemDTO> getRuleItems() { return ruleItems; } public void setRuleItems(Set<OpenGrayReleaseRuleItemDTO> ruleItems) { this.ruleItems = ruleItems; } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-adminservice/src/test/java/com/ctrip/framework/apollo/adminservice/controller/ControllerIntegrationExceptionTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.adminservice.controller; import com.google.gson.Gson; import com.ctrip.framework.apollo.biz.service.AdminService; import com.ctrip.framework.apollo.biz.service.AppService; import com.ctrip.framework.apollo.common.dto.AppDTO; import com.ctrip.framework.apollo.common.entity.App; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.Sql.ExecutionPhase; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.client.HttpStatusCodeException; import java.util.Map; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; public class ControllerIntegrationExceptionTest extends AbstractControllerTest { @Autowired AppController appController; @Mock AdminService adminService; private Object realAdminService; @Autowired AppService appService; private static final Gson GSON = new Gson(); @Before public void setUp() { MockitoAnnotations.initMocks(this); realAdminService = ReflectionTestUtils.getField(appController, "adminService"); ReflectionTestUtils.setField(appController, "adminService", adminService); } @After public void tearDown() throws Exception { ReflectionTestUtils.setField(appController, "adminService", realAdminService); } private String getBaseAppUrl() { return "http://localhost:" + port + "/apps/"; } @Test @Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD) public void testCreateFailed() { AppDTO dto = generateSampleDTOData(); when(adminService.createNewApp(any(App.class))).thenThrow(new RuntimeException("save failed")); try { restTemplate.postForEntity(getBaseAppUrl(), dto, AppDTO.class); } catch (HttpStatusCodeException e) { @SuppressWarnings("unchecked") Map<String, String> attr = GSON.fromJson(e.getResponseBodyAsString(), Map.class); Assert.assertEquals("save failed", attr.get("message")); } App savedApp = appService.findOne(dto.getAppId()); Assert.assertNull(savedApp); } private AppDTO generateSampleDTOData() { AppDTO dto = new AppDTO(); dto.setAppId("someAppId"); dto.setName("someName"); dto.setOwnerName("someOwner"); dto.setOwnerEmail("someOwner@ctrip.com"); return dto; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.adminservice.controller; import com.google.gson.Gson; import com.ctrip.framework.apollo.biz.service.AdminService; import com.ctrip.framework.apollo.biz.service.AppService; import com.ctrip.framework.apollo.common.dto.AppDTO; import com.ctrip.framework.apollo.common.entity.App; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.Sql.ExecutionPhase; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.client.HttpStatusCodeException; import java.util.Map; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; public class ControllerIntegrationExceptionTest extends AbstractControllerTest { @Autowired AppController appController; @Mock AdminService adminService; private Object realAdminService; @Autowired AppService appService; private static final Gson GSON = new Gson(); @Before public void setUp() { MockitoAnnotations.initMocks(this); realAdminService = ReflectionTestUtils.getField(appController, "adminService"); ReflectionTestUtils.setField(appController, "adminService", adminService); } @After public void tearDown() throws Exception { ReflectionTestUtils.setField(appController, "adminService", realAdminService); } private String getBaseAppUrl() { return "http://localhost:" + port + "/apps/"; } @Test @Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD) public void testCreateFailed() { AppDTO dto = generateSampleDTOData(); when(adminService.createNewApp(any(App.class))).thenThrow(new RuntimeException("save failed")); try { restTemplate.postForEntity(getBaseAppUrl(), dto, AppDTO.class); } catch (HttpStatusCodeException e) { @SuppressWarnings("unchecked") Map<String, String> attr = GSON.fromJson(e.getResponseBodyAsString(), Map.class); Assert.assertEquals("save failed", attr.get("message")); } App savedApp = appService.findOne(dto.getAppId()); Assert.assertNull(savedApp); } private AppDTO generateSampleDTOData() { AppDTO dto = new AppDTO(); dto.setAppId("someAppId"); dto.setName("someName"); dto.setOwnerName("someOwner"); dto.setOwnerEmail("someOwner@ctrip.com"); return dto; } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-core/src/test/java/com/ctrip/framework/apollo/core/signature/SignatureTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.core.signature; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.google.common.net.HttpHeaders; import java.util.Map; import org.junit.Test; /** * @author nisiyong */ public class SignatureTest { @Test public void testSignature() { String timestamp = "1576478257344"; String pathWithQuery = "/configs/100004458/default/application?ip=10.0.0.1"; String secret = "df23df3f59884980844ff3dada30fa97"; String actualSignature = Signature.signature(timestamp, pathWithQuery, secret); String expectedSignature = "EoKyziXvKqzHgwx+ijDJwgVTDgE="; assertEquals(expectedSignature, actualSignature); } @Test public void testBuildHttpHeaders() { String url = "http://10.0.0.1:8080/configs/100004458/default/application?ip=10.0.0.1"; String appId = "100004458"; String secret = "df23df3f59884980844ff3dada30fa97"; Map<String, String> actualHttpHeaders = Signature.buildHttpHeaders(url, appId, secret); assertTrue(actualHttpHeaders.containsKey(HttpHeaders.AUTHORIZATION)); assertTrue(actualHttpHeaders.containsKey(Signature.HTTP_HEADER_TIMESTAMP)); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.core.signature; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.google.common.net.HttpHeaders; import java.util.Map; import org.junit.Test; /** * @author nisiyong */ public class SignatureTest { @Test public void testSignature() { String timestamp = "1576478257344"; String pathWithQuery = "/configs/100004458/default/application?ip=10.0.0.1"; String secret = "df23df3f59884980844ff3dada30fa97"; String actualSignature = Signature.signature(timestamp, pathWithQuery, secret); String expectedSignature = "EoKyziXvKqzHgwx+ijDJwgVTDgE="; assertEquals(expectedSignature, actualSignature); } @Test public void testBuildHttpHeaders() { String url = "http://10.0.0.1:8080/configs/100004458/default/application?ip=10.0.0.1"; String appId = "100004458"; String secret = "df23df3f59884980844ff3dada30fa97"; Map<String, String> actualHttpHeaders = Signature.buildHttpHeaders(url, appId, secret); assertTrue(actualHttpHeaders.containsKey(HttpHeaders.AUTHORIZATION)); assertTrue(actualHttpHeaders.containsKey(Signature.HTTP_HEADER_TIMESTAMP)); } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultRolePermissionService.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.defaultimpl; import com.ctrip.framework.apollo.openapi.repository.ConsumerRoleRepository; import com.ctrip.framework.apollo.portal.component.config.PortalConfig; import com.ctrip.framework.apollo.portal.entity.bo.UserInfo; import com.ctrip.framework.apollo.portal.entity.po.Permission; import com.ctrip.framework.apollo.portal.entity.po.Role; import com.ctrip.framework.apollo.portal.entity.po.RolePermission; import com.ctrip.framework.apollo.portal.entity.po.UserRole; import com.ctrip.framework.apollo.portal.repository.PermissionRepository; import com.ctrip.framework.apollo.portal.repository.RolePermissionRepository; import com.ctrip.framework.apollo.portal.repository.RoleRepository; import com.ctrip.framework.apollo.portal.repository.UserRoleRepository; import com.ctrip.framework.apollo.portal.service.RolePermissionService; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.StreamSupport; /** * Created by timothy on 2017/4/26. */ public class DefaultRolePermissionService implements RolePermissionService { @Autowired private RoleRepository roleRepository; @Autowired private RolePermissionRepository rolePermissionRepository; @Autowired private UserRoleRepository userRoleRepository; @Autowired private PermissionRepository permissionRepository; @Autowired private PortalConfig portalConfig; @Autowired private ConsumerRoleRepository consumerRoleRepository; /** * Create role with permissions, note that role name should be unique */ @Transactional public Role createRoleWithPermissions(Role role, Set<Long> permissionIds) { Role current = findRoleByRoleName(role.getRoleName()); Preconditions.checkState(current == null, "Role %s already exists!", role.getRoleName()); Role createdRole = roleRepository.save(role); if (!CollectionUtils.isEmpty(permissionIds)) { Iterable<RolePermission> rolePermissions = permissionIds.stream().map(permissionId -> { RolePermission rolePermission = new RolePermission(); rolePermission.setRoleId(createdRole.getId()); rolePermission.setPermissionId(permissionId); rolePermission.setDataChangeCreatedBy(createdRole.getDataChangeCreatedBy()); rolePermission.setDataChangeLastModifiedBy(createdRole.getDataChangeLastModifiedBy()); return rolePermission; }).collect(Collectors.toList()); rolePermissionRepository.saveAll(rolePermissions); } return createdRole; } /** * Assign role to users * * @return the users assigned roles */ @Transactional public Set<String> assignRoleToUsers(String roleName, Set<String> userIds, String operatorUserId) { Role role = findRoleByRoleName(roleName); Preconditions.checkState(role != null, "Role %s doesn't exist!", roleName); List<UserRole> existedUserRoles = userRoleRepository.findByUserIdInAndRoleId(userIds, role.getId()); Set<String> existedUserIds = existedUserRoles.stream().map(UserRole::getUserId).collect(Collectors.toSet()); Set<String> toAssignUserIds = Sets.difference(userIds, existedUserIds); Iterable<UserRole> toCreate = toAssignUserIds.stream().map(userId -> { UserRole userRole = new UserRole(); userRole.setRoleId(role.getId()); userRole.setUserId(userId); userRole.setDataChangeCreatedBy(operatorUserId); userRole.setDataChangeLastModifiedBy(operatorUserId); return userRole; }).collect(Collectors.toList()); userRoleRepository.saveAll(toCreate); return toAssignUserIds; } /** * Remove role from users */ @Transactional public void removeRoleFromUsers(String roleName, Set<String> userIds, String operatorUserId) { Role role = findRoleByRoleName(roleName); Preconditions.checkState(role != null, "Role %s doesn't exist!", roleName); List<UserRole> existedUserRoles = userRoleRepository.findByUserIdInAndRoleId(userIds, role.getId()); for (UserRole userRole : existedUserRoles) { userRole.setDeleted(true); userRole.setDataChangeLastModifiedTime(new Date()); userRole.setDataChangeLastModifiedBy(operatorUserId); } userRoleRepository.saveAll(existedUserRoles); } /** * Query users with role */ public Set<UserInfo> queryUsersWithRole(String roleName) { Role role = findRoleByRoleName(roleName); if (role == null) { return Collections.emptySet(); } List<UserRole> userRoles = userRoleRepository.findByRoleId(role.getId()); Set<UserInfo> users = userRoles.stream().map(userRole -> { UserInfo userInfo = new UserInfo(); userInfo.setUserId(userRole.getUserId()); return userInfo; }).collect(Collectors.toSet()); return users; } /** * Find role by role name, note that roleName should be unique */ public Role findRoleByRoleName(String roleName) { return roleRepository.findTopByRoleName(roleName); } /** * Check whether user has the permission */ public boolean userHasPermission(String userId, String permissionType, String targetId) { Permission permission = permissionRepository.findTopByPermissionTypeAndTargetId(permissionType, targetId); if (permission == null) { return false; } if (isSuperAdmin(userId)) { return true; } List<UserRole> userRoles = userRoleRepository.findByUserId(userId); if (CollectionUtils.isEmpty(userRoles)) { return false; } Set<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toSet()); List<RolePermission> rolePermissions = rolePermissionRepository.findByRoleIdIn(roleIds); if (CollectionUtils.isEmpty(rolePermissions)) { return false; } for (RolePermission rolePermission : rolePermissions) { if (rolePermission.getPermissionId() == permission.getId()) { return true; } } return false; } @Override public List<Role> findUserRoles(String userId) { List<UserRole> userRoles = userRoleRepository.findByUserId(userId); if (CollectionUtils.isEmpty(userRoles)) { return Collections.emptyList(); } Set<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toSet()); return Lists.newLinkedList(roleRepository.findAllById(roleIds)); } public boolean isSuperAdmin(String userId) { return portalConfig.superAdmins().contains(userId); } /** * Create permission, note that permissionType + targetId should be unique */ @Transactional public Permission createPermission(Permission permission) { String permissionType = permission.getPermissionType(); String targetId = permission.getTargetId(); Permission current = permissionRepository.findTopByPermissionTypeAndTargetId(permissionType, targetId); Preconditions.checkState(current == null, "Permission with permissionType %s targetId %s already exists!", permissionType, targetId); return permissionRepository.save(permission); } /** * Create permissions, note that permissionType + targetId should be unique */ @Transactional public Set<Permission> createPermissions(Set<Permission> permissions) { Multimap<String, String> targetIdPermissionTypes = HashMultimap.create(); for (Permission permission : permissions) { targetIdPermissionTypes.put(permission.getTargetId(), permission.getPermissionType()); } for (String targetId : targetIdPermissionTypes.keySet()) { Collection<String> permissionTypes = targetIdPermissionTypes.get(targetId); List<Permission> current = permissionRepository.findByPermissionTypeInAndTargetId(permissionTypes, targetId); Preconditions.checkState(CollectionUtils.isEmpty(current), "Permission with permissionType %s targetId %s already exists!", permissionTypes, targetId); } Iterable<Permission> results = permissionRepository.saveAll(permissions); return StreamSupport.stream(results.spliterator(), false).collect(Collectors.toSet()); } @Transactional @Override public void deleteRolePermissionsByAppId(String appId, String operator) { List<Long> permissionIds = permissionRepository.findPermissionIdsByAppId(appId); if (!permissionIds.isEmpty()) { // 1. delete Permission permissionRepository.batchDelete(permissionIds, operator); // 2. delete Role Permission rolePermissionRepository.batchDeleteByPermissionIds(permissionIds, operator); } List<Long> roleIds = roleRepository.findRoleIdsByAppId(appId); if (!roleIds.isEmpty()) { // 3. delete Role roleRepository.batchDelete(roleIds, operator); // 4. delete User Role userRoleRepository.batchDeleteByRoleIds(roleIds, operator); // 5. delete Consumer Role consumerRoleRepository.batchDeleteByRoleIds(roleIds, operator); } } @Transactional @Override public void deleteRolePermissionsByAppIdAndNamespace(String appId, String namespaceName, String operator) { List<Long> permissionIds = permissionRepository.findPermissionIdsByAppIdAndNamespace(appId, namespaceName); if (!permissionIds.isEmpty()) { // 1. delete Permission permissionRepository.batchDelete(permissionIds, operator); // 2. delete Role Permission rolePermissionRepository.batchDeleteByPermissionIds(permissionIds, operator); } List<Long> roleIds = roleRepository.findRoleIdsByAppIdAndNamespace(appId, namespaceName); if (!roleIds.isEmpty()) { // 3. delete Role roleRepository.batchDelete(roleIds, operator); // 4. delete User Role userRoleRepository.batchDeleteByRoleIds(roleIds, operator); // 5. delete Consumer Role consumerRoleRepository.batchDeleteByRoleIds(roleIds, operator); } } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.defaultimpl; import com.ctrip.framework.apollo.openapi.repository.ConsumerRoleRepository; import com.ctrip.framework.apollo.portal.component.config.PortalConfig; import com.ctrip.framework.apollo.portal.entity.bo.UserInfo; import com.ctrip.framework.apollo.portal.entity.po.Permission; import com.ctrip.framework.apollo.portal.entity.po.Role; import com.ctrip.framework.apollo.portal.entity.po.RolePermission; import com.ctrip.framework.apollo.portal.entity.po.UserRole; import com.ctrip.framework.apollo.portal.repository.PermissionRepository; import com.ctrip.framework.apollo.portal.repository.RolePermissionRepository; import com.ctrip.framework.apollo.portal.repository.RoleRepository; import com.ctrip.framework.apollo.portal.repository.UserRoleRepository; import com.ctrip.framework.apollo.portal.service.RolePermissionService; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.StreamSupport; /** * Created by timothy on 2017/4/26. */ public class DefaultRolePermissionService implements RolePermissionService { @Autowired private RoleRepository roleRepository; @Autowired private RolePermissionRepository rolePermissionRepository; @Autowired private UserRoleRepository userRoleRepository; @Autowired private PermissionRepository permissionRepository; @Autowired private PortalConfig portalConfig; @Autowired private ConsumerRoleRepository consumerRoleRepository; /** * Create role with permissions, note that role name should be unique */ @Transactional public Role createRoleWithPermissions(Role role, Set<Long> permissionIds) { Role current = findRoleByRoleName(role.getRoleName()); Preconditions.checkState(current == null, "Role %s already exists!", role.getRoleName()); Role createdRole = roleRepository.save(role); if (!CollectionUtils.isEmpty(permissionIds)) { Iterable<RolePermission> rolePermissions = permissionIds.stream().map(permissionId -> { RolePermission rolePermission = new RolePermission(); rolePermission.setRoleId(createdRole.getId()); rolePermission.setPermissionId(permissionId); rolePermission.setDataChangeCreatedBy(createdRole.getDataChangeCreatedBy()); rolePermission.setDataChangeLastModifiedBy(createdRole.getDataChangeLastModifiedBy()); return rolePermission; }).collect(Collectors.toList()); rolePermissionRepository.saveAll(rolePermissions); } return createdRole; } /** * Assign role to users * * @return the users assigned roles */ @Transactional public Set<String> assignRoleToUsers(String roleName, Set<String> userIds, String operatorUserId) { Role role = findRoleByRoleName(roleName); Preconditions.checkState(role != null, "Role %s doesn't exist!", roleName); List<UserRole> existedUserRoles = userRoleRepository.findByUserIdInAndRoleId(userIds, role.getId()); Set<String> existedUserIds = existedUserRoles.stream().map(UserRole::getUserId).collect(Collectors.toSet()); Set<String> toAssignUserIds = Sets.difference(userIds, existedUserIds); Iterable<UserRole> toCreate = toAssignUserIds.stream().map(userId -> { UserRole userRole = new UserRole(); userRole.setRoleId(role.getId()); userRole.setUserId(userId); userRole.setDataChangeCreatedBy(operatorUserId); userRole.setDataChangeLastModifiedBy(operatorUserId); return userRole; }).collect(Collectors.toList()); userRoleRepository.saveAll(toCreate); return toAssignUserIds; } /** * Remove role from users */ @Transactional public void removeRoleFromUsers(String roleName, Set<String> userIds, String operatorUserId) { Role role = findRoleByRoleName(roleName); Preconditions.checkState(role != null, "Role %s doesn't exist!", roleName); List<UserRole> existedUserRoles = userRoleRepository.findByUserIdInAndRoleId(userIds, role.getId()); for (UserRole userRole : existedUserRoles) { userRole.setDeleted(true); userRole.setDataChangeLastModifiedTime(new Date()); userRole.setDataChangeLastModifiedBy(operatorUserId); } userRoleRepository.saveAll(existedUserRoles); } /** * Query users with role */ public Set<UserInfo> queryUsersWithRole(String roleName) { Role role = findRoleByRoleName(roleName); if (role == null) { return Collections.emptySet(); } List<UserRole> userRoles = userRoleRepository.findByRoleId(role.getId()); Set<UserInfo> users = userRoles.stream().map(userRole -> { UserInfo userInfo = new UserInfo(); userInfo.setUserId(userRole.getUserId()); return userInfo; }).collect(Collectors.toSet()); return users; } /** * Find role by role name, note that roleName should be unique */ public Role findRoleByRoleName(String roleName) { return roleRepository.findTopByRoleName(roleName); } /** * Check whether user has the permission */ public boolean userHasPermission(String userId, String permissionType, String targetId) { Permission permission = permissionRepository.findTopByPermissionTypeAndTargetId(permissionType, targetId); if (permission == null) { return false; } if (isSuperAdmin(userId)) { return true; } List<UserRole> userRoles = userRoleRepository.findByUserId(userId); if (CollectionUtils.isEmpty(userRoles)) { return false; } Set<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toSet()); List<RolePermission> rolePermissions = rolePermissionRepository.findByRoleIdIn(roleIds); if (CollectionUtils.isEmpty(rolePermissions)) { return false; } for (RolePermission rolePermission : rolePermissions) { if (rolePermission.getPermissionId() == permission.getId()) { return true; } } return false; } @Override public List<Role> findUserRoles(String userId) { List<UserRole> userRoles = userRoleRepository.findByUserId(userId); if (CollectionUtils.isEmpty(userRoles)) { return Collections.emptyList(); } Set<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toSet()); return Lists.newLinkedList(roleRepository.findAllById(roleIds)); } public boolean isSuperAdmin(String userId) { return portalConfig.superAdmins().contains(userId); } /** * Create permission, note that permissionType + targetId should be unique */ @Transactional public Permission createPermission(Permission permission) { String permissionType = permission.getPermissionType(); String targetId = permission.getTargetId(); Permission current = permissionRepository.findTopByPermissionTypeAndTargetId(permissionType, targetId); Preconditions.checkState(current == null, "Permission with permissionType %s targetId %s already exists!", permissionType, targetId); return permissionRepository.save(permission); } /** * Create permissions, note that permissionType + targetId should be unique */ @Transactional public Set<Permission> createPermissions(Set<Permission> permissions) { Multimap<String, String> targetIdPermissionTypes = HashMultimap.create(); for (Permission permission : permissions) { targetIdPermissionTypes.put(permission.getTargetId(), permission.getPermissionType()); } for (String targetId : targetIdPermissionTypes.keySet()) { Collection<String> permissionTypes = targetIdPermissionTypes.get(targetId); List<Permission> current = permissionRepository.findByPermissionTypeInAndTargetId(permissionTypes, targetId); Preconditions.checkState(CollectionUtils.isEmpty(current), "Permission with permissionType %s targetId %s already exists!", permissionTypes, targetId); } Iterable<Permission> results = permissionRepository.saveAll(permissions); return StreamSupport.stream(results.spliterator(), false).collect(Collectors.toSet()); } @Transactional @Override public void deleteRolePermissionsByAppId(String appId, String operator) { List<Long> permissionIds = permissionRepository.findPermissionIdsByAppId(appId); if (!permissionIds.isEmpty()) { // 1. delete Permission permissionRepository.batchDelete(permissionIds, operator); // 2. delete Role Permission rolePermissionRepository.batchDeleteByPermissionIds(permissionIds, operator); } List<Long> roleIds = roleRepository.findRoleIdsByAppId(appId); if (!roleIds.isEmpty()) { // 3. delete Role roleRepository.batchDelete(roleIds, operator); // 4. delete User Role userRoleRepository.batchDeleteByRoleIds(roleIds, operator); // 5. delete Consumer Role consumerRoleRepository.batchDeleteByRoleIds(roleIds, operator); } } @Transactional @Override public void deleteRolePermissionsByAppIdAndNamespace(String appId, String namespaceName, String operator) { List<Long> permissionIds = permissionRepository.findPermissionIdsByAppIdAndNamespace(appId, namespaceName); if (!permissionIds.isEmpty()) { // 1. delete Permission permissionRepository.batchDelete(permissionIds, operator); // 2. delete Role Permission rolePermissionRepository.batchDeleteByPermissionIds(permissionIds, operator); } List<Long> roleIds = roleRepository.findRoleIdsByAppIdAndNamespace(appId, namespaceName); if (!roleIds.isEmpty()) { // 3. delete Role roleRepository.batchDelete(roleIds, operator); // 4. delete User Role userRoleRepository.batchDeleteByRoleIds(roleIds, operator); // 5. delete Consumer Role consumerRoleRepository.batchDeleteByRoleIds(roleIds, operator); } } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/SystemRoleManagerService.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.service; import com.ctrip.framework.apollo.portal.component.config.PortalConfig; import com.ctrip.framework.apollo.portal.constant.PermissionType; import com.ctrip.framework.apollo.portal.util.RoleUtils; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SystemRoleManagerService { public static final Logger logger = LoggerFactory.getLogger(SystemRoleManagerService.class); public static final String SYSTEM_PERMISSION_TARGET_ID = "SystemRole"; public static final String CREATE_APPLICATION_ROLE_NAME = RoleUtils.buildCreateApplicationRoleName(PermissionType.CREATE_APPLICATION, SYSTEM_PERMISSION_TARGET_ID); public static final String CREATE_APPLICATION_LIMIT_SWITCH_KEY = "role.create-application.enabled"; public static final String MANAGE_APP_MASTER_LIMIT_SWITCH_KEY = "role.manage-app-master.enabled"; private final RolePermissionService rolePermissionService; private final PortalConfig portalConfig; private final RoleInitializationService roleInitializationService; @Autowired public SystemRoleManagerService(final RolePermissionService rolePermissionService, final PortalConfig portalConfig, final RoleInitializationService roleInitializationService) { this.rolePermissionService = rolePermissionService; this.portalConfig = portalConfig; this.roleInitializationService = roleInitializationService; } @PostConstruct private void init() { roleInitializationService.initCreateAppRole(); } private boolean isCreateApplicationPermissionEnabled() { return portalConfig.isCreateApplicationPermissionEnabled(); } public boolean isManageAppMasterPermissionEnabled() { return portalConfig.isManageAppMasterPermissionEnabled(); } public boolean hasCreateApplicationPermission(String userId) { if (!isCreateApplicationPermissionEnabled()) { return true; } return rolePermissionService.userHasPermission(userId, PermissionType.CREATE_APPLICATION, SYSTEM_PERMISSION_TARGET_ID); } public boolean hasManageAppMasterPermission(String userId, String appId) { if (!isManageAppMasterPermissionEnabled()) { return true; } return rolePermissionService.userHasPermission(userId, PermissionType.MANAGE_APP_MASTER, appId); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.service; import com.ctrip.framework.apollo.portal.component.config.PortalConfig; import com.ctrip.framework.apollo.portal.constant.PermissionType; import com.ctrip.framework.apollo.portal.util.RoleUtils; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SystemRoleManagerService { public static final Logger logger = LoggerFactory.getLogger(SystemRoleManagerService.class); public static final String SYSTEM_PERMISSION_TARGET_ID = "SystemRole"; public static final String CREATE_APPLICATION_ROLE_NAME = RoleUtils.buildCreateApplicationRoleName(PermissionType.CREATE_APPLICATION, SYSTEM_PERMISSION_TARGET_ID); public static final String CREATE_APPLICATION_LIMIT_SWITCH_KEY = "role.create-application.enabled"; public static final String MANAGE_APP_MASTER_LIMIT_SWITCH_KEY = "role.manage-app-master.enabled"; private final RolePermissionService rolePermissionService; private final PortalConfig portalConfig; private final RoleInitializationService roleInitializationService; @Autowired public SystemRoleManagerService(final RolePermissionService rolePermissionService, final PortalConfig portalConfig, final RoleInitializationService roleInitializationService) { this.rolePermissionService = rolePermissionService; this.portalConfig = portalConfig; this.roleInitializationService = roleInitializationService; } @PostConstruct private void init() { roleInitializationService.initCreateAppRole(); } private boolean isCreateApplicationPermissionEnabled() { return portalConfig.isCreateApplicationPermissionEnabled(); } public boolean isManageAppMasterPermissionEnabled() { return portalConfig.isManageAppMasterPermissionEnabled(); } public boolean hasCreateApplicationPermission(String userId) { if (!isCreateApplicationPermissionEnabled()) { return true; } return rolePermissionService.userHasPermission(userId, PermissionType.CREATE_APPLICATION, SYSTEM_PERMISSION_TARGET_ID); } public boolean hasManageAppMasterPermission(String userId, String appId) { if (!isManageAppMasterPermissionEnabled()) { return true; } return rolePermissionService.userHasPermission(userId, PermissionType.MANAGE_APP_MASTER, appId); } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./scripts/apollo-on-kubernetes/README.md
# 使用方法 ## 一、构建镜像 ### 1.1 获取 apollo 压缩包 从 https://github.com/ctripcorp/apollo/releases 下载预先打好的 java 包 <br/> 例如你下载的是: <br/> apollo-portal-1.0.0-github.zip <br/> apollo-adminservice-1.0.0-github.zip <br/> apollo-configservice-1.0.0-github.zip <br/> ### 1.2 解压压缩包, 获取程序 jar 包 - 解压 apollo-portal-1.0.0-github.zip <br/> 获取 apollo-portal-1.0.0.jar, 重命名为 apollo-portal.jar, 放到 scripts/apollo-on-kubernetes/apollo-portal-server - 解压 apollo-adminservice-1.0.0-github.zip <br/> 获取 apollo-adminservice-1.0.0.jar, 重命名为 apollo-adminservice.jar, 放到 scripts/apollo-on-kubernetes/apollo-admin-server - 解压 apollo-configservice-1.0.0-github.zip <br/> 获取 apollo-configservice-1.0.0.jar, 重命名为 apollo-configservice.jar, 放到 scripts/apollo-on-kubernetes/apollo-config-server ### 1.3 build image 需要分别为alpine-bash-3.8-image,apollo-config-server,apollo-admin-server和apollo-portal-server构建镜像。 以 build apollo-config-server image 为例, 其他类似 ```bash scripts/apollo-on-kubernetes/apollo-config-server$ tree -L 2 . ├── apollo-configservice.conf ├── apollo-configservice.jar ├── config │   ├── application-github.properties │   └── app.properties ├── Dockerfile ├── entrypoint.sh └── scripts └── startup-kubernetes.sh ``` build image ```bash # 在 scripts/apollo-on-kubernetes/apollo-config-server 路径下 docker build -t apollo-config-server:v1.0.0 . ``` push image <br/> 将 image push 到你的 docker registry, 例如 vmware harbor ## 二、Deploy apollo on kubernetes ### 2.1 部署 MySQL 服务 你可以选用 MySQL-Galera-WSrep 来提高你的 MySQL 服务的可用性 <br/> MySQL 部署步骤略 ### 2.1 导入 MySQL DB 文件 由于上面部署了分布式的 MySQL, 所有 config-server、admin-server、portal-server 使用同一个 MySQL 服务的不同数据库 示例假设你的 apollo 开启了 4 个环境, 即 dev、test-alpha、test-beta、prod, 在你的 MySQL 中导入 scripts/apollo-on-kubernetes/db 下的文件即可 如果有需要, 你可以更改 eureka.service.url 的地址, 格式为 http://config-server-pod-name-index.meta-server-service-name:8080/eureka/ , 例如 http://statefulset-apollo-config-server-dev-0.service-apollo-meta-server-dev:8080/eureka/ ### 2.2 Deploy apollo on kubernetes 示例假设你有 4 台 kubernetes node 来部署 apollo, apollo 开启了 4 个环境, 即 dev、test-alpha、test-beta、prod 按照 scripts/apollo-on-kubernetes/kubernetes/kubectl-apply.sh 文件的内容部署 apollo 即可,注意需要按照实际情况修改对应配置文件中的数据库连接信息、eureka.service.url、replicas、nodeSelector、镜像信息等。 ```bash scripts/apollo-on-kubernetes/kubernetes$ cat kubectl-apply.sh # create namespace kubectl create namespace sre # dev-env kubectl apply -f apollo-env-dev/service-mysql-for-apollo-dev-env.yaml --record && \ kubectl apply -f apollo-env-dev/service-apollo-config-server-dev.yaml --record && \ kubectl apply -f apollo-env-dev/service-apollo-admin-server-dev.yaml --record # fat-env(test-alpha-env) kubectl apply -f apollo-env-test-alpha/service-mysql-for-apollo-test-alpha-env.yaml --record && \ kubectl apply -f apollo-env-test-alpha/service-apollo-config-server-test-alpha.yaml --record && \ kubectl apply -f apollo-env-test-alpha/service-apollo-admin-server-test-alpha.yaml --record # uat-env(test-beta-env) kubectl apply -f apollo-env-test-beta/service-mysql-for-apollo-test-beta-env.yaml --record && \ kubectl apply -f apollo-env-test-beta/service-apollo-config-server-test-beta.yaml --record && \ kubectl apply -f apollo-env-test-beta/service-apollo-admin-server-test-beta.yaml --record # prod-env kubectl apply -f apollo-env-prod/service-mysql-for-apollo-prod-env.yaml --record && \ kubectl apply -f apollo-env-prod/service-apollo-config-server-prod.yaml --record && \ kubectl apply -f apollo-env-prod/service-apollo-admin-server-prod.yaml --record # portal kubectl apply -f service-apollo-portal-server.yaml --record ``` ~~你需要注意的是, 应当尽量让同一个 server 的不同 pod 在不同 node 上, 这个通过 kubernetes nodeSelector 实现~~ 去掉nodeSelector 改为POD反亲和性[podAntiAffinity](https://kubernetes.io/docs/concepts/configuration/assign-pod-node/) ### 2.3 验证所有 pod 处于 Running 并且 READY 状态 ```bash kubectl get pod -n sre -o wide # 示例结果 NAME READY STATUS RESTARTS AGE IP NODE deployment-apollo-admin-server-dev-b7bbd657-4d5jx 1/1 Running 0 2d 10.247.4.79 k8s-apollo-node-2 deployment-apollo-admin-server-dev-b7bbd657-lwz5x 1/1 Running 0 2d 10.247.8.7 k8s-apollo-node-3 deployment-apollo-admin-server-dev-b7bbd657-xs4wt 1/1 Running 0 2d 10.247.1.23 k8s-apollo-node-1 deployment-apollo-admin-server-prod-699bbd894f-j977p 1/1 Running 0 2d 10.247.4.83 k8s-apollo-node-2 deployment-apollo-admin-server-prod-699bbd894f-n9m54 1/1 Running 0 2d 10.247.8.11 k8s-apollo-node-3 deployment-apollo-admin-server-prod-699bbd894f-vs56w 1/1 Running 0 2d 10.247.1.27 k8s-apollo-node-1 deployment-apollo-admin-server-test-beta-7c855cd4f5-9br65 1/1 Running 0 2d 10.247.1.25 k8s-apollo-node-1 deployment-apollo-admin-server-test-beta-7c855cd4f5-cck5g 1/1 Running 0 2d 10.247.8.9 k8s-apollo-node-3 deployment-apollo-admin-server-test-beta-7c855cd4f5-x6gt4 1/1 Running 0 2d 10.247.4.81 k8s-apollo-node-2 deployment-apollo-portal-server-6d4bbc879c-bv7cn 1/1 Running 0 2d 10.247.8.12 k8s-apollo-node-3 deployment-apollo-portal-server-6d4bbc879c-c4zrb 1/1 Running 0 2d 10.247.1.28 k8s-apollo-node-1 deployment-apollo-portal-server-6d4bbc879c-qm4mn 1/1 Running 0 2d 10.247.4.84 k8s-apollo-node-2 statefulset-apollo-config-server-dev-0 1/1 Running 0 2d 10.247.8.6 k8s-apollo-node-3 statefulset-apollo-config-server-dev-1 1/1 Running 0 2d 10.247.4.78 k8s-apollo-node-2 statefulset-apollo-config-server-dev-2 1/1 Running 0 2d 10.247.1.22 k8s-apollo-node-1 statefulset-apollo-config-server-prod-0 1/1 Running 0 2d 10.247.8.10 k8s-apollo-node-3 statefulset-apollo-config-server-prod-1 1/1 Running 0 2d 10.247.4.82 k8s-apollo-node-2 statefulset-apollo-config-server-prod-2 1/1 Running 0 2d 10.247.1.26 k8s-apollo-node-1 statefulset-apollo-config-server-test-beta-0 1/1 Running 0 2d 10.247.8.8 k8s-apollo-node-3 statefulset-apollo-config-server-test-beta-1 1/1 Running 0 2d 10.247.4.80 k8s-apollo-node-2 statefulset-apollo-config-server-test-beta-2 1/1 Running 0 2d 10.247.1.24 k8s-apollo-node-1 ``` ### 2.4 访问 apollo service - server 端(即 portal) <br/> &nbsp;&nbsp;&nbsp;&nbsp;kubernetes-master-ip:30001 - client 端, 在 client 端无需再实现负载均衡 <br/> Dev<br/> &nbsp;&nbsp;&nbsp;&nbsp;kubernetes-master-ip:30002 <br/> Test-Alpha <br/> &nbsp;&nbsp;&nbsp;&nbsp;kubernetes-master-ip:30003 <br/> Test-Beta <br/> &nbsp;&nbsp;&nbsp;&nbsp;kubernetes-master-ip:30004 <br/> Prod <br/> &nbsp;&nbsp;&nbsp;&nbsp;kubernetes-master-ip:30005 <br/> # FAQ ## 关于修改的 Dockerfile 添加 ENV 和 entrypoint.sh, 启动 server 需要的配置, 在 kubernetes yaml 文件中可以通过 configmap 传入、也可以通过 ENV 传入 关于 Dockerfile、entrypoint.sh 具体内容, 你可以查看文件里的内容 ## 关于 kubernetes yaml 文件 具体内容请查看 `scripts/apollo-on-kubernetes/kubernetes/service-apollo-portal-server.yaml` 注释 <br/> 其他类似。 ## 关于 eureka.service.url 使用 meta-server(即 config-server) 的 pod name, config-server 务必使用 statefulset。 格式为:`http://<config server pod名>.<meta server 服务名>:<meta server端口号>/eureka/`。 以 apollo-env-dev 为例: ```bash ('eureka.service.url', 'default', 'http://statefulset-apollo-config-server-dev-0.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-1.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-2.service-apollo-meta-server-dev:8080/eureka/', 'Eureka服务Url,多个service以英文逗号分隔') ``` 你可以精简 config-server pod 的 name, 示例的长名字是为了更好的阅读与理解。 ### 方式一:通过Spring Boot文件 application-github.properties配置(推荐) 推荐此方式配置 `eureka.service.url`,因为可以通过ConfigMap的方式传入容器,无需再修改数据库的字段。 Admin Server的配置: ```yaml --- # configmap for apollo-admin-server-dev kind: ConfigMap apiVersion: v1 metadata: namespace: sre name: configmap-apollo-admin-server-dev data: application-github.properties: | spring.datasource.url = jdbc:mysql://service-mysql-for-apollo-dev-env-mariadb.sre:3306/DevApolloConfigDB?characterEncoding=utf8 spring.datasource.username = root spring.datasource.password = test eureka.service.url = http://statefulset-apollo-config-server-dev-0.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-1.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-2.service-apollo-meta-server-dev:8080/eureka/ ``` Config Server的配置: ```yaml --- # configmap for apollo-config-server-dev kind: ConfigMap apiVersion: v1 metadata: namespace: sre name: configmap-apollo-config-server-dev data: application-github.properties: | spring.datasource.url = jdbc:mysql://service-mysql-for-apollo-dev-env-mariadb.sre:3306/DevApolloConfigDB?characterEncoding=utf8 spring.datasource.username = root spring.datasource.password = m6bCdQXa00 eureka.service.url = http://statefulset-apollo-config-server-dev-0.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-1.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-2.service-apollo-meta-server-dev:8080/eureka/ ``` ### 方式二:修改数据表 ApolloConfigDB.ServerConfig 修改数据库表 ApolloConfigDB.ServerConfig的 eureka.service.url。
# 使用方法 ## 一、构建镜像 ### 1.1 获取 apollo 压缩包 从 https://github.com/ctripcorp/apollo/releases 下载预先打好的 java 包 <br/> 例如你下载的是: <br/> apollo-portal-1.0.0-github.zip <br/> apollo-adminservice-1.0.0-github.zip <br/> apollo-configservice-1.0.0-github.zip <br/> ### 1.2 解压压缩包, 获取程序 jar 包 - 解压 apollo-portal-1.0.0-github.zip <br/> 获取 apollo-portal-1.0.0.jar, 重命名为 apollo-portal.jar, 放到 scripts/apollo-on-kubernetes/apollo-portal-server - 解压 apollo-adminservice-1.0.0-github.zip <br/> 获取 apollo-adminservice-1.0.0.jar, 重命名为 apollo-adminservice.jar, 放到 scripts/apollo-on-kubernetes/apollo-admin-server - 解压 apollo-configservice-1.0.0-github.zip <br/> 获取 apollo-configservice-1.0.0.jar, 重命名为 apollo-configservice.jar, 放到 scripts/apollo-on-kubernetes/apollo-config-server ### 1.3 build image 需要分别为alpine-bash-3.8-image,apollo-config-server,apollo-admin-server和apollo-portal-server构建镜像。 以 build apollo-config-server image 为例, 其他类似 ```bash scripts/apollo-on-kubernetes/apollo-config-server$ tree -L 2 . ├── apollo-configservice.conf ├── apollo-configservice.jar ├── config │   ├── application-github.properties │   └── app.properties ├── Dockerfile ├── entrypoint.sh └── scripts └── startup-kubernetes.sh ``` build image ```bash # 在 scripts/apollo-on-kubernetes/apollo-config-server 路径下 docker build -t apollo-config-server:v1.0.0 . ``` push image <br/> 将 image push 到你的 docker registry, 例如 vmware harbor ## 二、Deploy apollo on kubernetes ### 2.1 部署 MySQL 服务 你可以选用 MySQL-Galera-WSrep 来提高你的 MySQL 服务的可用性 <br/> MySQL 部署步骤略 ### 2.1 导入 MySQL DB 文件 由于上面部署了分布式的 MySQL, 所有 config-server、admin-server、portal-server 使用同一个 MySQL 服务的不同数据库 示例假设你的 apollo 开启了 4 个环境, 即 dev、test-alpha、test-beta、prod, 在你的 MySQL 中导入 scripts/apollo-on-kubernetes/db 下的文件即可 如果有需要, 你可以更改 eureka.service.url 的地址, 格式为 http://config-server-pod-name-index.meta-server-service-name:8080/eureka/ , 例如 http://statefulset-apollo-config-server-dev-0.service-apollo-meta-server-dev:8080/eureka/ ### 2.2 Deploy apollo on kubernetes 示例假设你有 4 台 kubernetes node 来部署 apollo, apollo 开启了 4 个环境, 即 dev、test-alpha、test-beta、prod 按照 scripts/apollo-on-kubernetes/kubernetes/kubectl-apply.sh 文件的内容部署 apollo 即可,注意需要按照实际情况修改对应配置文件中的数据库连接信息、eureka.service.url、replicas、nodeSelector、镜像信息等。 ```bash scripts/apollo-on-kubernetes/kubernetes$ cat kubectl-apply.sh # create namespace kubectl create namespace sre # dev-env kubectl apply -f apollo-env-dev/service-mysql-for-apollo-dev-env.yaml --record && \ kubectl apply -f apollo-env-dev/service-apollo-config-server-dev.yaml --record && \ kubectl apply -f apollo-env-dev/service-apollo-admin-server-dev.yaml --record # fat-env(test-alpha-env) kubectl apply -f apollo-env-test-alpha/service-mysql-for-apollo-test-alpha-env.yaml --record && \ kubectl apply -f apollo-env-test-alpha/service-apollo-config-server-test-alpha.yaml --record && \ kubectl apply -f apollo-env-test-alpha/service-apollo-admin-server-test-alpha.yaml --record # uat-env(test-beta-env) kubectl apply -f apollo-env-test-beta/service-mysql-for-apollo-test-beta-env.yaml --record && \ kubectl apply -f apollo-env-test-beta/service-apollo-config-server-test-beta.yaml --record && \ kubectl apply -f apollo-env-test-beta/service-apollo-admin-server-test-beta.yaml --record # prod-env kubectl apply -f apollo-env-prod/service-mysql-for-apollo-prod-env.yaml --record && \ kubectl apply -f apollo-env-prod/service-apollo-config-server-prod.yaml --record && \ kubectl apply -f apollo-env-prod/service-apollo-admin-server-prod.yaml --record # portal kubectl apply -f service-apollo-portal-server.yaml --record ``` ~~你需要注意的是, 应当尽量让同一个 server 的不同 pod 在不同 node 上, 这个通过 kubernetes nodeSelector 实现~~ 去掉nodeSelector 改为POD反亲和性[podAntiAffinity](https://kubernetes.io/docs/concepts/configuration/assign-pod-node/) ### 2.3 验证所有 pod 处于 Running 并且 READY 状态 ```bash kubectl get pod -n sre -o wide # 示例结果 NAME READY STATUS RESTARTS AGE IP NODE deployment-apollo-admin-server-dev-b7bbd657-4d5jx 1/1 Running 0 2d 10.247.4.79 k8s-apollo-node-2 deployment-apollo-admin-server-dev-b7bbd657-lwz5x 1/1 Running 0 2d 10.247.8.7 k8s-apollo-node-3 deployment-apollo-admin-server-dev-b7bbd657-xs4wt 1/1 Running 0 2d 10.247.1.23 k8s-apollo-node-1 deployment-apollo-admin-server-prod-699bbd894f-j977p 1/1 Running 0 2d 10.247.4.83 k8s-apollo-node-2 deployment-apollo-admin-server-prod-699bbd894f-n9m54 1/1 Running 0 2d 10.247.8.11 k8s-apollo-node-3 deployment-apollo-admin-server-prod-699bbd894f-vs56w 1/1 Running 0 2d 10.247.1.27 k8s-apollo-node-1 deployment-apollo-admin-server-test-beta-7c855cd4f5-9br65 1/1 Running 0 2d 10.247.1.25 k8s-apollo-node-1 deployment-apollo-admin-server-test-beta-7c855cd4f5-cck5g 1/1 Running 0 2d 10.247.8.9 k8s-apollo-node-3 deployment-apollo-admin-server-test-beta-7c855cd4f5-x6gt4 1/1 Running 0 2d 10.247.4.81 k8s-apollo-node-2 deployment-apollo-portal-server-6d4bbc879c-bv7cn 1/1 Running 0 2d 10.247.8.12 k8s-apollo-node-3 deployment-apollo-portal-server-6d4bbc879c-c4zrb 1/1 Running 0 2d 10.247.1.28 k8s-apollo-node-1 deployment-apollo-portal-server-6d4bbc879c-qm4mn 1/1 Running 0 2d 10.247.4.84 k8s-apollo-node-2 statefulset-apollo-config-server-dev-0 1/1 Running 0 2d 10.247.8.6 k8s-apollo-node-3 statefulset-apollo-config-server-dev-1 1/1 Running 0 2d 10.247.4.78 k8s-apollo-node-2 statefulset-apollo-config-server-dev-2 1/1 Running 0 2d 10.247.1.22 k8s-apollo-node-1 statefulset-apollo-config-server-prod-0 1/1 Running 0 2d 10.247.8.10 k8s-apollo-node-3 statefulset-apollo-config-server-prod-1 1/1 Running 0 2d 10.247.4.82 k8s-apollo-node-2 statefulset-apollo-config-server-prod-2 1/1 Running 0 2d 10.247.1.26 k8s-apollo-node-1 statefulset-apollo-config-server-test-beta-0 1/1 Running 0 2d 10.247.8.8 k8s-apollo-node-3 statefulset-apollo-config-server-test-beta-1 1/1 Running 0 2d 10.247.4.80 k8s-apollo-node-2 statefulset-apollo-config-server-test-beta-2 1/1 Running 0 2d 10.247.1.24 k8s-apollo-node-1 ``` ### 2.4 访问 apollo service - server 端(即 portal) <br/> &nbsp;&nbsp;&nbsp;&nbsp;kubernetes-master-ip:30001 - client 端, 在 client 端无需再实现负载均衡 <br/> Dev<br/> &nbsp;&nbsp;&nbsp;&nbsp;kubernetes-master-ip:30002 <br/> Test-Alpha <br/> &nbsp;&nbsp;&nbsp;&nbsp;kubernetes-master-ip:30003 <br/> Test-Beta <br/> &nbsp;&nbsp;&nbsp;&nbsp;kubernetes-master-ip:30004 <br/> Prod <br/> &nbsp;&nbsp;&nbsp;&nbsp;kubernetes-master-ip:30005 <br/> # FAQ ## 关于修改的 Dockerfile 添加 ENV 和 entrypoint.sh, 启动 server 需要的配置, 在 kubernetes yaml 文件中可以通过 configmap 传入、也可以通过 ENV 传入 关于 Dockerfile、entrypoint.sh 具体内容, 你可以查看文件里的内容 ## 关于 kubernetes yaml 文件 具体内容请查看 `scripts/apollo-on-kubernetes/kubernetes/service-apollo-portal-server.yaml` 注释 <br/> 其他类似。 ## 关于 eureka.service.url 使用 meta-server(即 config-server) 的 pod name, config-server 务必使用 statefulset。 格式为:`http://<config server pod名>.<meta server 服务名>:<meta server端口号>/eureka/`。 以 apollo-env-dev 为例: ```bash ('eureka.service.url', 'default', 'http://statefulset-apollo-config-server-dev-0.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-1.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-2.service-apollo-meta-server-dev:8080/eureka/', 'Eureka服务Url,多个service以英文逗号分隔') ``` 你可以精简 config-server pod 的 name, 示例的长名字是为了更好的阅读与理解。 ### 方式一:通过Spring Boot文件 application-github.properties配置(推荐) 推荐此方式配置 `eureka.service.url`,因为可以通过ConfigMap的方式传入容器,无需再修改数据库的字段。 Admin Server的配置: ```yaml --- # configmap for apollo-admin-server-dev kind: ConfigMap apiVersion: v1 metadata: namespace: sre name: configmap-apollo-admin-server-dev data: application-github.properties: | spring.datasource.url = jdbc:mysql://service-mysql-for-apollo-dev-env-mariadb.sre:3306/DevApolloConfigDB?characterEncoding=utf8 spring.datasource.username = root spring.datasource.password = test eureka.service.url = http://statefulset-apollo-config-server-dev-0.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-1.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-2.service-apollo-meta-server-dev:8080/eureka/ ``` Config Server的配置: ```yaml --- # configmap for apollo-config-server-dev kind: ConfigMap apiVersion: v1 metadata: namespace: sre name: configmap-apollo-config-server-dev data: application-github.properties: | spring.datasource.url = jdbc:mysql://service-mysql-for-apollo-dev-env-mariadb.sre:3306/DevApolloConfigDB?characterEncoding=utf8 spring.datasource.username = root spring.datasource.password = m6bCdQXa00 eureka.service.url = http://statefulset-apollo-config-server-dev-0.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-1.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-2.service-apollo-meta-server-dev:8080/eureka/ ``` ### 方式二:修改数据表 ApolloConfigDB.ServerConfig 修改数据库表 ApolloConfigDB.ServerConfig的 eureka.service.url。
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-client/src/test/java/com/ctrip/framework/apollo/internals/PropertiesConfigFileTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.internals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import com.ctrip.framework.apollo.ConfigFileChangeListener; import com.ctrip.framework.apollo.build.MockInjector; import com.ctrip.framework.apollo.enums.PropertyChangeType; import com.ctrip.framework.apollo.model.ConfigFileChangeEvent; import com.ctrip.framework.apollo.util.factory.PropertiesFactory; import com.google.common.util.concurrent.SettableFuture; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; import org.mockito.stubbing.Answer; /** * @author Jason Song(song_s@ctrip.com) */ @RunWith(MockitoJUnitRunner.class) public class PropertiesConfigFileTest { private String someNamespace; @Mock private ConfigRepository configRepository; @Mock private PropertiesFactory propertiesFactory; @Before public void setUp() throws Exception { someNamespace = "someName"; when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() { @Override public Properties answer(InvocationOnMock invocation) { return new Properties(); } }); MockInjector.setInstance(PropertiesFactory.class, propertiesFactory); } @After public void tearDown() throws Exception { MockInjector.reset(); } @Test public void testWhenHasContent() throws Exception { Properties someProperties = new Properties(); String someKey = "someKey"; String someValue = "someValue"; someProperties.setProperty(someKey, someValue); when(configRepository.getConfig()).thenReturn(someProperties); PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); assertEquals(ConfigFileFormat.Properties, configFile.getConfigFileFormat()); assertEquals(someNamespace, configFile.getNamespace()); assertTrue(configFile.hasContent()); assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue))); } @Test public void testWhenHasNoContent() throws Exception { when(configRepository.getConfig()).thenReturn(null); PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); assertFalse(configFile.hasContent()); assertNull(configFile.getContent()); } @Test public void testWhenConfigRepositoryHasError() throws Exception { when(configRepository.getConfig()).thenThrow(new RuntimeException("someError")); PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); assertFalse(configFile.hasContent()); assertNull(configFile.getContent()); } @Test public void testOnRepositoryChange() throws Exception { Properties someProperties = new Properties(); String someKey = "someKey"; String someValue = "someValue"; String anotherValue = "anotherValue"; someProperties.setProperty(someKey, someValue); when(configRepository.getConfig()).thenReturn(someProperties); PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue))); Properties anotherProperties = new Properties(); anotherProperties.setProperty(someKey, anotherValue); final SettableFuture<ConfigFileChangeEvent> configFileChangeFuture = SettableFuture.create(); ConfigFileChangeListener someListener = new ConfigFileChangeListener() { @Override public void onChange(ConfigFileChangeEvent changeEvent) { configFileChangeFuture.set(changeEvent); } }; configFile.addChangeListener(someListener); configFile.onRepositoryChange(someNamespace, anotherProperties); ConfigFileChangeEvent changeEvent = configFileChangeFuture.get(500, TimeUnit.MILLISECONDS); assertFalse(configFile.getContent().contains(String.format("%s=%s", someKey, someValue))); assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, anotherValue))); assertEquals(someNamespace, changeEvent.getNamespace()); assertTrue(changeEvent.getOldValue().contains(String.format("%s=%s", someKey, someValue))); assertTrue(changeEvent.getNewValue().contains(String.format("%s=%s", someKey, anotherValue))); assertEquals(PropertyChangeType.MODIFIED, changeEvent.getChangeType()); } @Test public void testWhenConfigRepositoryHasErrorAndThenRecovered() throws Exception { Properties someProperties = new Properties(); String someKey = "someKey"; String someValue = "someValue"; someProperties.setProperty(someKey, someValue); when(configRepository.getConfig()).thenThrow(new RuntimeException("someError")); PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); assertFalse(configFile.hasContent()); assertNull(configFile.getContent()); configFile.onRepositoryChange(someNamespace, someProperties); assertTrue(configFile.hasContent()); assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue))); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.internals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import com.ctrip.framework.apollo.ConfigFileChangeListener; import com.ctrip.framework.apollo.build.MockInjector; import com.ctrip.framework.apollo.enums.PropertyChangeType; import com.ctrip.framework.apollo.model.ConfigFileChangeEvent; import com.ctrip.framework.apollo.util.factory.PropertiesFactory; import com.google.common.util.concurrent.SettableFuture; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; import org.mockito.stubbing.Answer; /** * @author Jason Song(song_s@ctrip.com) */ @RunWith(MockitoJUnitRunner.class) public class PropertiesConfigFileTest { private String someNamespace; @Mock private ConfigRepository configRepository; @Mock private PropertiesFactory propertiesFactory; @Before public void setUp() throws Exception { someNamespace = "someName"; when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() { @Override public Properties answer(InvocationOnMock invocation) { return new Properties(); } }); MockInjector.setInstance(PropertiesFactory.class, propertiesFactory); } @After public void tearDown() throws Exception { MockInjector.reset(); } @Test public void testWhenHasContent() throws Exception { Properties someProperties = new Properties(); String someKey = "someKey"; String someValue = "someValue"; someProperties.setProperty(someKey, someValue); when(configRepository.getConfig()).thenReturn(someProperties); PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); assertEquals(ConfigFileFormat.Properties, configFile.getConfigFileFormat()); assertEquals(someNamespace, configFile.getNamespace()); assertTrue(configFile.hasContent()); assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue))); } @Test public void testWhenHasNoContent() throws Exception { when(configRepository.getConfig()).thenReturn(null); PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); assertFalse(configFile.hasContent()); assertNull(configFile.getContent()); } @Test public void testWhenConfigRepositoryHasError() throws Exception { when(configRepository.getConfig()).thenThrow(new RuntimeException("someError")); PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); assertFalse(configFile.hasContent()); assertNull(configFile.getContent()); } @Test public void testOnRepositoryChange() throws Exception { Properties someProperties = new Properties(); String someKey = "someKey"; String someValue = "someValue"; String anotherValue = "anotherValue"; someProperties.setProperty(someKey, someValue); when(configRepository.getConfig()).thenReturn(someProperties); PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue))); Properties anotherProperties = new Properties(); anotherProperties.setProperty(someKey, anotherValue); final SettableFuture<ConfigFileChangeEvent> configFileChangeFuture = SettableFuture.create(); ConfigFileChangeListener someListener = new ConfigFileChangeListener() { @Override public void onChange(ConfigFileChangeEvent changeEvent) { configFileChangeFuture.set(changeEvent); } }; configFile.addChangeListener(someListener); configFile.onRepositoryChange(someNamespace, anotherProperties); ConfigFileChangeEvent changeEvent = configFileChangeFuture.get(500, TimeUnit.MILLISECONDS); assertFalse(configFile.getContent().contains(String.format("%s=%s", someKey, someValue))); assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, anotherValue))); assertEquals(someNamespace, changeEvent.getNamespace()); assertTrue(changeEvent.getOldValue().contains(String.format("%s=%s", someKey, someValue))); assertTrue(changeEvent.getNewValue().contains(String.format("%s=%s", someKey, anotherValue))); assertEquals(PropertyChangeType.MODIFIED, changeEvent.getChangeType()); } @Test public void testWhenConfigRepositoryHasErrorAndThenRecovered() throws Exception { Properties someProperties = new Properties(); String someKey = "someKey"; String someValue = "someValue"; someProperties.setProperty(someKey, someValue); when(configRepository.getConfig()).thenThrow(new RuntimeException("someError")); PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); assertFalse(configFile.hasContent()); assertNull(configFile.getContent()); configFile.onRepositoryChange(someNamespace, someProperties); assertTrue(configFile.hasContent()); assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue))); } }
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./docs/en/community/team.md
# Apollo Team The Apollo team is comprised of Members and Contributors. Members have direct access to the source of Apollo project and actively evolve the code-base. Contributors improve the project through submission of patches and suggestions to the Members. The number of Contributors to the project is unbounded. All contributions to Apollo are greatly appreciated, whether for trivial cleanups, big new features or other material rewards. For more information about the community governance model, please refer [GOVERNANCE.md](https://github.com/ctripcorp/apollo/blob/master/GOVERNANCE.md). ## Members Members include Project Management Committee members and committers. The list is in alphabet order. ### Project Management Committee | Github ID | Name | Organization | | ---------- | ---------- | ------------ | | JaredTan95 | Jared Tan | DaoCloud | | kezhenxu94 | Zhenxu Ke | Tetrate | | nobodyiam | Jason Song | Ant Group | | zouyx | Joe Zou | Shein | ### Committer | Github ID | Name | Organization | | ----------- | ------------- | ------------ | | Anilople | Xiaoquan Wang | Some Bank | | klboke | Kailing Chen | TapTap | | lepdou | Le Zhang | Ant Group | | nisiyong | Stephen Ni | Qihoo 360 | | pengweiqhca | Wei Peng | Tuhu | | vdisk-group | Lvqiu Ye | Hundsun | ## Contributors ### Apollo main repository <img src="https://opencollective.com/apollo/contributors.svg?width=880&button=false" /> ### apollo.net <img src="https://opencollective.com/apollonet/contributors.svg?width=880&button=false" /> ## Becoming a Committer Please refer [How to become a Committer](https://github.com/ctripcorp/apollo/blob/master/GOVERNANCE.md#how-to-become-a-committer).
# Apollo Team The Apollo team is comprised of Members and Contributors. Members have direct access to the source of Apollo project and actively evolve the code-base. Contributors improve the project through submission of patches and suggestions to the Members. The number of Contributors to the project is unbounded. All contributions to Apollo are greatly appreciated, whether for trivial cleanups, big new features or other material rewards. For more information about the community governance model, please refer [GOVERNANCE.md](https://github.com/ctripcorp/apollo/blob/master/GOVERNANCE.md). ## Members Members include Project Management Committee members and committers. The list is in alphabet order. ### Project Management Committee | Github ID | Name | Organization | | ---------- | ---------- | ------------ | | JaredTan95 | Jared Tan | DaoCloud | | kezhenxu94 | Zhenxu Ke | Tetrate | | nobodyiam | Jason Song | Ant Group | | zouyx | Joe Zou | Shein | ### Committer | Github ID | Name | Organization | | ----------- | ------------- | ------------ | | Anilople | Xiaoquan Wang | Some Bank | | klboke | Kailing Chen | TapTap | | lepdou | Le Zhang | Ant Group | | nisiyong | Stephen Ni | Qihoo 360 | | pengweiqhca | Wei Peng | Tuhu | | vdisk-group | Lvqiu Ye | Hundsun | ## Contributors ### Apollo main repository <img src="https://opencollective.com/apollo/contributors.svg?width=880&button=false" /> ### apollo.net <img src="https://opencollective.com/apollonet/contributors.svg?width=880&button=false" /> ## Becoming a Committer Please refer [How to become a Committer](https://github.com/ctripcorp/apollo/blob/master/GOVERNANCE.md#how-to-become-a-committer).
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./scripts/sql/apolloconfigdb.sql
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Create Database # ------------------------------------------------------------ CREATE DATABASE IF NOT EXISTS ApolloConfigDB DEFAULT CHARACTER SET = utf8mb4; Use ApolloConfigDB; # Dump of table app # ------------------------------------------------------------ DROP TABLE IF EXISTS `App`; CREATE TABLE `App` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Name` (`Name`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用表'; # Dump of table appnamespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `AppNamespace`; CREATE TABLE `AppNamespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT 'namespace名字,注意,需要全局唯一', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'app id', `Format` varchar(32) NOT NULL DEFAULT 'properties' COMMENT 'namespace的format类型', `IsPublic` bit(1) NOT NULL DEFAULT b'0' COMMENT 'namespace是否为公共', `Comment` varchar(64) NOT NULL DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId` (`AppId`), KEY `Name_AppId` (`Name`,`AppId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用namespace定义'; # Dump of table audit # ------------------------------------------------------------ DROP TABLE IF EXISTS `Audit`; CREATE TABLE `Audit` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `EntityName` varchar(50) NOT NULL DEFAULT 'default' COMMENT '表名', `EntityId` int(10) unsigned DEFAULT NULL COMMENT '记录ID', `OpName` varchar(50) NOT NULL DEFAULT 'default' COMMENT '操作类型', `Comment` varchar(500) DEFAULT NULL COMMENT '备注', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='日志审计表'; # Dump of table cluster # ------------------------------------------------------------ DROP TABLE IF EXISTS `Cluster`; CREATE TABLE `Cluster` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT '集群名字', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'App id', `ParentClusterId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '父cluster', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId_Name` (`AppId`,`Name`), KEY `IX_ParentClusterId` (`ParentClusterId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='集群'; # Dump of table commit # ------------------------------------------------------------ DROP TABLE IF EXISTS `Commit`; CREATE TABLE `Commit` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `ChangeSets` longtext NOT NULL COMMENT '修改变更集', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `NamespaceName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'namespaceName', `Comment` varchar(500) DEFAULT NULL COMMENT '备注', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `AppId` (`AppId`(191)), KEY `ClusterName` (`ClusterName`(191)), KEY `NamespaceName` (`NamespaceName`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='commit 历史表'; # Dump of table grayreleaserule # ------------------------------------------------------------ DROP TABLE IF EXISTS `GrayReleaseRule`; CREATE TABLE `GrayReleaseRule` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Cluster Name', `NamespaceName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Namespace Name', `BranchName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'branch name', `Rules` varchar(16000) DEFAULT '[]' COMMENT '灰度规则', `ReleaseId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '灰度对应的release', `BranchStatus` tinyint(2) DEFAULT '1' COMMENT '灰度分支状态: 0:删除分支,1:正在使用的规则 2:全量发布', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Namespace` (`AppId`,`ClusterName`,`NamespaceName`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='灰度规则表'; # Dump of table instance # ------------------------------------------------------------ DROP TABLE IF EXISTS `Instance`; CREATE TABLE `Instance` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `DataCenter` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'Data Center Name', `Ip` varchar(32) NOT NULL DEFAULT '' COMMENT 'instance ip', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_UNIQUE_KEY` (`AppId`,`ClusterName`,`Ip`,`DataCenter`), KEY `IX_IP` (`Ip`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='使用配置的应用实例'; # Dump of table instanceconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `InstanceConfig`; CREATE TABLE `InstanceConfig` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `InstanceId` int(11) unsigned DEFAULT NULL COMMENT 'Instance Id', `ConfigAppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'Config App Id', `ConfigClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Config Cluster Name', `ConfigNamespaceName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Config Namespace Name', `ReleaseKey` varchar(64) NOT NULL DEFAULT '' COMMENT '发布的Key', `ReleaseDeliveryTime` timestamp NULL DEFAULT NULL COMMENT '配置获取时间', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_UNIQUE_KEY` (`InstanceId`,`ConfigAppId`,`ConfigNamespaceName`), KEY `IX_ReleaseKey` (`ReleaseKey`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Valid_Namespace` (`ConfigAppId`,`ConfigClusterName`,`ConfigNamespaceName`,`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用实例的配置信息'; # Dump of table item # ------------------------------------------------------------ DROP TABLE IF EXISTS `Item`; CREATE TABLE `Item` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `NamespaceId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '集群NamespaceId', `Key` varchar(128) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Value` longtext NOT NULL COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `LineNum` int(10) unsigned DEFAULT '0' COMMENT '行号', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_GroupId` (`NamespaceId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置项目'; # Dump of table namespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `Namespace`; CREATE TABLE `Namespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'Cluster Name', `NamespaceName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'Namespace Name', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId_ClusterName_NamespaceName` (`AppId`(191),`ClusterName`(191),`NamespaceName`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_NamespaceName` (`NamespaceName`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='命名空间'; # Dump of table namespacelock # ------------------------------------------------------------ DROP TABLE IF EXISTS `NamespaceLock`; CREATE TABLE `NamespaceLock` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id', `NamespaceId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '集群NamespaceId', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', `IsDeleted` bit(1) DEFAULT b'0' COMMENT '软删除', PRIMARY KEY (`Id`), UNIQUE KEY `IX_NamespaceId` (`NamespaceId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='namespace的编辑锁'; # Dump of table release # ------------------------------------------------------------ DROP TABLE IF EXISTS `Release`; CREATE TABLE `Release` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `ReleaseKey` varchar(64) NOT NULL DEFAULT '' COMMENT '发布的Key', `Name` varchar(64) NOT NULL DEFAULT 'default' COMMENT '发布名字', `Comment` varchar(256) DEFAULT NULL COMMENT '发布说明', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `NamespaceName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'namespaceName', `Configurations` longtext NOT NULL COMMENT '发布配置', `IsAbandoned` bit(1) NOT NULL DEFAULT b'0' COMMENT '是否废弃', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId_ClusterName_GroupName` (`AppId`(191),`ClusterName`(191),`NamespaceName`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_ReleaseKey` (`ReleaseKey`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发布'; # Dump of table releasehistory # ------------------------------------------------------------ DROP TABLE IF EXISTS `ReleaseHistory`; CREATE TABLE `ReleaseHistory` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `NamespaceName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'namespaceName', `BranchName` varchar(32) NOT NULL DEFAULT 'default' COMMENT '发布分支名', `ReleaseId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '关联的Release Id', `PreviousReleaseId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '前一次发布的ReleaseId', `Operation` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '发布类型,0: 普通发布,1: 回滚,2: 灰度发布,3: 灰度规则更新,4: 灰度合并回主分支发布,5: 主分支发布灰度自动发布,6: 主分支回滚灰度自动发布,7: 放弃灰度', `OperationContext` longtext NOT NULL COMMENT '发布上下文信息', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Namespace` (`AppId`,`ClusterName`,`NamespaceName`,`BranchName`), KEY `IX_ReleaseId` (`ReleaseId`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发布历史'; # Dump of table releasemessage # ------------------------------------------------------------ DROP TABLE IF EXISTS `ReleaseMessage`; CREATE TABLE `ReleaseMessage` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Message` varchar(1024) NOT NULL DEFAULT '' COMMENT '发布的消息内容', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Message` (`Message`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发布消息'; # Dump of table serverconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `ServerConfig`; CREATE TABLE `ServerConfig` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Key` varchar(64) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Cluster` varchar(32) NOT NULL DEFAULT 'default' COMMENT '配置对应的集群,default为不针对特定的集群', `Value` varchar(2048) NOT NULL DEFAULT 'default' COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Key` (`Key`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置服务自身配置'; # Dump of table accesskey # ------------------------------------------------------------ DROP TABLE IF EXISTS `AccessKey`; CREATE TABLE `AccessKey` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Secret` varchar(128) NOT NULL DEFAULT '' COMMENT 'Secret', `IsEnabled` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: enabled, 0: disabled', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='访问密钥'; # Config # ------------------------------------------------------------ INSERT INTO `ServerConfig` (`Key`, `Cluster`, `Value`, `Comment`) VALUES ('eureka.service.url', 'default', 'http://localhost:8080/eureka/', 'Eureka服务Url,多个service以英文逗号分隔'), ('namespace.lock.switch', 'default', 'false', '一次发布只能有一个人修改开关'), ('item.key.length.limit', 'default', '128', 'item key 最大长度限制'), ('item.value.length.limit', 'default', '20000', 'item value最大长度限制'), ('config-service.cache.enabled', 'default', 'false', 'ConfigService是否开启缓存,开启后能提高性能,但是会增大内存消耗!'); /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Create Database # ------------------------------------------------------------ CREATE DATABASE IF NOT EXISTS ApolloConfigDB DEFAULT CHARACTER SET = utf8mb4; Use ApolloConfigDB; # Dump of table app # ------------------------------------------------------------ DROP TABLE IF EXISTS `App`; CREATE TABLE `App` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Name` (`Name`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用表'; # Dump of table appnamespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `AppNamespace`; CREATE TABLE `AppNamespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT 'namespace名字,注意,需要全局唯一', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'app id', `Format` varchar(32) NOT NULL DEFAULT 'properties' COMMENT 'namespace的format类型', `IsPublic` bit(1) NOT NULL DEFAULT b'0' COMMENT 'namespace是否为公共', `Comment` varchar(64) NOT NULL DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId` (`AppId`), KEY `Name_AppId` (`Name`,`AppId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用namespace定义'; # Dump of table audit # ------------------------------------------------------------ DROP TABLE IF EXISTS `Audit`; CREATE TABLE `Audit` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `EntityName` varchar(50) NOT NULL DEFAULT 'default' COMMENT '表名', `EntityId` int(10) unsigned DEFAULT NULL COMMENT '记录ID', `OpName` varchar(50) NOT NULL DEFAULT 'default' COMMENT '操作类型', `Comment` varchar(500) DEFAULT NULL COMMENT '备注', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='日志审计表'; # Dump of table cluster # ------------------------------------------------------------ DROP TABLE IF EXISTS `Cluster`; CREATE TABLE `Cluster` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT '集群名字', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'App id', `ParentClusterId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '父cluster', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId_Name` (`AppId`,`Name`), KEY `IX_ParentClusterId` (`ParentClusterId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='集群'; # Dump of table commit # ------------------------------------------------------------ DROP TABLE IF EXISTS `Commit`; CREATE TABLE `Commit` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `ChangeSets` longtext NOT NULL COMMENT '修改变更集', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `NamespaceName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'namespaceName', `Comment` varchar(500) DEFAULT NULL COMMENT '备注', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `AppId` (`AppId`(191)), KEY `ClusterName` (`ClusterName`(191)), KEY `NamespaceName` (`NamespaceName`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='commit 历史表'; # Dump of table grayreleaserule # ------------------------------------------------------------ DROP TABLE IF EXISTS `GrayReleaseRule`; CREATE TABLE `GrayReleaseRule` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Cluster Name', `NamespaceName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Namespace Name', `BranchName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'branch name', `Rules` varchar(16000) DEFAULT '[]' COMMENT '灰度规则', `ReleaseId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '灰度对应的release', `BranchStatus` tinyint(2) DEFAULT '1' COMMENT '灰度分支状态: 0:删除分支,1:正在使用的规则 2:全量发布', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Namespace` (`AppId`,`ClusterName`,`NamespaceName`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='灰度规则表'; # Dump of table instance # ------------------------------------------------------------ DROP TABLE IF EXISTS `Instance`; CREATE TABLE `Instance` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `DataCenter` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'Data Center Name', `Ip` varchar(32) NOT NULL DEFAULT '' COMMENT 'instance ip', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_UNIQUE_KEY` (`AppId`,`ClusterName`,`Ip`,`DataCenter`), KEY `IX_IP` (`Ip`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='使用配置的应用实例'; # Dump of table instanceconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `InstanceConfig`; CREATE TABLE `InstanceConfig` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `InstanceId` int(11) unsigned DEFAULT NULL COMMENT 'Instance Id', `ConfigAppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'Config App Id', `ConfigClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Config Cluster Name', `ConfigNamespaceName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Config Namespace Name', `ReleaseKey` varchar(64) NOT NULL DEFAULT '' COMMENT '发布的Key', `ReleaseDeliveryTime` timestamp NULL DEFAULT NULL COMMENT '配置获取时间', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_UNIQUE_KEY` (`InstanceId`,`ConfigAppId`,`ConfigNamespaceName`), KEY `IX_ReleaseKey` (`ReleaseKey`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Valid_Namespace` (`ConfigAppId`,`ConfigClusterName`,`ConfigNamespaceName`,`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用实例的配置信息'; # Dump of table item # ------------------------------------------------------------ DROP TABLE IF EXISTS `Item`; CREATE TABLE `Item` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `NamespaceId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '集群NamespaceId', `Key` varchar(128) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Value` longtext NOT NULL COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `LineNum` int(10) unsigned DEFAULT '0' COMMENT '行号', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_GroupId` (`NamespaceId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置项目'; # Dump of table namespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `Namespace`; CREATE TABLE `Namespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'Cluster Name', `NamespaceName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'Namespace Name', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId_ClusterName_NamespaceName` (`AppId`(191),`ClusterName`(191),`NamespaceName`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_NamespaceName` (`NamespaceName`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='命名空间'; # Dump of table namespacelock # ------------------------------------------------------------ DROP TABLE IF EXISTS `NamespaceLock`; CREATE TABLE `NamespaceLock` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id', `NamespaceId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '集群NamespaceId', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', `IsDeleted` bit(1) DEFAULT b'0' COMMENT '软删除', PRIMARY KEY (`Id`), UNIQUE KEY `IX_NamespaceId` (`NamespaceId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='namespace的编辑锁'; # Dump of table release # ------------------------------------------------------------ DROP TABLE IF EXISTS `Release`; CREATE TABLE `Release` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `ReleaseKey` varchar(64) NOT NULL DEFAULT '' COMMENT '发布的Key', `Name` varchar(64) NOT NULL DEFAULT 'default' COMMENT '发布名字', `Comment` varchar(256) DEFAULT NULL COMMENT '发布说明', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `NamespaceName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'namespaceName', `Configurations` longtext NOT NULL COMMENT '发布配置', `IsAbandoned` bit(1) NOT NULL DEFAULT b'0' COMMENT '是否废弃', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId_ClusterName_GroupName` (`AppId`(191),`ClusterName`(191),`NamespaceName`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_ReleaseKey` (`ReleaseKey`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发布'; # Dump of table releasehistory # ------------------------------------------------------------ DROP TABLE IF EXISTS `ReleaseHistory`; CREATE TABLE `ReleaseHistory` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `NamespaceName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'namespaceName', `BranchName` varchar(32) NOT NULL DEFAULT 'default' COMMENT '发布分支名', `ReleaseId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '关联的Release Id', `PreviousReleaseId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '前一次发布的ReleaseId', `Operation` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '发布类型,0: 普通发布,1: 回滚,2: 灰度发布,3: 灰度规则更新,4: 灰度合并回主分支发布,5: 主分支发布灰度自动发布,6: 主分支回滚灰度自动发布,7: 放弃灰度', `OperationContext` longtext NOT NULL COMMENT '发布上下文信息', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Namespace` (`AppId`,`ClusterName`,`NamespaceName`,`BranchName`), KEY `IX_ReleaseId` (`ReleaseId`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发布历史'; # Dump of table releasemessage # ------------------------------------------------------------ DROP TABLE IF EXISTS `ReleaseMessage`; CREATE TABLE `ReleaseMessage` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Message` varchar(1024) NOT NULL DEFAULT '' COMMENT '发布的消息内容', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Message` (`Message`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发布消息'; # Dump of table serverconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `ServerConfig`; CREATE TABLE `ServerConfig` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Key` varchar(64) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Cluster` varchar(32) NOT NULL DEFAULT 'default' COMMENT '配置对应的集群,default为不针对特定的集群', `Value` varchar(2048) NOT NULL DEFAULT 'default' COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Key` (`Key`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置服务自身配置'; # Dump of table accesskey # ------------------------------------------------------------ DROP TABLE IF EXISTS `AccessKey`; CREATE TABLE `AccessKey` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Secret` varchar(128) NOT NULL DEFAULT '' COMMENT 'Secret', `IsEnabled` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: enabled, 0: disabled', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='访问密钥'; # Config # ------------------------------------------------------------ INSERT INTO `ServerConfig` (`Key`, `Cluster`, `Value`, `Comment`) VALUES ('eureka.service.url', 'default', 'http://localhost:8080/eureka/', 'Eureka服务Url,多个service以英文逗号分隔'), ('namespace.lock.switch', 'default', 'false', '一次发布只能有一个人修改开关'), ('item.key.length.limit', 'default', '128', 'item key 最大长度限制'), ('item.value.length.limit', 'default', '20000', 'item value最大长度限制'), ('config-service.cache.enabled', 'default', 'false', 'ConfigService是否开启缓存,开启后能提高性能,但是会增大内存消耗!'); /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
-1
apolloconfig/apollo
3,816
Reduce bootstrap time in the situation with large properties
## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
Shawyeok
2021-07-08T09:46:00Z
2021-07-19T13:19:40Z
622e35a199d979e3cc6913c79c53e92491f5bd2e
6d50ca881a6afb2766725bdb3c09c14d450cc12f
Reduce bootstrap time in the situation with large properties. ## What's the purpose of this PR Reduce bootstrap time in the situation with large properties. Use test method described in [#3800](https://github.com/ctripcorp/apollo/issues/3800#issuecomment-876288944), compare results:   | Baseline | New -- | -- | --   | 11717ms | 599ms   | 12755ms | 647ms   | 12849ms | 567ms   | 11482ms | 627ms   | 11903ms | 611ms Stdev | 622ms | 30ms Aveage | 12141ms | 610ms ## Which issue(s) this PR fixes: Fixes #3800 ## Brief changelog Reduce bootstrap time in the situation with large properties. Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/NetUtil.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.core.utils; import com.google.common.io.CharStreams; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; /** * Created by gl49 on 2018/6/8. */ public class NetUtil { private static final int DEFAULT_TIMEOUT_IN_SECONDS = 5000; /** * ping the url, return true if ping ok, false otherwise */ public static boolean pingUrl(String address) { try { URL urlObj = new URL(address); HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setConnectTimeout(DEFAULT_TIMEOUT_IN_SECONDS); connection.setReadTimeout(DEFAULT_TIMEOUT_IN_SECONDS); int statusCode = connection.getResponseCode(); cleanUpConnection(connection); return (200 <= statusCode && statusCode <= 399); } catch (Throwable ignore) { } return false; } /** * according to https://docs.oracle.com/javase/7/docs/technotes/guides/net/http-keepalive.html, we should clean up the * connection by reading the response body so that the connection could be reused. */ private static void cleanUpConnection(HttpURLConnection conn) { InputStreamReader isr = null; InputStreamReader esr = null; try { isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); CharStreams.toString(isr); } catch (IOException e) { InputStream errorStream = conn.getErrorStream(); if (errorStream != null) { esr = new InputStreamReader(errorStream, StandardCharsets.UTF_8); try { CharStreams.toString(esr); } catch (IOException ioe) { //ignore } } } finally { if (isr != null) { try { isr.close(); } catch (IOException ex) { // ignore } } if (esr != null) { try { esr.close(); } catch (IOException ex) { // ignore } } } } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.core.utils; import com.google.common.io.CharStreams; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; /** * Created by gl49 on 2018/6/8. */ public class NetUtil { private static final int DEFAULT_TIMEOUT_IN_SECONDS = 5000; /** * ping the url, return true if ping ok, false otherwise */ public static boolean pingUrl(String address) { try { URL urlObj = new URL(address); HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setConnectTimeout(DEFAULT_TIMEOUT_IN_SECONDS); connection.setReadTimeout(DEFAULT_TIMEOUT_IN_SECONDS); int statusCode = connection.getResponseCode(); cleanUpConnection(connection); return (200 <= statusCode && statusCode <= 399); } catch (Throwable ignore) { } return false; } /** * according to https://docs.oracle.com/javase/7/docs/technotes/guides/net/http-keepalive.html, we should clean up the * connection by reading the response body so that the connection could be reused. */ private static void cleanUpConnection(HttpURLConnection conn) { InputStreamReader isr = null; InputStreamReader esr = null; try { isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); CharStreams.toString(isr); } catch (IOException e) { InputStream errorStream = conn.getErrorStream(); if (errorStream != null) { esr = new InputStreamReader(errorStream, StandardCharsets.UTF_8); try { CharStreams.toString(esr); } catch (IOException ioe) { //ignore } } } finally { if (isr != null) { try { isr.close(); } catch (IOException ex) { // ignore } } if (esr != null) { try { esr.close(); } catch (IOException ex) { // ignore } } } } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./CHANGES.md
Changes by Version ================== Release Notes. Apollo 1.9.0 ------------------ * [extend DataChange_CreatedBy, DataChange_LastModifiedBy from 32 to 64.](https://github.com/ctripcorp/apollo/pull/3552) * [add spring configuration metadata](https://github.com/ctripcorp/apollo/pull/3553) * [fix #3551 and optimize ldap samples ](https://github.com/ctripcorp/apollo/pull/3561) * [update wiki url and refine documentation](https://github.com/ctripcorp/apollo/pull/3563) * [slim docker images](https://github.com/ctripcorp/apollo/pull/3572) * [add network strategy guideline to docker quick start](https://github.com/ctripcorp/apollo/pull/3574) * [Added support for consul service discovery](https://github.com/ctripcorp/apollo/pull/3575) * [disable consul in apollo-assembly by default ](https://github.com/ctripcorp/apollo/pull/3585) * [ServiceBootstrap unit test fix](https://github.com/ctripcorp/apollo/pull/3593) * [replace http client implementation with interface ](https://github.com/ctripcorp/apollo/pull/3594) * [Allow users to inject customized instance via ApolloInjectorCustomizer](https://github.com/ctripcorp/apollo/pull/3602) * [Fixes #3606](https://github.com/ctripcorp/apollo/pull/3609) * [Bump xstream from 1.4.15 to 1.4.16](https://github.com/ctripcorp/apollo/pull/3611) * [docs: user practices. Alibaba Sentinel Dashboard Push Rules to apollo](https://github.com/ctripcorp/apollo/pull/3617) * [update known users](https://github.com/ctripcorp/apollo/pull/3619) * [add maven deploy action](https://github.com/ctripcorp/apollo/pull/3620) * [fix the issue that access key doesn't work if appid passed is in different case](https://github.com/ctripcorp/apollo/pull/3627) * [fix oidc logout](https://github.com/ctripcorp/apollo/pull/3628) * [docs: third party sdk nodejs client](https://github.com/ctripcorp/apollo/pull/3632) * [update known users](https://github.com/ctripcorp/apollo/pull/3633) * [docs: use docsify pagination plugin](https://github.com/ctripcorp/apollo/pull/3634) * [apollo client to support jdk16](https://github.com/ctripcorp/apollo/pull/3646) * [add English version of readme](https://github.com/ctripcorp/apollo/pull/3656) * [update known users](https://github.com/ctripcorp/apollo/pull/3657) * [update apolloconfig.com domain](https://github.com/ctripcorp/apollo/pull/3658) * [localize css to speed up the loading of google fonts](https://github.com/ctripcorp/apollo/pull/3660) * [test(apollo-client): use assertEquals instead of assertThat](https://github.com/ctripcorp/apollo/pull/3667) * [test(apollo-client): make timeout more longer when long poll](https://github.com/ctripcorp/apollo/pull/3668) * [fix unit test](https://github.com/ctripcorp/apollo/pull/3669) * [解决日志系统未初始化完成时,apollo 的加载日志没法输出问题](https://github.com/ctripcorp/apollo/pull/3677) * [fix[apollo-configService]: Solve configService startup exception](https://github.com/ctripcorp/apollo/pull/3679) * [Community Governance Proposal](https://github.com/ctripcorp/apollo/pull/3670) * [增加阿波罗client的php库](https://github.com/ctripcorp/apollo/pull/3682) * [Bump xstream from 1.4.16 to 1.4.17](https://github.com/ctripcorp/apollo/pull/3692) * [Improve the nacos registry configuration document](https://github.com/ctripcorp/apollo/pull/3695) * [Remove redundant invoke of trySyncFromUpstream](https://github.com/ctripcorp/apollo/pull/3699) * [add apollo team introduction and community releated contents](https://github.com/ctripcorp/apollo/pull/3713) * [fix oidc sql](https://github.com/ctripcorp/apollo/pull/3720) * [feat(apollo-client): add method interestedChangedKeys to ConfigChangeEvent](https://github.com/ctripcorp/apollo/pull/3666) * [add More... link for known users](https://github.com/ctripcorp/apollo/pull/3757) * [update OIDC documentation](https://github.com/ctripcorp/apollo/pull/3766) * [Improve the item-value length limit configuration document](https://github.com/ctripcorp/apollo/pull/3789) * [Use queue#take instead of poll](https://github.com/ctripcorp/apollo/pull/3765) * [feature: add Spring Boot 2.4 config data loader support](https://github.com/ctripcorp/apollo/pull/3754) * [feat(open-api): get authorized apps](https://github.com/ctripcorp/apollo/pull/3647) * [feature: shared session for multi apollo portal](https://github.com/ctripcorp/apollo/pull/3786) * [feature: add email for select user on apollo portal](https://github.com/ctripcorp/apollo/pull/3797) * [feature: modify item comment valid size](https://github.com/ctripcorp/apollo/pull/3803) * [set default session store-type](https://github.com/ctripcorp/apollo/pull/3812) * [speed up the stale issue mark and close phase](https://github.com/ctripcorp/apollo/pull/3808) ------------------ All issues and pull requests are [here](https://github.com/ctripcorp/apollo/milestone/6?closed=1)
Changes by Version ================== Release Notes. Apollo 1.9.0 ------------------ * [extend DataChange_CreatedBy, DataChange_LastModifiedBy from 32 to 64.](https://github.com/ctripcorp/apollo/pull/3552) * [add spring configuration metadata](https://github.com/ctripcorp/apollo/pull/3553) * [fix #3551 and optimize ldap samples ](https://github.com/ctripcorp/apollo/pull/3561) * [update wiki url and refine documentation](https://github.com/ctripcorp/apollo/pull/3563) * [slim docker images](https://github.com/ctripcorp/apollo/pull/3572) * [add network strategy guideline to docker quick start](https://github.com/ctripcorp/apollo/pull/3574) * [Added support for consul service discovery](https://github.com/ctripcorp/apollo/pull/3575) * [disable consul in apollo-assembly by default ](https://github.com/ctripcorp/apollo/pull/3585) * [ServiceBootstrap unit test fix](https://github.com/ctripcorp/apollo/pull/3593) * [replace http client implementation with interface ](https://github.com/ctripcorp/apollo/pull/3594) * [Allow users to inject customized instance via ApolloInjectorCustomizer](https://github.com/ctripcorp/apollo/pull/3602) * [Fixes #3606](https://github.com/ctripcorp/apollo/pull/3609) * [Bump xstream from 1.4.15 to 1.4.16](https://github.com/ctripcorp/apollo/pull/3611) * [docs: user practices. Alibaba Sentinel Dashboard Push Rules to apollo](https://github.com/ctripcorp/apollo/pull/3617) * [update known users](https://github.com/ctripcorp/apollo/pull/3619) * [add maven deploy action](https://github.com/ctripcorp/apollo/pull/3620) * [fix the issue that access key doesn't work if appid passed is in different case](https://github.com/ctripcorp/apollo/pull/3627) * [fix oidc logout](https://github.com/ctripcorp/apollo/pull/3628) * [docs: third party sdk nodejs client](https://github.com/ctripcorp/apollo/pull/3632) * [update known users](https://github.com/ctripcorp/apollo/pull/3633) * [docs: use docsify pagination plugin](https://github.com/ctripcorp/apollo/pull/3634) * [apollo client to support jdk16](https://github.com/ctripcorp/apollo/pull/3646) * [add English version of readme](https://github.com/ctripcorp/apollo/pull/3656) * [update known users](https://github.com/ctripcorp/apollo/pull/3657) * [update apolloconfig.com domain](https://github.com/ctripcorp/apollo/pull/3658) * [localize css to speed up the loading of google fonts](https://github.com/ctripcorp/apollo/pull/3660) * [test(apollo-client): use assertEquals instead of assertThat](https://github.com/ctripcorp/apollo/pull/3667) * [test(apollo-client): make timeout more longer when long poll](https://github.com/ctripcorp/apollo/pull/3668) * [fix unit test](https://github.com/ctripcorp/apollo/pull/3669) * [解决日志系统未初始化完成时,apollo 的加载日志没法输出问题](https://github.com/ctripcorp/apollo/pull/3677) * [fix[apollo-configService]: Solve configService startup exception](https://github.com/ctripcorp/apollo/pull/3679) * [Community Governance Proposal](https://github.com/ctripcorp/apollo/pull/3670) * [增加阿波罗client的php库](https://github.com/ctripcorp/apollo/pull/3682) * [Bump xstream from 1.4.16 to 1.4.17](https://github.com/ctripcorp/apollo/pull/3692) * [Improve the nacos registry configuration document](https://github.com/ctripcorp/apollo/pull/3695) * [Remove redundant invoke of trySyncFromUpstream](https://github.com/ctripcorp/apollo/pull/3699) * [add apollo team introduction and community releated contents](https://github.com/ctripcorp/apollo/pull/3713) * [fix oidc sql](https://github.com/ctripcorp/apollo/pull/3720) * [feat(apollo-client): add method interestedChangedKeys to ConfigChangeEvent](https://github.com/ctripcorp/apollo/pull/3666) * [add More... link for known users](https://github.com/ctripcorp/apollo/pull/3757) * [update OIDC documentation](https://github.com/ctripcorp/apollo/pull/3766) * [Improve the item-value length limit configuration document](https://github.com/ctripcorp/apollo/pull/3789) * [Use queue#take instead of poll](https://github.com/ctripcorp/apollo/pull/3765) * [feature: add Spring Boot 2.4 config data loader support](https://github.com/ctripcorp/apollo/pull/3754) * [feat(open-api): get authorized apps](https://github.com/ctripcorp/apollo/pull/3647) * [feature: shared session for multi apollo portal](https://github.com/ctripcorp/apollo/pull/3786) * [feature: add email for select user on apollo portal](https://github.com/ctripcorp/apollo/pull/3797) * [feature: modify item comment valid size](https://github.com/ctripcorp/apollo/pull/3803) * [set default session store-type](https://github.com/ctripcorp/apollo/pull/3812) * [speed up the stale issue mark and close phase](https://github.com/ctripcorp/apollo/pull/3808) * [feature: add the delegating password encoder for apollo-portal simple auth](https://github.com/ctripcorp/apollo/pull/3804) ------------------ All issues and pull requests are [here](https://github.com/ctripcorp/apollo/milestone/6?closed=1)
1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-client/src/test/java/com/ctrip/framework/apollo/spring/JavaConfigAnnotationTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.spring; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigChangeListener; import com.ctrip.framework.apollo.ConfigFileChangeListener; import com.ctrip.framework.apollo.core.ConfigConsts; import com.ctrip.framework.apollo.internals.SimpleConfig; import com.ctrip.framework.apollo.internals.YamlConfigFile; import com.ctrip.framework.apollo.model.ConfigChange; import com.ctrip.framework.apollo.model.ConfigChangeEvent; import com.ctrip.framework.apollo.spring.annotation.ApolloConfig; import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener; import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.SettableFuture; import java.io.IOException; import java.util.Collections; import java.util.Properties; import java.util.Queue; import java.util.UUID; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anySetOf; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Jason Song(song_s@ctrip.com) */ public class JavaConfigAnnotationTest extends AbstractSpringIntegrationTest { private static final String FX_APOLLO_NAMESPACE = "FX.apollo"; private static final String APPLICATION_YAML_NAMESPACE = "application.yaml"; private static <T> T getBean(Class<T> beanClass, Class<?>... annotatedClasses) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(annotatedClasses); return context.getBean(beanClass); } private static <T> T getSimpleBean(Class<? extends T> clazz) { return getBean(clazz, clazz); } @Override @After public void tearDown() throws Exception { // clear the system properties System.clearProperty(SystemPropertyKeyConstants.SIMPLE_NAMESPACE); System.clearProperty(SystemPropertyKeyConstants.REDIS_NAMESPACE); System.clearProperty(SystemPropertyKeyConstants.FROM_SYSTEM_NAMESPACE); System.clearProperty(SystemPropertyKeyConstants.FROM_SYSTEM_YAML_NAMESPACE); System.clearProperty(SystemPropertyKeyConstants.FROM_NAMESPACE_APPLICATION_KEY); System.clearProperty(SystemPropertyKeyConstants.FROM_NAMESPACE_APPLICATION_KEY_YAML); super.tearDown(); } @Test public void testApolloConfig() throws Exception { Config applicationConfig = mock(Config.class); Config fxApolloConfig = mock(Config.class); String someKey = "someKey"; String someValue = "someValue"; mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); prepareYamlConfigFile(APPLICATION_YAML_NAMESPACE, readYamlContentAsConfigFileProperties("case9.yml")); TestApolloConfigBean1 bean = getBean(TestApolloConfigBean1.class, AppConfig1.class); assertEquals(applicationConfig, bean.getConfig()); assertEquals(applicationConfig, bean.getAnotherConfig()); assertEquals(fxApolloConfig, bean.getYetAnotherConfig()); Config yamlConfig = bean.getYamlConfig(); assertEquals(someValue, yamlConfig.getProperty(someKey, null)); } @Test(expected = BeanCreationException.class) public void testApolloConfigWithWrongFieldType() throws Exception { Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); getBean(TestApolloConfigBean2.class, AppConfig2.class); } @Test public void testApolloConfigWithInheritance() throws Exception { Config applicationConfig = mock(Config.class); Config fxApolloConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); prepareYamlConfigFile(APPLICATION_YAML_NAMESPACE, readYamlContentAsConfigFileProperties("case9.yml")); TestApolloChildConfigBean bean = getBean(TestApolloChildConfigBean.class, AppConfig6.class); assertEquals(applicationConfig, bean.getConfig()); assertEquals(applicationConfig, bean.getAnotherConfig()); assertEquals(fxApolloConfig, bean.getYetAnotherConfig()); assertEquals(applicationConfig, bean.getSomeConfig()); } @Test public void testEnableApolloConfigResolveExpressionSimple() { String someKey = "someKey-2020-11-14-1750"; String someValue = UUID.randomUUID().toString(); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); Config xxxConfig = mock(Config.class); when(xxxConfig.getProperty(eq(someKey), anyString())).thenReturn(someValue); mockConfig("xxx", xxxConfig); TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration configuration = getSimpleBean(TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration.class); // check assertEquals(someValue, configuration.getSomeKey()); verify(xxxConfig, times(1)).getProperty(eq(someKey), anyString()); } @Test public void testEnableApolloConfigResolveExpressionFromSystemProperty() { mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); final String someKey = "someKey-2020-11-14-1750"; final String someValue = UUID.randomUUID().toString(); final String resolvedNamespaceName = "yyy"; System.setProperty(SystemPropertyKeyConstants.SIMPLE_NAMESPACE, resolvedNamespaceName); Config yyyConfig = mock(Config.class); when(yyyConfig.getProperty(eq(someKey), anyString())).thenReturn(someValue); mockConfig(resolvedNamespaceName, yyyConfig); TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration configuration = getSimpleBean(TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration.class); // check assertEquals(someValue, configuration.getSomeKey()); verify(yyyConfig, times(1)).getProperty(eq(someKey), anyString()); } @Test(expected = BeanCreationException.class) public void testEnableApolloConfigUnresolvedValueInField() { mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); mockConfig("xxx", mock(Config.class)); getSimpleBean(TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration.class); } @Test(expected = IllegalArgumentException.class) public void testEnableApolloConfigUnresolvable() { getSimpleBean(TestEnableApolloConfigUnresolvableConfiguration.class); } @Test public void testApolloConfigChangeListener() throws Exception { Config applicationConfig = mock(Config.class); Config fxApolloConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); final List<ConfigChangeListener> applicationListeners = Lists.newArrayList(); final List<ConfigChangeListener> fxApolloListeners = Lists.newArrayList(); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { applicationListeners.add(invocation.getArgumentAt(0, ConfigChangeListener.class)); return Void.class; } }).when(applicationConfig).addChangeListener(any(ConfigChangeListener.class)); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { fxApolloListeners.add(invocation.getArgumentAt(0, ConfigChangeListener.class)); return Void.class; } }).when(fxApolloConfig).addChangeListener(any(ConfigChangeListener.class)); ConfigChangeEvent someEvent = mock(ConfigChangeEvent.class); ConfigChangeEvent anotherEvent = mock(ConfigChangeEvent.class); TestApolloConfigChangeListenerBean1 bean = getBean(TestApolloConfigChangeListenerBean1.class, AppConfig3.class); //PropertySourcesProcessor add listeners to listen config changed of all namespace assertEquals(4, applicationListeners.size()); assertEquals(1, fxApolloListeners.size()); for (ConfigChangeListener listener : applicationListeners) { listener.onChange(someEvent); } assertEquals(someEvent, bean.getChangeEvent1()); assertEquals(someEvent, bean.getChangeEvent2()); assertEquals(someEvent, bean.getChangeEvent3()); for (ConfigChangeListener listener : fxApolloListeners) { listener.onChange(anotherEvent); } assertEquals(someEvent, bean.getChangeEvent1()); assertEquals(someEvent, bean.getChangeEvent2()); assertEquals(anotherEvent, bean.getChangeEvent3()); } @Test(expected = BeanCreationException.class) public void testApolloConfigChangeListenerWithWrongParamType() throws Exception { Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); getBean(TestApolloConfigChangeListenerBean2.class, AppConfig4.class); } @Test(expected = BeanCreationException.class) public void testApolloConfigChangeListenerWithWrongParamCount() throws Exception { Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); getBean(TestApolloConfigChangeListenerBean3.class, AppConfig5.class); } @Test public void testApolloConfigChangeListenerWithInheritance() throws Exception { Config applicationConfig = mock(Config.class); Config fxApolloConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); final List<ConfigChangeListener> applicationListeners = Lists.newArrayList(); final List<ConfigChangeListener> fxApolloListeners = Lists.newArrayList(); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { applicationListeners.add(invocation.getArgumentAt(0, ConfigChangeListener.class)); return Void.class; } }).when(applicationConfig).addChangeListener(any(ConfigChangeListener.class)); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { fxApolloListeners.add(invocation.getArgumentAt(0, ConfigChangeListener.class)); return Void.class; } }).when(fxApolloConfig).addChangeListener(any(ConfigChangeListener.class)); ConfigChangeEvent someEvent = mock(ConfigChangeEvent.class); ConfigChangeEvent anotherEvent = mock(ConfigChangeEvent.class); TestApolloChildConfigChangeListener bean = getBean(TestApolloChildConfigChangeListener.class, AppConfig7.class); //PropertySourcesProcessor add listeners to listen config changed of all namespace assertEquals(5, applicationListeners.size()); assertEquals(1, fxApolloListeners.size()); for (ConfigChangeListener listener : applicationListeners) { listener.onChange(someEvent); } assertEquals(someEvent, bean.getChangeEvent1()); assertEquals(someEvent, bean.getChangeEvent2()); assertEquals(someEvent, bean.getChangeEvent3()); assertEquals(someEvent, bean.getSomeChangeEvent()); for (ConfigChangeListener listener : fxApolloListeners) { listener.onChange(anotherEvent); } assertEquals(someEvent, bean.getChangeEvent1()); assertEquals(someEvent, bean.getChangeEvent2()); assertEquals(anotherEvent, bean.getChangeEvent3()); assertEquals(someEvent, bean.getSomeChangeEvent()); } @Test public void testApolloConfigChangeListenerWithInterestedKeys() throws Exception { Config applicationConfig = mock(Config.class); Config fxApolloConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); TestApolloConfigChangeListenerWithInterestedKeysBean bean = getBean( TestApolloConfigChangeListenerWithInterestedKeysBean.class, AppConfig8.class); final ArgumentCaptor<Set> applicationConfigInterestedKeys = ArgumentCaptor.forClass(Set.class); final ArgumentCaptor<Set> fxApolloConfigInterestedKeys = ArgumentCaptor.forClass(Set.class); verify(applicationConfig, times(2)) .addChangeListener(any(ConfigChangeListener.class), applicationConfigInterestedKeys.capture(), anySetOf(String.class)); verify(fxApolloConfig, times(1)) .addChangeListener(any(ConfigChangeListener.class), fxApolloConfigInterestedKeys.capture(), anySetOf(String.class)); assertEquals(2, applicationConfigInterestedKeys.getAllValues().size()); Set<String> result = Sets.newHashSet(); for (Set interestedKeys : applicationConfigInterestedKeys.getAllValues()) { result.addAll(interestedKeys); } assertEquals(Sets.newHashSet("someKey", "anotherKey"), result); assertEquals(1, fxApolloConfigInterestedKeys.getAllValues().size()); assertEquals(Collections.singletonList(Sets.newHashSet("anotherKey")), fxApolloConfigInterestedKeys.getAllValues()); } @Test public void testApolloConfigChangeListenerWithInterestedKeyPrefixes() { Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean bean = getBean( TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean.class, AppConfig10.class); final ArgumentCaptor<Set> interestedKeyPrefixesArgumentCaptor = ArgumentCaptor .forClass(Set.class); verify(applicationConfig, times(1)) .addChangeListener(any(ConfigChangeListener.class), anySetOf(String.class), interestedKeyPrefixesArgumentCaptor.capture()); assertEquals(1, interestedKeyPrefixesArgumentCaptor.getAllValues().size()); Set<String> result = Sets.newHashSet(); for (Set<String> interestedKeyPrefixes : interestedKeyPrefixesArgumentCaptor.getAllValues()) { result.addAll(interestedKeyPrefixes); } assertEquals(Sets.newHashSet("logging.level", "number"), result); } @Test public void testApolloConfigChangeListenerWithInterestedKeyPrefixes_fire() { // default mock, useless here // just for speed up test without waiting mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); SimpleConfig simpleConfig = spy( this.prepareConfig( TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1.SPECIAL_NAMESPACE, new Properties())); mockConfig(TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1.SPECIAL_NAMESPACE, simpleConfig); TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1 bean = getBean( TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1.class, AppConfig11.class); verify(simpleConfig, atLeastOnce()) .addChangeListener(any(ConfigChangeListener.class), anySetOf(String.class), anySetOf(String.class)); Properties properties = new Properties(); properties.put("logging.level.com", "debug"); properties.put("logging.level.root", "warn"); properties.put("number.value", "333"); // publish config change simpleConfig.onRepositoryChange( TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1.SPECIAL_NAMESPACE, properties); // get event from bean ConfigChangeEvent configChangeEvent = bean.getConfigChangeEvent(); Set<String> interestedChangedKeys = configChangeEvent.interestedChangedKeys(); assertEquals(Sets.newHashSet("logging.level.com", "logging.level.root", "number.value"), interestedChangedKeys); } @Test public void testApolloConfigChangeListenerWithYamlFile() throws Exception { String someKey = "someKey"; String someValue = "someValue"; String anotherValue = "anotherValue"; YamlConfigFile configFile = prepareYamlConfigFile(APPLICATION_YAML_NAMESPACE, readYamlContentAsConfigFileProperties("case9.yml")); TestApolloConfigChangeListenerWithYamlFile bean = getBean(TestApolloConfigChangeListenerWithYamlFile.class, AppConfig9.class); Config yamlConfig = bean.getYamlConfig(); SettableFuture<ConfigChangeEvent> future = bean.getConfigChangeEventFuture(); assertEquals(someValue, yamlConfig.getProperty(someKey, null)); assertFalse(future.isDone()); configFile.onRepositoryChange(APPLICATION_YAML_NAMESPACE, readYamlContentAsConfigFileProperties("case9-new.yml")); ConfigChangeEvent configChangeEvent = future.get(100, TimeUnit.MILLISECONDS); ConfigChange change = configChangeEvent.getChange(someKey); assertEquals(someValue, change.getOldValue()); assertEquals(anotherValue, change.getNewValue()); assertEquals(anotherValue, yamlConfig.getProperty(someKey, null)); } @Test public void testApolloConfigChangeListenerResolveExpressionSimple() { // for ignore, no listener use it Config ignoreConfig = mock(Config.class); mockConfig("ignore.for.listener", ignoreConfig); Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); getSimpleBean(TestApolloConfigChangeListenerResolveExpressionSimpleConfiguration.class); // no using verify(ignoreConfig, never()).addChangeListener(any(ConfigChangeListener.class)); // one invocation for spring value auto update and another for the @ApolloConfigChangeListener annotation verify(applicationConfig, times(2)).addChangeListener(any(ConfigChangeListener.class)); } /** * resolve namespace's name from system property. */ @Test public void testApolloConfigChangeListenerResolveExpressionFromSystemProperty() { Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); final String namespaceName = "magicRedis"; System.setProperty(SystemPropertyKeyConstants.REDIS_NAMESPACE, namespaceName); Config redisConfig = mock(Config.class); mockConfig(namespaceName, redisConfig); getSimpleBean( TestApolloConfigChangeListenerResolveExpressionFromSystemPropertyConfiguration.class); // if config was used, it must be invoked on method addChangeListener 1 time verify(redisConfig, times(1)).addChangeListener(any(ConfigChangeListener.class)); } /** * resolve namespace from config. ${mysql.namespace} will be resolved by config from namespace * application. */ @Test public void testApolloConfigChangeListenerResolveExpressionFromApplicationNamespace() { final String namespaceKey = "mysql.namespace"; final String namespaceName = "magicMysqlNamespaceApplication"; Properties properties = new Properties(); properties.setProperty(namespaceKey, namespaceName); this.prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); Config mysqlConfig = mock(Config.class); mockConfig(namespaceName, mysqlConfig); getSimpleBean( TestApolloConfigChangeListenerResolveExpressionFromApplicationNamespaceConfiguration.class); // if config was used, it must be invoked on method addChangeListener 1 time verify(mysqlConfig, times(1)).addChangeListener(any(ConfigChangeListener.class)); } @Test(expected = BeanCreationException.class) public void testApolloConfigChangeListenerUnresolvedPlaceholder() { Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); getSimpleBean(TestApolloConfigChangeListenerUnresolvedPlaceholderConfiguration.class); } @Test public void testApolloConfigChangeListenerResolveExpressionFromSelfYaml() throws IOException { mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); final String resolvedValue = "resolve.from.self.yml"; YamlConfigFile yamlConfigFile = prepareYamlConfigFile(resolvedValue, readYamlContentAsConfigFileProperties(resolvedValue)); getSimpleBean(TestApolloConfigChangeListenerResolveExpressionFromSelfYamlConfiguration.class); verify(yamlConfigFile, times(1)).addChangeListener(any(ConfigFileChangeListener.class)); } @Test public void testApolloConfigResolveExpressionDefault() { mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); Config defaultConfig = mock(Config.class); Config yamlConfig = mock(Config.class); mockConfig("default-2020-11-14-1733", defaultConfig); mockConfig(APPLICATION_YAML_NAMESPACE, yamlConfig); TestApolloConfigResolveExpressionDefaultConfiguration configuration = getSimpleBean( TestApolloConfigResolveExpressionDefaultConfiguration.class); assertSame(defaultConfig, configuration.getDefaultConfig()); assertSame(yamlConfig, configuration.getYamlConfig()); } @Test public void testApolloConfigResolveExpressionFromSystemProperty() { mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); final String namespaceName = "xxx6"; final String yamlNamespaceName = "yyy8.yml"; System.setProperty(SystemPropertyKeyConstants.FROM_SYSTEM_NAMESPACE, namespaceName); System.setProperty(SystemPropertyKeyConstants.FROM_SYSTEM_YAML_NAMESPACE, yamlNamespaceName); Config config = mock(Config.class); Config yamlConfig = mock(Config.class); mockConfig(namespaceName, config); mockConfig(yamlNamespaceName, yamlConfig); TestApolloConfigResolveExpressionFromSystemPropertyConfiguration configuration = getSimpleBean( TestApolloConfigResolveExpressionFromSystemPropertyConfiguration.class); assertSame(config, configuration.getConfig()); assertSame(yamlConfig, configuration.getYamlConfig()); } @Test(expected = BeanCreationException.class) public void testApolloConfigUnresolvedExpression() { mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); getSimpleBean(TestApolloConfigUnresolvedExpressionConfiguration.class); } @Test public void testApolloConfigResolveExpressionFromApolloConfigNamespaceApplication() { final String namespaceName = "xxx6"; final String yamlNamespaceName = "yyy8.yml"; { // hide variable scope Properties properties = new Properties(); properties.setProperty(SystemPropertyKeyConstants.FROM_NAMESPACE_APPLICATION_KEY, namespaceName); properties.setProperty(SystemPropertyKeyConstants.FROM_NAMESPACE_APPLICATION_KEY_YAML, yamlNamespaceName); this.prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); } final Config config = mock(Config.class); final Config yamlConfig = mock(Config.class); mockConfig(namespaceName, config); mockConfig(yamlNamespaceName, yamlConfig); TestApolloConfigResolveExpressionFromApolloConfigNamespaceApplication configuration = getSimpleBean( TestApolloConfigResolveExpressionFromApolloConfigNamespaceApplication.class); assertSame(config, configuration.getConfig()); assertSame(yamlConfig, configuration.getYamlConfig()); } private static class SystemPropertyKeyConstants { static final String SIMPLE_NAMESPACE = "simple.namespace"; static final String REDIS_NAMESPACE = "redis.namespace"; static final String FROM_SYSTEM_NAMESPACE = "from.system.namespace"; static final String FROM_SYSTEM_YAML_NAMESPACE = "from.system.yaml.namespace"; static final String FROM_NAMESPACE_APPLICATION_KEY = "from.namespace.application.key"; static final String FROM_NAMESPACE_APPLICATION_KEY_YAML = "from.namespace.application.key.yaml"; } @EnableApolloConfig protected static class TestApolloConfigResolveExpressionDefaultConfiguration { @ApolloConfig(value = "${simple.namespace:default-2020-11-14-1733}") private Config defaultConfig; @ApolloConfig(value = "${simple.yaml.namespace:" + APPLICATION_YAML_NAMESPACE + "}") private Config yamlConfig; public Config getDefaultConfig() { return defaultConfig; } public Config getYamlConfig() { return yamlConfig; } } @EnableApolloConfig protected static class TestApolloConfigResolveExpressionFromSystemPropertyConfiguration { @ApolloConfig(value = "${from.system.namespace}") private Config config; @ApolloConfig(value = "${from.system.yaml.namespace}") private Config yamlConfig; public Config getConfig() { return config; } public Config getYamlConfig() { return yamlConfig; } } @EnableApolloConfig protected static class TestApolloConfigUnresolvedExpressionConfiguration { @ApolloConfig(value = "${so.complex.to.resolve}") private Config config; } @EnableApolloConfig protected static class TestApolloConfigResolveExpressionFromApolloConfigNamespaceApplication { @ApolloConfig(value = "${from.namespace.application.key}") private Config config; @ApolloConfig(value = "${from.namespace.application.key.yaml}") private Config yamlConfig; public Config getConfig() { return config; } public Config getYamlConfig() { return yamlConfig; } } @Configuration @EnableApolloConfig static class TestApolloConfigChangeListenerResolveExpressionSimpleConfiguration { @ApolloConfigChangeListener("${simple.application:application}") private void onChange(ConfigChangeEvent event) { } } @Configuration @EnableApolloConfig static class TestApolloConfigChangeListenerResolveExpressionFromSystemPropertyConfiguration { @ApolloConfigChangeListener("${redis.namespace}") private void onChange(ConfigChangeEvent event) { } } @Configuration @EnableApolloConfig static class TestApolloConfigChangeListenerResolveExpressionFromApplicationNamespaceConfiguration { @ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, "${mysql.namespace}"}) private void onChange(ConfigChangeEvent event) { } } @Configuration @EnableApolloConfig static class TestApolloConfigChangeListenerUnresolvedPlaceholderConfiguration { @ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, "${i.can.not.be.resolved}"}) private void onChange(ConfigChangeEvent event) { } } @Configuration @EnableApolloConfig("resolve.from.self.yml") static class TestApolloConfigChangeListenerResolveExpressionFromSelfYamlConfiguration { /** * value in file src/test/resources/spring/yaml/resolve.from.self.yml */ @ApolloConfigChangeListener("${i.can.resolve.from.self}") private void onChange(ConfigChangeEvent event) { } } @Configuration @EnableApolloConfig(value = {ConfigConsts.NAMESPACE_APPLICATION, "${simple.namespace:xxx}"}) static class TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration { @Value("${someKey-2020-11-14-1750}") private String someKey; public String getSomeKey() { return this.someKey; } } @Configuration @EnableApolloConfig(value = "${unresolvable.property}") static class TestEnableApolloConfigUnresolvableConfiguration { } @Configuration @EnableApolloConfig static class AppConfig1 { @Bean public TestApolloConfigBean1 bean() { return new TestApolloConfigBean1(); } } @Configuration @EnableApolloConfig static class AppConfig2 { @Bean public TestApolloConfigBean2 bean() { return new TestApolloConfigBean2(); } } @Configuration @EnableApolloConfig static class AppConfig3 { @Bean public TestApolloConfigChangeListenerBean1 bean() { return new TestApolloConfigChangeListenerBean1(); } } @Configuration @EnableApolloConfig static class AppConfig4 { @Bean public TestApolloConfigChangeListenerBean2 bean() { return new TestApolloConfigChangeListenerBean2(); } } @Configuration @EnableApolloConfig static class AppConfig5 { @Bean public TestApolloConfigChangeListenerBean3 bean() { return new TestApolloConfigChangeListenerBean3(); } } @Configuration @EnableApolloConfig static class AppConfig6 { @Bean public TestApolloChildConfigBean bean() { return new TestApolloChildConfigBean(); } } @Configuration @EnableApolloConfig static class AppConfig7 { @Bean public TestApolloChildConfigChangeListener bean() { return new TestApolloChildConfigChangeListener(); } } @Configuration @EnableApolloConfig static class AppConfig8 { @Bean public TestApolloConfigChangeListenerWithInterestedKeysBean bean() { return new TestApolloConfigChangeListenerWithInterestedKeysBean(); } } @Configuration @EnableApolloConfig(APPLICATION_YAML_NAMESPACE) static class AppConfig9 { @Bean public TestApolloConfigChangeListenerWithYamlFile bean() { return new TestApolloConfigChangeListenerWithYamlFile(); } } @Configuration @EnableApolloConfig static class AppConfig10 { @Bean public TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean bean() { return new TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean(); } } @Configuration @EnableApolloConfig static class AppConfig11 { @Bean public TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1 bean() { return spy(new TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1()); } } static class TestApolloConfigBean1 { @ApolloConfig private Config config; @ApolloConfig(ConfigConsts.NAMESPACE_APPLICATION) private Config anotherConfig; @ApolloConfig(FX_APOLLO_NAMESPACE) private Config yetAnotherConfig; @ApolloConfig(APPLICATION_YAML_NAMESPACE) private Config yamlConfig; public Config getConfig() { return config; } public Config getAnotherConfig() { return anotherConfig; } public Config getYetAnotherConfig() { return yetAnotherConfig; } public Config getYamlConfig() { return yamlConfig; } } static class TestApolloConfigBean2 { @ApolloConfig private String config; } static class TestApolloChildConfigBean extends TestApolloConfigBean1 { @ApolloConfig private Config someConfig; public Config getSomeConfig() { return someConfig; } } static class TestApolloConfigChangeListenerBean1 { private ConfigChangeEvent changeEvent1; private ConfigChangeEvent changeEvent2; private ConfigChangeEvent changeEvent3; @ApolloConfigChangeListener private void onChange1(ConfigChangeEvent changeEvent) { this.changeEvent1 = changeEvent; } @ApolloConfigChangeListener(ConfigConsts.NAMESPACE_APPLICATION) private void onChange2(ConfigChangeEvent changeEvent) { this.changeEvent2 = changeEvent; } @ApolloConfigChangeListener({ConfigConsts.NAMESPACE_APPLICATION, FX_APOLLO_NAMESPACE}) private void onChange3(ConfigChangeEvent changeEvent) { this.changeEvent3 = changeEvent; } public ConfigChangeEvent getChangeEvent1() { return changeEvent1; } public ConfigChangeEvent getChangeEvent2() { return changeEvent2; } public ConfigChangeEvent getChangeEvent3() { return changeEvent3; } } static class TestApolloConfigChangeListenerBean2 { @ApolloConfigChangeListener private void onChange(String event) { } } static class TestApolloConfigChangeListenerBean3 { @ApolloConfigChangeListener private void onChange(ConfigChangeEvent event, String someParam) { } } static class TestApolloChildConfigChangeListener extends TestApolloConfigChangeListenerBean1 { private ConfigChangeEvent someChangeEvent; @ApolloConfigChangeListener private void someOnChange(ConfigChangeEvent changeEvent) { this.someChangeEvent = changeEvent; } public ConfigChangeEvent getSomeChangeEvent() { return someChangeEvent; } } static class TestApolloConfigChangeListenerWithInterestedKeysBean { @ApolloConfigChangeListener(interestedKeys = {"someKey"}) private void someOnChange(ConfigChangeEvent changeEvent) {} @ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, FX_APOLLO_NAMESPACE}, interestedKeys = {"anotherKey"}) private void anotherOnChange(ConfigChangeEvent changeEvent) { } } private static class TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean { @ApolloConfigChangeListener(interestedKeyPrefixes = {"number", "logging.level"}) private void onChange(ConfigChangeEvent changeEvent) { } } private static class TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1 { static final String SPECIAL_NAMESPACE = "special-namespace-2021"; private final Queue<ConfigChangeEvent> configChangeEventQueue = new ArrayBlockingQueue<>(100); @ApolloConfigChangeListener(value = SPECIAL_NAMESPACE, interestedKeyPrefixes = {"number", "logging.level"}) private void onChange(ConfigChangeEvent changeEvent) { this.configChangeEventQueue.add(changeEvent); } public ConfigChangeEvent getConfigChangeEvent() { return this.configChangeEventQueue.poll(); } } static class TestApolloConfigChangeListenerWithYamlFile { private SettableFuture<ConfigChangeEvent> configChangeEventFuture = SettableFuture.create(); @ApolloConfig(APPLICATION_YAML_NAMESPACE) private Config yamlConfig; @ApolloConfigChangeListener(APPLICATION_YAML_NAMESPACE) private void onChange(ConfigChangeEvent event) { configChangeEventFuture.set(event); } public SettableFuture<ConfigChangeEvent> getConfigChangeEventFuture() { return configChangeEventFuture; } public Config getYamlConfig() { return yamlConfig; } } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.spring; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigChangeListener; import com.ctrip.framework.apollo.ConfigFileChangeListener; import com.ctrip.framework.apollo.core.ConfigConsts; import com.ctrip.framework.apollo.internals.SimpleConfig; import com.ctrip.framework.apollo.internals.YamlConfigFile; import com.ctrip.framework.apollo.model.ConfigChange; import com.ctrip.framework.apollo.model.ConfigChangeEvent; import com.ctrip.framework.apollo.spring.annotation.ApolloConfig; import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener; import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.SettableFuture; import java.io.IOException; import java.util.Collections; import java.util.Properties; import java.util.UUID; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anySetOf; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * @author Jason Song(song_s@ctrip.com) */ public class JavaConfigAnnotationTest extends AbstractSpringIntegrationTest { private static final String FX_APOLLO_NAMESPACE = "FX.apollo"; private static final String APPLICATION_YAML_NAMESPACE = "application.yaml"; private static <T> T getBean(Class<T> beanClass, Class<?>... annotatedClasses) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(annotatedClasses); return context.getBean(beanClass); } private static <T> T getSimpleBean(Class<? extends T> clazz) { return getBean(clazz, clazz); } @Override @After public void tearDown() throws Exception { // clear the system properties System.clearProperty(SystemPropertyKeyConstants.SIMPLE_NAMESPACE); System.clearProperty(SystemPropertyKeyConstants.REDIS_NAMESPACE); System.clearProperty(SystemPropertyKeyConstants.FROM_SYSTEM_NAMESPACE); System.clearProperty(SystemPropertyKeyConstants.FROM_SYSTEM_YAML_NAMESPACE); System.clearProperty(SystemPropertyKeyConstants.FROM_NAMESPACE_APPLICATION_KEY); System.clearProperty(SystemPropertyKeyConstants.FROM_NAMESPACE_APPLICATION_KEY_YAML); super.tearDown(); } @Test public void testApolloConfig() throws Exception { Config applicationConfig = mock(Config.class); Config fxApolloConfig = mock(Config.class); String someKey = "someKey"; String someValue = "someValue"; mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); prepareYamlConfigFile(APPLICATION_YAML_NAMESPACE, readYamlContentAsConfigFileProperties("case9.yml")); TestApolloConfigBean1 bean = getBean(TestApolloConfigBean1.class, AppConfig1.class); assertEquals(applicationConfig, bean.getConfig()); assertEquals(applicationConfig, bean.getAnotherConfig()); assertEquals(fxApolloConfig, bean.getYetAnotherConfig()); Config yamlConfig = bean.getYamlConfig(); assertEquals(someValue, yamlConfig.getProperty(someKey, null)); } @Test(expected = BeanCreationException.class) public void testApolloConfigWithWrongFieldType() throws Exception { Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); getBean(TestApolloConfigBean2.class, AppConfig2.class); } @Test public void testApolloConfigWithInheritance() throws Exception { Config applicationConfig = mock(Config.class); Config fxApolloConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); prepareYamlConfigFile(APPLICATION_YAML_NAMESPACE, readYamlContentAsConfigFileProperties("case9.yml")); TestApolloChildConfigBean bean = getBean(TestApolloChildConfigBean.class, AppConfig6.class); assertEquals(applicationConfig, bean.getConfig()); assertEquals(applicationConfig, bean.getAnotherConfig()); assertEquals(fxApolloConfig, bean.getYetAnotherConfig()); assertEquals(applicationConfig, bean.getSomeConfig()); } @Test public void testEnableApolloConfigResolveExpressionSimple() { String someKey = "someKey-2020-11-14-1750"; String someValue = UUID.randomUUID().toString(); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); Config xxxConfig = mock(Config.class); when(xxxConfig.getProperty(eq(someKey), anyString())).thenReturn(someValue); mockConfig("xxx", xxxConfig); TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration configuration = getSimpleBean(TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration.class); // check assertEquals(someValue, configuration.getSomeKey()); verify(xxxConfig, times(1)).getProperty(eq(someKey), anyString()); } @Test public void testEnableApolloConfigResolveExpressionFromSystemProperty() { mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); final String someKey = "someKey-2020-11-14-1750"; final String someValue = UUID.randomUUID().toString(); final String resolvedNamespaceName = "yyy"; System.setProperty(SystemPropertyKeyConstants.SIMPLE_NAMESPACE, resolvedNamespaceName); Config yyyConfig = mock(Config.class); when(yyyConfig.getProperty(eq(someKey), anyString())).thenReturn(someValue); mockConfig(resolvedNamespaceName, yyyConfig); TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration configuration = getSimpleBean(TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration.class); // check assertEquals(someValue, configuration.getSomeKey()); verify(yyyConfig, times(1)).getProperty(eq(someKey), anyString()); } @Test(expected = BeanCreationException.class) public void testEnableApolloConfigUnresolvedValueInField() { mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); mockConfig("xxx", mock(Config.class)); getSimpleBean(TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration.class); } @Test(expected = IllegalArgumentException.class) public void testEnableApolloConfigUnresolvable() { getSimpleBean(TestEnableApolloConfigUnresolvableConfiguration.class); } @Test public void testApolloConfigChangeListener() throws Exception { Config applicationConfig = mock(Config.class); Config fxApolloConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); final List<ConfigChangeListener> applicationListeners = Lists.newArrayList(); final List<ConfigChangeListener> fxApolloListeners = Lists.newArrayList(); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { applicationListeners.add(invocation.getArgumentAt(0, ConfigChangeListener.class)); return Void.class; } }).when(applicationConfig).addChangeListener(any(ConfigChangeListener.class)); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { fxApolloListeners.add(invocation.getArgumentAt(0, ConfigChangeListener.class)); return Void.class; } }).when(fxApolloConfig).addChangeListener(any(ConfigChangeListener.class)); ConfigChangeEvent someEvent = mock(ConfigChangeEvent.class); ConfigChangeEvent anotherEvent = mock(ConfigChangeEvent.class); TestApolloConfigChangeListenerBean1 bean = getBean(TestApolloConfigChangeListenerBean1.class, AppConfig3.class); //PropertySourcesProcessor add listeners to listen config changed of all namespace assertEquals(4, applicationListeners.size()); assertEquals(1, fxApolloListeners.size()); for (ConfigChangeListener listener : applicationListeners) { listener.onChange(someEvent); } assertEquals(someEvent, bean.getChangeEvent1()); assertEquals(someEvent, bean.getChangeEvent2()); assertEquals(someEvent, bean.getChangeEvent3()); for (ConfigChangeListener listener : fxApolloListeners) { listener.onChange(anotherEvent); } assertEquals(someEvent, bean.getChangeEvent1()); assertEquals(someEvent, bean.getChangeEvent2()); assertEquals(anotherEvent, bean.getChangeEvent3()); } @Test(expected = BeanCreationException.class) public void testApolloConfigChangeListenerWithWrongParamType() throws Exception { Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); getBean(TestApolloConfigChangeListenerBean2.class, AppConfig4.class); } @Test(expected = BeanCreationException.class) public void testApolloConfigChangeListenerWithWrongParamCount() throws Exception { Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); getBean(TestApolloConfigChangeListenerBean3.class, AppConfig5.class); } @Test public void testApolloConfigChangeListenerWithInheritance() throws Exception { Config applicationConfig = mock(Config.class); Config fxApolloConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); final List<ConfigChangeListener> applicationListeners = Lists.newArrayList(); final List<ConfigChangeListener> fxApolloListeners = Lists.newArrayList(); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { applicationListeners.add(invocation.getArgumentAt(0, ConfigChangeListener.class)); return Void.class; } }).when(applicationConfig).addChangeListener(any(ConfigChangeListener.class)); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { fxApolloListeners.add(invocation.getArgumentAt(0, ConfigChangeListener.class)); return Void.class; } }).when(fxApolloConfig).addChangeListener(any(ConfigChangeListener.class)); ConfigChangeEvent someEvent = mock(ConfigChangeEvent.class); ConfigChangeEvent anotherEvent = mock(ConfigChangeEvent.class); TestApolloChildConfigChangeListener bean = getBean(TestApolloChildConfigChangeListener.class, AppConfig7.class); //PropertySourcesProcessor add listeners to listen config changed of all namespace assertEquals(5, applicationListeners.size()); assertEquals(1, fxApolloListeners.size()); for (ConfigChangeListener listener : applicationListeners) { listener.onChange(someEvent); } assertEquals(someEvent, bean.getChangeEvent1()); assertEquals(someEvent, bean.getChangeEvent2()); assertEquals(someEvent, bean.getChangeEvent3()); assertEquals(someEvent, bean.getSomeChangeEvent()); for (ConfigChangeListener listener : fxApolloListeners) { listener.onChange(anotherEvent); } assertEquals(someEvent, bean.getChangeEvent1()); assertEquals(someEvent, bean.getChangeEvent2()); assertEquals(anotherEvent, bean.getChangeEvent3()); assertEquals(someEvent, bean.getSomeChangeEvent()); } @Test public void testApolloConfigChangeListenerWithInterestedKeys() throws Exception { Config applicationConfig = mock(Config.class); Config fxApolloConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); TestApolloConfigChangeListenerWithInterestedKeysBean bean = getBean( TestApolloConfigChangeListenerWithInterestedKeysBean.class, AppConfig8.class); final ArgumentCaptor<Set> applicationConfigInterestedKeys = ArgumentCaptor.forClass(Set.class); final ArgumentCaptor<Set> fxApolloConfigInterestedKeys = ArgumentCaptor.forClass(Set.class); verify(applicationConfig, times(2)) .addChangeListener(any(ConfigChangeListener.class), applicationConfigInterestedKeys.capture(), anySetOf(String.class)); verify(fxApolloConfig, times(1)) .addChangeListener(any(ConfigChangeListener.class), fxApolloConfigInterestedKeys.capture(), anySetOf(String.class)); assertEquals(2, applicationConfigInterestedKeys.getAllValues().size()); Set<String> result = Sets.newHashSet(); for (Set interestedKeys : applicationConfigInterestedKeys.getAllValues()) { result.addAll(interestedKeys); } assertEquals(Sets.newHashSet("someKey", "anotherKey"), result); assertEquals(1, fxApolloConfigInterestedKeys.getAllValues().size()); assertEquals(Collections.singletonList(Sets.newHashSet("anotherKey")), fxApolloConfigInterestedKeys.getAllValues()); } @Test public void testApolloConfigChangeListenerWithInterestedKeyPrefixes() { Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean bean = getBean( TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean.class, AppConfig10.class); final ArgumentCaptor<Set> interestedKeyPrefixesArgumentCaptor = ArgumentCaptor .forClass(Set.class); verify(applicationConfig, times(1)) .addChangeListener(any(ConfigChangeListener.class), anySetOf(String.class), interestedKeyPrefixesArgumentCaptor.capture()); assertEquals(1, interestedKeyPrefixesArgumentCaptor.getAllValues().size()); Set<String> result = Sets.newHashSet(); for (Set<String> interestedKeyPrefixes : interestedKeyPrefixesArgumentCaptor.getAllValues()) { result.addAll(interestedKeyPrefixes); } assertEquals(Sets.newHashSet("logging.level", "number"), result); } @Test public void testApolloConfigChangeListenerWithInterestedKeyPrefixes_fire() throws InterruptedException { // default mock, useless here // just for speed up test without waiting mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); SimpleConfig simpleConfig = spy( this.prepareConfig( TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1.SPECIAL_NAMESPACE, new Properties())); mockConfig(TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1.SPECIAL_NAMESPACE, simpleConfig); TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1 bean = getBean( TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1.class, AppConfig11.class); verify(simpleConfig, atLeastOnce()) .addChangeListener(any(ConfigChangeListener.class), anySetOf(String.class), anySetOf(String.class)); Properties properties = new Properties(); properties.put("logging.level.com", "debug"); properties.put("logging.level.root", "warn"); properties.put("number.value", "333"); // publish config change simpleConfig.onRepositoryChange( TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1.SPECIAL_NAMESPACE, properties); // get event from bean ConfigChangeEvent configChangeEvent = bean.getConfigChangeEvent(); Set<String> interestedChangedKeys = configChangeEvent.interestedChangedKeys(); assertEquals(Sets.newHashSet("logging.level.com", "logging.level.root", "number.value"), interestedChangedKeys); } @Test public void testApolloConfigChangeListenerWithYamlFile() throws Exception { String someKey = "someKey"; String someValue = "someValue"; String anotherValue = "anotherValue"; YamlConfigFile configFile = prepareYamlConfigFile(APPLICATION_YAML_NAMESPACE, readYamlContentAsConfigFileProperties("case9.yml")); TestApolloConfigChangeListenerWithYamlFile bean = getBean(TestApolloConfigChangeListenerWithYamlFile.class, AppConfig9.class); Config yamlConfig = bean.getYamlConfig(); SettableFuture<ConfigChangeEvent> future = bean.getConfigChangeEventFuture(); assertEquals(someValue, yamlConfig.getProperty(someKey, null)); assertFalse(future.isDone()); configFile.onRepositoryChange(APPLICATION_YAML_NAMESPACE, readYamlContentAsConfigFileProperties("case9-new.yml")); ConfigChangeEvent configChangeEvent = future.get(100, TimeUnit.MILLISECONDS); ConfigChange change = configChangeEvent.getChange(someKey); assertEquals(someValue, change.getOldValue()); assertEquals(anotherValue, change.getNewValue()); assertEquals(anotherValue, yamlConfig.getProperty(someKey, null)); } @Test public void testApolloConfigChangeListenerResolveExpressionSimple() { // for ignore, no listener use it Config ignoreConfig = mock(Config.class); mockConfig("ignore.for.listener", ignoreConfig); Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); getSimpleBean(TestApolloConfigChangeListenerResolveExpressionSimpleConfiguration.class); // no using verify(ignoreConfig, never()).addChangeListener(any(ConfigChangeListener.class)); // one invocation for spring value auto update and another for the @ApolloConfigChangeListener annotation verify(applicationConfig, times(2)).addChangeListener(any(ConfigChangeListener.class)); } /** * resolve namespace's name from system property. */ @Test public void testApolloConfigChangeListenerResolveExpressionFromSystemProperty() { Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); final String namespaceName = "magicRedis"; System.setProperty(SystemPropertyKeyConstants.REDIS_NAMESPACE, namespaceName); Config redisConfig = mock(Config.class); mockConfig(namespaceName, redisConfig); getSimpleBean( TestApolloConfigChangeListenerResolveExpressionFromSystemPropertyConfiguration.class); // if config was used, it must be invoked on method addChangeListener 1 time verify(redisConfig, times(1)).addChangeListener(any(ConfigChangeListener.class)); } /** * resolve namespace from config. ${mysql.namespace} will be resolved by config from namespace * application. */ @Test public void testApolloConfigChangeListenerResolveExpressionFromApplicationNamespace() { final String namespaceKey = "mysql.namespace"; final String namespaceName = "magicMysqlNamespaceApplication"; Properties properties = new Properties(); properties.setProperty(namespaceKey, namespaceName); this.prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); Config mysqlConfig = mock(Config.class); mockConfig(namespaceName, mysqlConfig); getSimpleBean( TestApolloConfigChangeListenerResolveExpressionFromApplicationNamespaceConfiguration.class); // if config was used, it must be invoked on method addChangeListener 1 time verify(mysqlConfig, times(1)).addChangeListener(any(ConfigChangeListener.class)); } @Test(expected = BeanCreationException.class) public void testApolloConfigChangeListenerUnresolvedPlaceholder() { Config applicationConfig = mock(Config.class); mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); getSimpleBean(TestApolloConfigChangeListenerUnresolvedPlaceholderConfiguration.class); } @Test public void testApolloConfigChangeListenerResolveExpressionFromSelfYaml() throws IOException { mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); final String resolvedValue = "resolve.from.self.yml"; YamlConfigFile yamlConfigFile = prepareYamlConfigFile(resolvedValue, readYamlContentAsConfigFileProperties(resolvedValue)); getSimpleBean(TestApolloConfigChangeListenerResolveExpressionFromSelfYamlConfiguration.class); verify(yamlConfigFile, times(1)).addChangeListener(any(ConfigFileChangeListener.class)); } @Test public void testApolloConfigResolveExpressionDefault() { mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); Config defaultConfig = mock(Config.class); Config yamlConfig = mock(Config.class); mockConfig("default-2020-11-14-1733", defaultConfig); mockConfig(APPLICATION_YAML_NAMESPACE, yamlConfig); TestApolloConfigResolveExpressionDefaultConfiguration configuration = getSimpleBean( TestApolloConfigResolveExpressionDefaultConfiguration.class); assertSame(defaultConfig, configuration.getDefaultConfig()); assertSame(yamlConfig, configuration.getYamlConfig()); } @Test public void testApolloConfigResolveExpressionFromSystemProperty() { mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); final String namespaceName = "xxx6"; final String yamlNamespaceName = "yyy8.yml"; System.setProperty(SystemPropertyKeyConstants.FROM_SYSTEM_NAMESPACE, namespaceName); System.setProperty(SystemPropertyKeyConstants.FROM_SYSTEM_YAML_NAMESPACE, yamlNamespaceName); Config config = mock(Config.class); Config yamlConfig = mock(Config.class); mockConfig(namespaceName, config); mockConfig(yamlNamespaceName, yamlConfig); TestApolloConfigResolveExpressionFromSystemPropertyConfiguration configuration = getSimpleBean( TestApolloConfigResolveExpressionFromSystemPropertyConfiguration.class); assertSame(config, configuration.getConfig()); assertSame(yamlConfig, configuration.getYamlConfig()); } @Test(expected = BeanCreationException.class) public void testApolloConfigUnresolvedExpression() { mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); getSimpleBean(TestApolloConfigUnresolvedExpressionConfiguration.class); } @Test public void testApolloConfigResolveExpressionFromApolloConfigNamespaceApplication() { final String namespaceName = "xxx6"; final String yamlNamespaceName = "yyy8.yml"; { // hide variable scope Properties properties = new Properties(); properties.setProperty(SystemPropertyKeyConstants.FROM_NAMESPACE_APPLICATION_KEY, namespaceName); properties.setProperty(SystemPropertyKeyConstants.FROM_NAMESPACE_APPLICATION_KEY_YAML, yamlNamespaceName); this.prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); } final Config config = mock(Config.class); final Config yamlConfig = mock(Config.class); mockConfig(namespaceName, config); mockConfig(yamlNamespaceName, yamlConfig); TestApolloConfigResolveExpressionFromApolloConfigNamespaceApplication configuration = getSimpleBean( TestApolloConfigResolveExpressionFromApolloConfigNamespaceApplication.class); assertSame(config, configuration.getConfig()); assertSame(yamlConfig, configuration.getYamlConfig()); } private static class SystemPropertyKeyConstants { static final String SIMPLE_NAMESPACE = "simple.namespace"; static final String REDIS_NAMESPACE = "redis.namespace"; static final String FROM_SYSTEM_NAMESPACE = "from.system.namespace"; static final String FROM_SYSTEM_YAML_NAMESPACE = "from.system.yaml.namespace"; static final String FROM_NAMESPACE_APPLICATION_KEY = "from.namespace.application.key"; static final String FROM_NAMESPACE_APPLICATION_KEY_YAML = "from.namespace.application.key.yaml"; } @EnableApolloConfig protected static class TestApolloConfigResolveExpressionDefaultConfiguration { @ApolloConfig(value = "${simple.namespace:default-2020-11-14-1733}") private Config defaultConfig; @ApolloConfig(value = "${simple.yaml.namespace:" + APPLICATION_YAML_NAMESPACE + "}") private Config yamlConfig; public Config getDefaultConfig() { return defaultConfig; } public Config getYamlConfig() { return yamlConfig; } } @EnableApolloConfig protected static class TestApolloConfigResolveExpressionFromSystemPropertyConfiguration { @ApolloConfig(value = "${from.system.namespace}") private Config config; @ApolloConfig(value = "${from.system.yaml.namespace}") private Config yamlConfig; public Config getConfig() { return config; } public Config getYamlConfig() { return yamlConfig; } } @EnableApolloConfig protected static class TestApolloConfigUnresolvedExpressionConfiguration { @ApolloConfig(value = "${so.complex.to.resolve}") private Config config; } @EnableApolloConfig protected static class TestApolloConfigResolveExpressionFromApolloConfigNamespaceApplication { @ApolloConfig(value = "${from.namespace.application.key}") private Config config; @ApolloConfig(value = "${from.namespace.application.key.yaml}") private Config yamlConfig; public Config getConfig() { return config; } public Config getYamlConfig() { return yamlConfig; } } @Configuration @EnableApolloConfig static class TestApolloConfigChangeListenerResolveExpressionSimpleConfiguration { @ApolloConfigChangeListener("${simple.application:application}") private void onChange(ConfigChangeEvent event) { } } @Configuration @EnableApolloConfig static class TestApolloConfigChangeListenerResolveExpressionFromSystemPropertyConfiguration { @ApolloConfigChangeListener("${redis.namespace}") private void onChange(ConfigChangeEvent event) { } } @Configuration @EnableApolloConfig static class TestApolloConfigChangeListenerResolveExpressionFromApplicationNamespaceConfiguration { @ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, "${mysql.namespace}"}) private void onChange(ConfigChangeEvent event) { } } @Configuration @EnableApolloConfig static class TestApolloConfigChangeListenerUnresolvedPlaceholderConfiguration { @ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, "${i.can.not.be.resolved}"}) private void onChange(ConfigChangeEvent event) { } } @Configuration @EnableApolloConfig("resolve.from.self.yml") static class TestApolloConfigChangeListenerResolveExpressionFromSelfYamlConfiguration { /** * value in file src/test/resources/spring/yaml/resolve.from.self.yml */ @ApolloConfigChangeListener("${i.can.resolve.from.self}") private void onChange(ConfigChangeEvent event) { } } @Configuration @EnableApolloConfig(value = {ConfigConsts.NAMESPACE_APPLICATION, "${simple.namespace:xxx}"}) static class TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration { @Value("${someKey-2020-11-14-1750}") private String someKey; public String getSomeKey() { return this.someKey; } } @Configuration @EnableApolloConfig(value = "${unresolvable.property}") static class TestEnableApolloConfigUnresolvableConfiguration { } @Configuration @EnableApolloConfig static class AppConfig1 { @Bean public TestApolloConfigBean1 bean() { return new TestApolloConfigBean1(); } } @Configuration @EnableApolloConfig static class AppConfig2 { @Bean public TestApolloConfigBean2 bean() { return new TestApolloConfigBean2(); } } @Configuration @EnableApolloConfig static class AppConfig3 { @Bean public TestApolloConfigChangeListenerBean1 bean() { return new TestApolloConfigChangeListenerBean1(); } } @Configuration @EnableApolloConfig static class AppConfig4 { @Bean public TestApolloConfigChangeListenerBean2 bean() { return new TestApolloConfigChangeListenerBean2(); } } @Configuration @EnableApolloConfig static class AppConfig5 { @Bean public TestApolloConfigChangeListenerBean3 bean() { return new TestApolloConfigChangeListenerBean3(); } } @Configuration @EnableApolloConfig static class AppConfig6 { @Bean public TestApolloChildConfigBean bean() { return new TestApolloChildConfigBean(); } } @Configuration @EnableApolloConfig static class AppConfig7 { @Bean public TestApolloChildConfigChangeListener bean() { return new TestApolloChildConfigChangeListener(); } } @Configuration @EnableApolloConfig static class AppConfig8 { @Bean public TestApolloConfigChangeListenerWithInterestedKeysBean bean() { return new TestApolloConfigChangeListenerWithInterestedKeysBean(); } } @Configuration @EnableApolloConfig(APPLICATION_YAML_NAMESPACE) static class AppConfig9 { @Bean public TestApolloConfigChangeListenerWithYamlFile bean() { return new TestApolloConfigChangeListenerWithYamlFile(); } } @Configuration @EnableApolloConfig static class AppConfig10 { @Bean public TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean bean() { return new TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean(); } } @Configuration @EnableApolloConfig static class AppConfig11 { @Bean public TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1 bean() { return spy(new TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1()); } } static class TestApolloConfigBean1 { @ApolloConfig private Config config; @ApolloConfig(ConfigConsts.NAMESPACE_APPLICATION) private Config anotherConfig; @ApolloConfig(FX_APOLLO_NAMESPACE) private Config yetAnotherConfig; @ApolloConfig(APPLICATION_YAML_NAMESPACE) private Config yamlConfig; public Config getConfig() { return config; } public Config getAnotherConfig() { return anotherConfig; } public Config getYetAnotherConfig() { return yetAnotherConfig; } public Config getYamlConfig() { return yamlConfig; } } static class TestApolloConfigBean2 { @ApolloConfig private String config; } static class TestApolloChildConfigBean extends TestApolloConfigBean1 { @ApolloConfig private Config someConfig; public Config getSomeConfig() { return someConfig; } } static class TestApolloConfigChangeListenerBean1 { private ConfigChangeEvent changeEvent1; private ConfigChangeEvent changeEvent2; private ConfigChangeEvent changeEvent3; @ApolloConfigChangeListener private void onChange1(ConfigChangeEvent changeEvent) { this.changeEvent1 = changeEvent; } @ApolloConfigChangeListener(ConfigConsts.NAMESPACE_APPLICATION) private void onChange2(ConfigChangeEvent changeEvent) { this.changeEvent2 = changeEvent; } @ApolloConfigChangeListener({ConfigConsts.NAMESPACE_APPLICATION, FX_APOLLO_NAMESPACE}) private void onChange3(ConfigChangeEvent changeEvent) { this.changeEvent3 = changeEvent; } public ConfigChangeEvent getChangeEvent1() { return changeEvent1; } public ConfigChangeEvent getChangeEvent2() { return changeEvent2; } public ConfigChangeEvent getChangeEvent3() { return changeEvent3; } } static class TestApolloConfigChangeListenerBean2 { @ApolloConfigChangeListener private void onChange(String event) { } } static class TestApolloConfigChangeListenerBean3 { @ApolloConfigChangeListener private void onChange(ConfigChangeEvent event, String someParam) { } } static class TestApolloChildConfigChangeListener extends TestApolloConfigChangeListenerBean1 { private ConfigChangeEvent someChangeEvent; @ApolloConfigChangeListener private void someOnChange(ConfigChangeEvent changeEvent) { this.someChangeEvent = changeEvent; } public ConfigChangeEvent getSomeChangeEvent() { return someChangeEvent; } } static class TestApolloConfigChangeListenerWithInterestedKeysBean { @ApolloConfigChangeListener(interestedKeys = {"someKey"}) private void someOnChange(ConfigChangeEvent changeEvent) {} @ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, FX_APOLLO_NAMESPACE}, interestedKeys = {"anotherKey"}) private void anotherOnChange(ConfigChangeEvent changeEvent) { } } private static class TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean { @ApolloConfigChangeListener(interestedKeyPrefixes = {"number", "logging.level"}) private void onChange(ConfigChangeEvent changeEvent) { } } private static class TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1 { static final String SPECIAL_NAMESPACE = "special-namespace-2021"; private final BlockingQueue<ConfigChangeEvent> configChangeEventQueue = new ArrayBlockingQueue<>(100); @ApolloConfigChangeListener(value = SPECIAL_NAMESPACE, interestedKeyPrefixes = {"number", "logging.level"}) private void onChange(ConfigChangeEvent changeEvent) { this.configChangeEventQueue.add(changeEvent); } public ConfigChangeEvent getConfigChangeEvent() throws InterruptedException { return this.configChangeEventQueue.poll(5, TimeUnit.SECONDS); } } static class TestApolloConfigChangeListenerWithYamlFile { private SettableFuture<ConfigChangeEvent> configChangeEventFuture = SettableFuture.create(); @ApolloConfig(APPLICATION_YAML_NAMESPACE) private Config yamlConfig; @ApolloConfigChangeListener(APPLICATION_YAML_NAMESPACE) private void onChange(ConfigChangeEvent event) { configChangeEventFuture.set(event); } public SettableFuture<ConfigChangeEvent> getConfigChangeEventFuture() { return configChangeEventFuture; } public Config getYamlConfig() { return yamlConfig; } } }
1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/configuration/AuthConfiguration.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.configuration; import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.portal.component.config.PortalConfig; import com.ctrip.framework.apollo.portal.repository.UserRepository; import com.ctrip.framework.apollo.portal.spi.LogoutHandler; import com.ctrip.framework.apollo.portal.spi.SsoHeartbeatHandler; import com.ctrip.framework.apollo.portal.spi.UserInfoHolder; import com.ctrip.framework.apollo.portal.spi.UserService; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripLogoutHandler; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripSsoHeartbeatHandler; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripUserInfoHolder; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripUserService; import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultLogoutHandler; import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultSsoHeartbeatHandler; import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultUserInfoHolder; import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultUserService; import com.ctrip.framework.apollo.portal.spi.ldap.ApolloLdapAuthenticationProvider; import com.ctrip.framework.apollo.portal.spi.ldap.FilterLdapByGroupUserSearch; import com.ctrip.framework.apollo.portal.spi.ldap.LdapUserService; import com.ctrip.framework.apollo.portal.spi.oidc.ExcludeClientCredentialsClientRegistrationRepository; import com.ctrip.framework.apollo.portal.spi.oidc.OidcAuthenticationSuccessEventListener; import com.ctrip.framework.apollo.portal.spi.oidc.OidcLocalUserService; import com.ctrip.framework.apollo.portal.spi.oidc.OidcLocalUserServiceImpl; import com.ctrip.framework.apollo.portal.spi.oidc.OidcLogoutHandler; import com.ctrip.framework.apollo.portal.spi.oidc.OidcUserInfoHolder; import com.ctrip.framework.apollo.portal.spi.springsecurity.SpringSecurityUserInfoHolder; import com.ctrip.framework.apollo.portal.spi.springsecurity.SpringSecurityUserService; import com.google.common.collect.Maps; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties; import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.annotation.Order; import org.springframework.core.env.Environment; import org.springframework.ldap.core.ContextSource; import org.springframework.ldap.core.LdapOperations; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.ldap.authentication.BindAuthenticator; import org.springframework.security.ldap.authentication.LdapAuthenticationProvider; import org.springframework.security.ldap.search.FilterBasedLdapUserSearch; import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator; import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler; import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository; import org.springframework.security.provisioning.JdbcUserDetailsManager; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; import javax.servlet.Filter; import javax.sql.DataSource; import java.util.Collections; import java.util.EventListener; import java.util.Map; @Configuration public class AuthConfiguration { private static final String[] BY_PASS_URLS = {"/prometheus/**", "/metrics/**", "/openapi/**", "/vendor/**", "/styles/**", "/scripts/**", "/views/**", "/img/**", "/i18n/**", "/prefix-path", "/health"}; /** * spring.profiles.active = ctrip */ @Configuration @Profile("ctrip") static class CtripAuthAutoConfiguration { private final PortalConfig portalConfig; public CtripAuthAutoConfiguration(final PortalConfig portalConfig) { this.portalConfig = portalConfig; } @Bean public ServletListenerRegistrationBean redisAppSettingListner() { ServletListenerRegistrationBean redisAppSettingListener = new ServletListenerRegistrationBean(); redisAppSettingListener .setListener(listener("org.jasig.cas.client.credis.CRedisAppSettingListner")); return redisAppSettingListener; } @Bean public ServletListenerRegistrationBean singleSignOutHttpSessionListener() { ServletListenerRegistrationBean singleSignOutHttpSessionListener = new ServletListenerRegistrationBean(); singleSignOutHttpSessionListener .setListener(listener("org.jasig.cas.client.session.SingleSignOutHttpSessionListener")); return singleSignOutHttpSessionListener; } @Bean public FilterRegistrationBean casFilter() { FilterRegistrationBean singleSignOutFilter = new FilterRegistrationBean(); singleSignOutFilter.setFilter(filter("org.jasig.cas.client.session.SingleSignOutFilter")); singleSignOutFilter.addUrlPatterns("/*"); singleSignOutFilter.setOrder(1); return singleSignOutFilter; } @Bean public FilterRegistrationBean authenticationFilter() { FilterRegistrationBean casFilter = new FilterRegistrationBean(); Map<String, String> filterInitParam = Maps.newHashMap(); filterInitParam.put("redisClusterName", "casClientPrincipal"); filterInitParam.put("serverName", portalConfig.portalServerName()); filterInitParam.put("casServerLoginUrl", portalConfig.casServerLoginUrl()); //we don't want to use session to store login information, since we will be deployed to a cluster, not a single instance filterInitParam.put("useSession", "false"); filterInitParam.put("/openapi.*", "exclude"); casFilter.setInitParameters(filterInitParam); casFilter .setFilter(filter("com.ctrip.framework.apollo.sso.filter.ApolloAuthenticationFilter")); casFilter.addUrlPatterns("/*"); casFilter.setOrder(2); return casFilter; } @Bean public FilterRegistrationBean casValidationFilter() { FilterRegistrationBean casValidationFilter = new FilterRegistrationBean(); Map<String, String> filterInitParam = Maps.newHashMap(); filterInitParam.put("casServerUrlPrefix", portalConfig.casServerUrlPrefix()); filterInitParam.put("serverName", portalConfig.portalServerName()); filterInitParam.put("encoding", "UTF-8"); //we don't want to use session to store login information, since we will be deployed to a cluster, not a single instance filterInitParam.put("useSession", "false"); filterInitParam.put("useRedis", "true"); filterInitParam.put("redisClusterName", "casClientPrincipal"); casValidationFilter .setFilter( filter("org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter")); casValidationFilter.setInitParameters(filterInitParam); casValidationFilter.addUrlPatterns("/*"); casValidationFilter.setOrder(3); return casValidationFilter; } @Bean public FilterRegistrationBean assertionHolder() { FilterRegistrationBean assertionHolderFilter = new FilterRegistrationBean(); Map<String, String> filterInitParam = Maps.newHashMap(); filterInitParam.put("/openapi.*", "exclude"); assertionHolderFilter.setInitParameters(filterInitParam); assertionHolderFilter.setFilter( filter("com.ctrip.framework.apollo.sso.filter.ApolloAssertionThreadLocalFilter")); assertionHolderFilter.addUrlPatterns("/*"); assertionHolderFilter.setOrder(4); return assertionHolderFilter; } @Bean public CtripUserInfoHolder ctripUserInfoHolder() { return new CtripUserInfoHolder(); } @Bean public CtripLogoutHandler logoutHandler() { return new CtripLogoutHandler(); } private Filter filter(String className) { Class clazz = null; try { clazz = Class.forName(className); Object obj = clazz.newInstance(); return (Filter) obj; } catch (Exception e) { throw new RuntimeException("instance filter fail", e); } } private EventListener listener(String className) { Class clazz = null; try { clazz = Class.forName(className); Object obj = clazz.newInstance(); return (EventListener) obj; } catch (Exception e) { throw new RuntimeException("instance listener fail", e); } } @Bean public UserService ctripUserService(PortalConfig portalConfig) { return new CtripUserService(portalConfig); } @Bean public SsoHeartbeatHandler ctripSsoHeartbeatHandler() { return new CtripSsoHeartbeatHandler(); } } /** * spring.profiles.active = auth */ @Configuration @Profile("auth") static class SpringSecurityAuthAutoConfiguration { @Bean @ConditionalOnMissingBean(SsoHeartbeatHandler.class) public SsoHeartbeatHandler defaultSsoHeartbeatHandler() { return new DefaultSsoHeartbeatHandler(); } @Bean @ConditionalOnMissingBean(UserInfoHolder.class) public UserInfoHolder springSecurityUserInfoHolder(UserService userService) { return new SpringSecurityUserInfoHolder(userService); } @Bean @ConditionalOnMissingBean(LogoutHandler.class) public LogoutHandler logoutHandler() { return new DefaultLogoutHandler(); } @Bean public JdbcUserDetailsManager jdbcUserDetailsManager(AuthenticationManagerBuilder auth, DataSource datasource) throws Exception { JdbcUserDetailsManager jdbcUserDetailsManager = auth.jdbcAuthentication() .passwordEncoder(new BCryptPasswordEncoder()).dataSource(datasource) .usersByUsernameQuery("select Username,Password,Enabled from `Users` where Username = ?") .authoritiesByUsernameQuery( "select Username,Authority from `Authorities` where Username = ?") .getUserDetailsService(); jdbcUserDetailsManager.setUserExistsSql("select Username from `Users` where Username = ?"); jdbcUserDetailsManager .setCreateUserSql("insert into `Users` (Username, Password, Enabled) values (?,?,?)"); jdbcUserDetailsManager .setUpdateUserSql("update `Users` set Password = ?, Enabled = ? where id = (select u.id from (select id from `Users` where Username = ?) as u)"); jdbcUserDetailsManager.setDeleteUserSql("delete from `Users` where id = (select u.id from (select id from `Users` where Username = ?) as u)"); jdbcUserDetailsManager .setCreateAuthoritySql("insert into `Authorities` (Username, Authority) values (?,?)"); jdbcUserDetailsManager .setDeleteUserAuthoritiesSql("delete from `Authorities` where id in (select a.id from (select id from `Authorities` where Username = ?) as a)"); jdbcUserDetailsManager .setChangePasswordSql("update `Users` set Password = ? where id = (select u.id from (select id from `Users` where Username = ?) as u)"); return jdbcUserDetailsManager; } @Bean @ConditionalOnMissingBean(UserService.class) public UserService springSecurityUserService() { return new SpringSecurityUserService(); } } @Order(99) @Profile("auth") @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) static class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter { public static final String USER_ROLE = "user"; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.headers().frameOptions().sameOrigin(); http.authorizeRequests() .antMatchers(BY_PASS_URLS).permitAll() .antMatchers("/**").hasAnyRole(USER_ROLE); http.formLogin().loginPage("/signin").defaultSuccessUrl("/", true).permitAll().failureUrl("/signin?#/error").and() .httpBasic(); http.logout().logoutUrl("/user/logout").invalidateHttpSession(true).clearAuthentication(true) .logoutSuccessUrl("/signin?#/logout"); http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/signin")); } } /** * spring.profiles.active = ldap */ @Configuration @Profile("ldap") @EnableConfigurationProperties({LdapProperties.class,LdapExtendProperties.class}) static class SpringSecurityLDAPAuthAutoConfiguration { private final LdapProperties properties; private final Environment environment; public SpringSecurityLDAPAuthAutoConfiguration(final LdapProperties properties, final Environment environment) { this.properties = properties; this.environment = environment; } @Bean @ConditionalOnMissingBean(SsoHeartbeatHandler.class) public SsoHeartbeatHandler defaultSsoHeartbeatHandler() { return new DefaultSsoHeartbeatHandler(); } @Bean @ConditionalOnMissingBean(UserInfoHolder.class) public UserInfoHolder springSecurityUserInfoHolder(UserService userService) { return new SpringSecurityUserInfoHolder(userService); } @Bean @ConditionalOnMissingBean(LogoutHandler.class) public LogoutHandler logoutHandler() { return new DefaultLogoutHandler(); } @Bean @ConditionalOnMissingBean(UserService.class) public UserService springSecurityUserService() { return new LdapUserService(); } @Bean @ConditionalOnMissingBean public ContextSource ldapContextSource() { LdapContextSource source = new LdapContextSource(); source.setUserDn(this.properties.getUsername()); source.setPassword(this.properties.getPassword()); source.setAnonymousReadOnly(this.properties.getAnonymousReadOnly()); source.setBase(this.properties.getBase()); source.setUrls(this.properties.determineUrls(this.environment)); source.setBaseEnvironmentProperties( Collections.unmodifiableMap(this.properties.getBaseEnvironment())); return source; } @Bean @ConditionalOnMissingBean(LdapOperations.class) public LdapTemplate ldapTemplate(ContextSource contextSource) { LdapTemplate ldapTemplate = new LdapTemplate(contextSource); ldapTemplate.setIgnorePartialResultException(true); return ldapTemplate; } } @Order(99) @Profile("ldap") @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) static class SpringSecurityLDAPConfigurer extends WebSecurityConfigurerAdapter { private final LdapProperties ldapProperties; private final LdapContextSource ldapContextSource; private final LdapExtendProperties ldapExtendProperties; public SpringSecurityLDAPConfigurer(final LdapProperties ldapProperties, final LdapContextSource ldapContextSource, final LdapExtendProperties ldapExtendProperties) { this.ldapProperties = ldapProperties; this.ldapContextSource = ldapContextSource; this.ldapExtendProperties = ldapExtendProperties; } @Bean public FilterBasedLdapUserSearch userSearch() { if (ldapExtendProperties.getGroup() == null || StringUtils .isBlank(ldapExtendProperties.getGroup().getGroupSearch())) { FilterBasedLdapUserSearch filterBasedLdapUserSearch = new FilterBasedLdapUserSearch("", ldapProperties.getSearchFilter(), ldapContextSource); filterBasedLdapUserSearch.setSearchSubtree(true); return filterBasedLdapUserSearch; } FilterLdapByGroupUserSearch filterLdapByGroupUserSearch = new FilterLdapByGroupUserSearch( ldapProperties.getBase(), ldapProperties.getSearchFilter(), ldapExtendProperties.getGroup().getGroupBase(), ldapContextSource, ldapExtendProperties.getGroup().getGroupSearch(), ldapExtendProperties.getMapping().getRdnKey(), ldapExtendProperties.getGroup().getGroupMembership(),ldapExtendProperties.getMapping().getLoginId()); filterLdapByGroupUserSearch.setSearchSubtree(true); return filterLdapByGroupUserSearch; } @Bean public LdapAuthenticationProvider ldapAuthProvider() { BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource); bindAuthenticator.setUserSearch(userSearch()); DefaultLdapAuthoritiesPopulator defaultAuthAutoConfiguration = new DefaultLdapAuthoritiesPopulator( ldapContextSource, null); defaultAuthAutoConfiguration.setIgnorePartialResultException(true); defaultAuthAutoConfiguration.setSearchSubtree(true); // Rewrite the logic of LdapAuthenticationProvider with ApolloLdapAuthenticationProvider, // use userId in LDAP system instead of userId input by user. return new ApolloLdapAuthenticationProvider( bindAuthenticator, defaultAuthAutoConfiguration, ldapExtendProperties); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.headers().frameOptions().sameOrigin(); http.authorizeRequests() .antMatchers(BY_PASS_URLS).permitAll() .antMatchers("/**").authenticated(); http.formLogin().loginPage("/signin").defaultSuccessUrl("/", true).permitAll().failureUrl("/signin?#/error").and() .httpBasic(); http.logout().logoutUrl("/user/logout").invalidateHttpSession(true).clearAuthentication(true) .logoutSuccessUrl("/signin?#/logout"); http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/signin")); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(ldapAuthProvider()); } } @Profile("oidc") @EnableConfigurationProperties({OAuth2ClientProperties.class, OAuth2ResourceServerProperties.class}) @Configuration static class OidcAuthAutoConfiguration { @Bean @ConditionalOnMissingBean(SsoHeartbeatHandler.class) public SsoHeartbeatHandler defaultSsoHeartbeatHandler() { return new DefaultSsoHeartbeatHandler(); } @Bean @ConditionalOnMissingBean(UserInfoHolder.class) public UserInfoHolder oidcUserInfoHolder(UserService userService) { return new OidcUserInfoHolder(userService); } @Bean @ConditionalOnMissingBean(LogoutHandler.class) public LogoutHandler oidcLogoutHandler() { return new OidcLogoutHandler(); } @Bean @ConditionalOnMissingBean(JdbcUserDetailsManager.class) public JdbcUserDetailsManager jdbcUserDetailsManager(AuthenticationManagerBuilder auth, DataSource datasource) throws Exception { return new SpringSecurityAuthAutoConfiguration().jdbcUserDetailsManager(auth, datasource); } @Bean @ConditionalOnMissingBean(UserService.class) public OidcLocalUserService oidcLocalUserService(JdbcUserDetailsManager userDetailsManager, UserRepository userRepository) { return new OidcLocalUserServiceImpl(userDetailsManager, userRepository); } @Bean public OidcAuthenticationSuccessEventListener oidcAuthenticationSuccessEventListener(OidcLocalUserService oidcLocalUserService) { return new OidcAuthenticationSuccessEventListener(oidcLocalUserService); } } @Profile("oidc") @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @Configuration static class OidcWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { private final InMemoryClientRegistrationRepository clientRegistrationRepository; private final OAuth2ResourceServerProperties oauth2ResourceServerProperties; public OidcWebSecurityConfigurerAdapter( InMemoryClientRegistrationRepository clientRegistrationRepository, OAuth2ResourceServerProperties oauth2ResourceServerProperties) { this.clientRegistrationRepository = clientRegistrationRepository; this.oauth2ResourceServerProperties = oauth2ResourceServerProperties; } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests(requests -> requests.antMatchers(BY_PASS_URLS).permitAll()); http.authorizeRequests(requests -> requests.anyRequest().authenticated()); http.oauth2Login(configure -> configure.clientRegistrationRepository( new ExcludeClientCredentialsClientRegistrationRepository( this.clientRegistrationRepository))); http.oauth2Client(); http.logout(configure -> { OidcClientInitiatedLogoutSuccessHandler logoutSuccessHandler = new OidcClientInitiatedLogoutSuccessHandler( this.clientRegistrationRepository); logoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}"); configure.logoutSuccessHandler(logoutSuccessHandler); }); // make jwt optional String jwtIssuerUri = this.oauth2ResourceServerProperties.getJwt().getIssuerUri(); if (!StringUtils.isBlank(jwtIssuerUri)) { http.oauth2ResourceServer().jwt(); } } } /** * default profile */ @Configuration @ConditionalOnMissingProfile({"ctrip", "auth", "ldap", "oidc"}) static class DefaultAuthAutoConfiguration { @Bean @ConditionalOnMissingBean(SsoHeartbeatHandler.class) public SsoHeartbeatHandler defaultSsoHeartbeatHandler() { return new DefaultSsoHeartbeatHandler(); } @Bean @ConditionalOnMissingBean(UserInfoHolder.class) public DefaultUserInfoHolder defaultUserInfoHolder() { return new DefaultUserInfoHolder(); } @Bean @ConditionalOnMissingBean(LogoutHandler.class) public DefaultLogoutHandler logoutHandler() { return new DefaultLogoutHandler(); } @Bean @ConditionalOnMissingBean(UserService.class) public UserService defaultUserService() { return new DefaultUserService(); } } @ConditionalOnMissingProfile({"auth", "ldap", "oidc"}) @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) static class DefaultWebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.headers().frameOptions().sameOrigin(); } } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.configuration; import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.portal.component.config.PortalConfig; import com.ctrip.framework.apollo.portal.repository.UserRepository; import com.ctrip.framework.apollo.portal.spi.LogoutHandler; import com.ctrip.framework.apollo.portal.spi.SsoHeartbeatHandler; import com.ctrip.framework.apollo.portal.spi.UserInfoHolder; import com.ctrip.framework.apollo.portal.spi.UserService; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripLogoutHandler; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripSsoHeartbeatHandler; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripUserInfoHolder; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripUserService; import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultLogoutHandler; import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultSsoHeartbeatHandler; import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultUserInfoHolder; import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultUserService; import com.ctrip.framework.apollo.portal.spi.ldap.ApolloLdapAuthenticationProvider; import com.ctrip.framework.apollo.portal.spi.ldap.FilterLdapByGroupUserSearch; import com.ctrip.framework.apollo.portal.spi.ldap.LdapUserService; import com.ctrip.framework.apollo.portal.spi.oidc.ExcludeClientCredentialsClientRegistrationRepository; import com.ctrip.framework.apollo.portal.spi.oidc.OidcAuthenticationSuccessEventListener; import com.ctrip.framework.apollo.portal.spi.oidc.OidcLocalUserService; import com.ctrip.framework.apollo.portal.spi.oidc.OidcLocalUserServiceImpl; import com.ctrip.framework.apollo.portal.spi.oidc.OidcLogoutHandler; import com.ctrip.framework.apollo.portal.spi.oidc.OidcUserInfoHolder; import com.ctrip.framework.apollo.portal.spi.springsecurity.ApolloPasswordEncoderFactory; import com.ctrip.framework.apollo.portal.spi.springsecurity.SpringSecurityUserInfoHolder; import com.ctrip.framework.apollo.portal.spi.springsecurity.SpringSecurityUserService; import com.google.common.collect.Maps; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties; import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.annotation.Order; import org.springframework.core.env.Environment; import org.springframework.ldap.core.ContextSource; import org.springframework.ldap.core.LdapOperations; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.ldap.authentication.BindAuthenticator; import org.springframework.security.ldap.authentication.LdapAuthenticationProvider; import org.springframework.security.ldap.search.FilterBasedLdapUserSearch; import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator; import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler; import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository; import org.springframework.security.provisioning.JdbcUserDetailsManager; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; import javax.servlet.Filter; import javax.sql.DataSource; import java.util.Collections; import java.util.EventListener; import java.util.Map; @Configuration public class AuthConfiguration { private static final String[] BY_PASS_URLS = {"/prometheus/**", "/metrics/**", "/openapi/**", "/vendor/**", "/styles/**", "/scripts/**", "/views/**", "/img/**", "/i18n/**", "/prefix-path", "/health"}; /** * spring.profiles.active = ctrip */ @Configuration @Profile("ctrip") static class CtripAuthAutoConfiguration { private final PortalConfig portalConfig; public CtripAuthAutoConfiguration(final PortalConfig portalConfig) { this.portalConfig = portalConfig; } @Bean public ServletListenerRegistrationBean redisAppSettingListner() { ServletListenerRegistrationBean redisAppSettingListener = new ServletListenerRegistrationBean(); redisAppSettingListener .setListener(listener("org.jasig.cas.client.credis.CRedisAppSettingListner")); return redisAppSettingListener; } @Bean public ServletListenerRegistrationBean singleSignOutHttpSessionListener() { ServletListenerRegistrationBean singleSignOutHttpSessionListener = new ServletListenerRegistrationBean(); singleSignOutHttpSessionListener .setListener(listener("org.jasig.cas.client.session.SingleSignOutHttpSessionListener")); return singleSignOutHttpSessionListener; } @Bean public FilterRegistrationBean casFilter() { FilterRegistrationBean singleSignOutFilter = new FilterRegistrationBean(); singleSignOutFilter.setFilter(filter("org.jasig.cas.client.session.SingleSignOutFilter")); singleSignOutFilter.addUrlPatterns("/*"); singleSignOutFilter.setOrder(1); return singleSignOutFilter; } @Bean public FilterRegistrationBean authenticationFilter() { FilterRegistrationBean casFilter = new FilterRegistrationBean(); Map<String, String> filterInitParam = Maps.newHashMap(); filterInitParam.put("redisClusterName", "casClientPrincipal"); filterInitParam.put("serverName", portalConfig.portalServerName()); filterInitParam.put("casServerLoginUrl", portalConfig.casServerLoginUrl()); //we don't want to use session to store login information, since we will be deployed to a cluster, not a single instance filterInitParam.put("useSession", "false"); filterInitParam.put("/openapi.*", "exclude"); casFilter.setInitParameters(filterInitParam); casFilter .setFilter(filter("com.ctrip.framework.apollo.sso.filter.ApolloAuthenticationFilter")); casFilter.addUrlPatterns("/*"); casFilter.setOrder(2); return casFilter; } @Bean public FilterRegistrationBean casValidationFilter() { FilterRegistrationBean casValidationFilter = new FilterRegistrationBean(); Map<String, String> filterInitParam = Maps.newHashMap(); filterInitParam.put("casServerUrlPrefix", portalConfig.casServerUrlPrefix()); filterInitParam.put("serverName", portalConfig.portalServerName()); filterInitParam.put("encoding", "UTF-8"); //we don't want to use session to store login information, since we will be deployed to a cluster, not a single instance filterInitParam.put("useSession", "false"); filterInitParam.put("useRedis", "true"); filterInitParam.put("redisClusterName", "casClientPrincipal"); casValidationFilter .setFilter( filter("org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter")); casValidationFilter.setInitParameters(filterInitParam); casValidationFilter.addUrlPatterns("/*"); casValidationFilter.setOrder(3); return casValidationFilter; } @Bean public FilterRegistrationBean assertionHolder() { FilterRegistrationBean assertionHolderFilter = new FilterRegistrationBean(); Map<String, String> filterInitParam = Maps.newHashMap(); filterInitParam.put("/openapi.*", "exclude"); assertionHolderFilter.setInitParameters(filterInitParam); assertionHolderFilter.setFilter( filter("com.ctrip.framework.apollo.sso.filter.ApolloAssertionThreadLocalFilter")); assertionHolderFilter.addUrlPatterns("/*"); assertionHolderFilter.setOrder(4); return assertionHolderFilter; } @Bean public CtripUserInfoHolder ctripUserInfoHolder() { return new CtripUserInfoHolder(); } @Bean public CtripLogoutHandler logoutHandler() { return new CtripLogoutHandler(); } private Filter filter(String className) { Class clazz = null; try { clazz = Class.forName(className); Object obj = clazz.newInstance(); return (Filter) obj; } catch (Exception e) { throw new RuntimeException("instance filter fail", e); } } private EventListener listener(String className) { Class clazz = null; try { clazz = Class.forName(className); Object obj = clazz.newInstance(); return (EventListener) obj; } catch (Exception e) { throw new RuntimeException("instance listener fail", e); } } @Bean public UserService ctripUserService(PortalConfig portalConfig) { return new CtripUserService(portalConfig); } @Bean public SsoHeartbeatHandler ctripSsoHeartbeatHandler() { return new CtripSsoHeartbeatHandler(); } } /** * spring.profiles.active = auth */ @Configuration @Profile("auth") static class SpringSecurityAuthAutoConfiguration { @Bean @ConditionalOnMissingBean(SsoHeartbeatHandler.class) public SsoHeartbeatHandler defaultSsoHeartbeatHandler() { return new DefaultSsoHeartbeatHandler(); } @Bean @ConditionalOnMissingBean(PasswordEncoder.class) public static PasswordEncoder passwordEncoder() { return ApolloPasswordEncoderFactory.createDelegatingPasswordEncoder(); } @Bean @ConditionalOnMissingBean(UserInfoHolder.class) public UserInfoHolder springSecurityUserInfoHolder(UserService userService) { return new SpringSecurityUserInfoHolder(userService); } @Bean @ConditionalOnMissingBean(LogoutHandler.class) public LogoutHandler logoutHandler() { return new DefaultLogoutHandler(); } @Bean public static JdbcUserDetailsManager jdbcUserDetailsManager(PasswordEncoder passwordEncoder, AuthenticationManagerBuilder auth, DataSource datasource) throws Exception { JdbcUserDetailsManager jdbcUserDetailsManager = auth.jdbcAuthentication() .passwordEncoder(passwordEncoder).dataSource(datasource) .usersByUsernameQuery("select Username,Password,Enabled from `Users` where Username = ?") .authoritiesByUsernameQuery( "select Username,Authority from `Authorities` where Username = ?") .getUserDetailsService(); jdbcUserDetailsManager.setUserExistsSql("select Username from `Users` where Username = ?"); jdbcUserDetailsManager .setCreateUserSql("insert into `Users` (Username, Password, Enabled) values (?,?,?)"); jdbcUserDetailsManager .setUpdateUserSql("update `Users` set Password = ?, Enabled = ? where id = (select u.id from (select id from `Users` where Username = ?) as u)"); jdbcUserDetailsManager.setDeleteUserSql("delete from `Users` where id = (select u.id from (select id from `Users` where Username = ?) as u)"); jdbcUserDetailsManager .setCreateAuthoritySql("insert into `Authorities` (Username, Authority) values (?,?)"); jdbcUserDetailsManager .setDeleteUserAuthoritiesSql("delete from `Authorities` where id in (select a.id from (select id from `Authorities` where Username = ?) as a)"); jdbcUserDetailsManager .setChangePasswordSql("update `Users` set Password = ? where id = (select u.id from (select id from `Users` where Username = ?) as u)"); return jdbcUserDetailsManager; } @Bean @ConditionalOnMissingBean(UserService.class) public UserService springSecurityUserService(PasswordEncoder passwordEncoder, JdbcUserDetailsManager userDetailsManager, UserRepository userRepository) { return new SpringSecurityUserService(passwordEncoder, userDetailsManager, userRepository); } } @Order(99) @Profile("auth") @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) static class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter { public static final String USER_ROLE = "user"; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.headers().frameOptions().sameOrigin(); http.authorizeRequests() .antMatchers(BY_PASS_URLS).permitAll() .antMatchers("/**").hasAnyRole(USER_ROLE); http.formLogin().loginPage("/signin").defaultSuccessUrl("/", true).permitAll().failureUrl("/signin?#/error").and() .httpBasic(); http.logout().logoutUrl("/user/logout").invalidateHttpSession(true).clearAuthentication(true) .logoutSuccessUrl("/signin?#/logout"); http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/signin")); } } /** * spring.profiles.active = ldap */ @Configuration @Profile("ldap") @EnableConfigurationProperties({LdapProperties.class,LdapExtendProperties.class}) static class SpringSecurityLDAPAuthAutoConfiguration { private final LdapProperties properties; private final Environment environment; public SpringSecurityLDAPAuthAutoConfiguration(final LdapProperties properties, final Environment environment) { this.properties = properties; this.environment = environment; } @Bean @ConditionalOnMissingBean(SsoHeartbeatHandler.class) public SsoHeartbeatHandler defaultSsoHeartbeatHandler() { return new DefaultSsoHeartbeatHandler(); } @Bean @ConditionalOnMissingBean(UserInfoHolder.class) public UserInfoHolder springSecurityUserInfoHolder(UserService userService) { return new SpringSecurityUserInfoHolder(userService); } @Bean @ConditionalOnMissingBean(LogoutHandler.class) public LogoutHandler logoutHandler() { return new DefaultLogoutHandler(); } @Bean @ConditionalOnMissingBean(UserService.class) public UserService springSecurityUserService() { return new LdapUserService(); } @Bean @ConditionalOnMissingBean public ContextSource ldapContextSource() { LdapContextSource source = new LdapContextSource(); source.setUserDn(this.properties.getUsername()); source.setPassword(this.properties.getPassword()); source.setAnonymousReadOnly(this.properties.getAnonymousReadOnly()); source.setBase(this.properties.getBase()); source.setUrls(this.properties.determineUrls(this.environment)); source.setBaseEnvironmentProperties( Collections.unmodifiableMap(this.properties.getBaseEnvironment())); return source; } @Bean @ConditionalOnMissingBean(LdapOperations.class) public LdapTemplate ldapTemplate(ContextSource contextSource) { LdapTemplate ldapTemplate = new LdapTemplate(contextSource); ldapTemplate.setIgnorePartialResultException(true); return ldapTemplate; } } @Order(99) @Profile("ldap") @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) static class SpringSecurityLDAPConfigurer extends WebSecurityConfigurerAdapter { private final LdapProperties ldapProperties; private final LdapContextSource ldapContextSource; private final LdapExtendProperties ldapExtendProperties; public SpringSecurityLDAPConfigurer(final LdapProperties ldapProperties, final LdapContextSource ldapContextSource, final LdapExtendProperties ldapExtendProperties) { this.ldapProperties = ldapProperties; this.ldapContextSource = ldapContextSource; this.ldapExtendProperties = ldapExtendProperties; } @Bean public FilterBasedLdapUserSearch userSearch() { if (ldapExtendProperties.getGroup() == null || StringUtils .isBlank(ldapExtendProperties.getGroup().getGroupSearch())) { FilterBasedLdapUserSearch filterBasedLdapUserSearch = new FilterBasedLdapUserSearch("", ldapProperties.getSearchFilter(), ldapContextSource); filterBasedLdapUserSearch.setSearchSubtree(true); return filterBasedLdapUserSearch; } FilterLdapByGroupUserSearch filterLdapByGroupUserSearch = new FilterLdapByGroupUserSearch( ldapProperties.getBase(), ldapProperties.getSearchFilter(), ldapExtendProperties.getGroup().getGroupBase(), ldapContextSource, ldapExtendProperties.getGroup().getGroupSearch(), ldapExtendProperties.getMapping().getRdnKey(), ldapExtendProperties.getGroup().getGroupMembership(),ldapExtendProperties.getMapping().getLoginId()); filterLdapByGroupUserSearch.setSearchSubtree(true); return filterLdapByGroupUserSearch; } @Bean public LdapAuthenticationProvider ldapAuthProvider() { BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource); bindAuthenticator.setUserSearch(userSearch()); DefaultLdapAuthoritiesPopulator defaultAuthAutoConfiguration = new DefaultLdapAuthoritiesPopulator( ldapContextSource, null); defaultAuthAutoConfiguration.setIgnorePartialResultException(true); defaultAuthAutoConfiguration.setSearchSubtree(true); // Rewrite the logic of LdapAuthenticationProvider with ApolloLdapAuthenticationProvider, // use userId in LDAP system instead of userId input by user. return new ApolloLdapAuthenticationProvider( bindAuthenticator, defaultAuthAutoConfiguration, ldapExtendProperties); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.headers().frameOptions().sameOrigin(); http.authorizeRequests() .antMatchers(BY_PASS_URLS).permitAll() .antMatchers("/**").authenticated(); http.formLogin().loginPage("/signin").defaultSuccessUrl("/", true).permitAll().failureUrl("/signin?#/error").and() .httpBasic(); http.logout().logoutUrl("/user/logout").invalidateHttpSession(true).clearAuthentication(true) .logoutSuccessUrl("/signin?#/logout"); http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/signin")); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(ldapAuthProvider()); } } @Profile("oidc") @EnableConfigurationProperties({OAuth2ClientProperties.class, OAuth2ResourceServerProperties.class}) @Configuration static class OidcAuthAutoConfiguration { @Bean @ConditionalOnMissingBean(SsoHeartbeatHandler.class) public SsoHeartbeatHandler defaultSsoHeartbeatHandler() { return new DefaultSsoHeartbeatHandler(); } @Bean @ConditionalOnMissingBean(UserInfoHolder.class) public UserInfoHolder oidcUserInfoHolder(UserService userService) { return new OidcUserInfoHolder(userService); } @Bean @ConditionalOnMissingBean(LogoutHandler.class) public LogoutHandler oidcLogoutHandler() { return new OidcLogoutHandler(); } @Bean @ConditionalOnMissingBean(PasswordEncoder.class) public PasswordEncoder passwordEncoder() { return SpringSecurityAuthAutoConfiguration.passwordEncoder(); } @Bean @ConditionalOnMissingBean(JdbcUserDetailsManager.class) public JdbcUserDetailsManager jdbcUserDetailsManager(PasswordEncoder passwordEncoder, AuthenticationManagerBuilder auth, DataSource datasource) throws Exception { return SpringSecurityAuthAutoConfiguration .jdbcUserDetailsManager(passwordEncoder, auth, datasource); } @Bean @ConditionalOnMissingBean(UserService.class) public OidcLocalUserService oidcLocalUserService(JdbcUserDetailsManager userDetailsManager, UserRepository userRepository) { return new OidcLocalUserServiceImpl(userDetailsManager, userRepository); } @Bean public OidcAuthenticationSuccessEventListener oidcAuthenticationSuccessEventListener(OidcLocalUserService oidcLocalUserService) { return new OidcAuthenticationSuccessEventListener(oidcLocalUserService); } } @Profile("oidc") @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @Configuration static class OidcWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { private final InMemoryClientRegistrationRepository clientRegistrationRepository; private final OAuth2ResourceServerProperties oauth2ResourceServerProperties; public OidcWebSecurityConfigurerAdapter( InMemoryClientRegistrationRepository clientRegistrationRepository, OAuth2ResourceServerProperties oauth2ResourceServerProperties) { this.clientRegistrationRepository = clientRegistrationRepository; this.oauth2ResourceServerProperties = oauth2ResourceServerProperties; } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests(requests -> requests.antMatchers(BY_PASS_URLS).permitAll()); http.authorizeRequests(requests -> requests.anyRequest().authenticated()); http.oauth2Login(configure -> configure.clientRegistrationRepository( new ExcludeClientCredentialsClientRegistrationRepository( this.clientRegistrationRepository))); http.oauth2Client(); http.logout(configure -> { OidcClientInitiatedLogoutSuccessHandler logoutSuccessHandler = new OidcClientInitiatedLogoutSuccessHandler( this.clientRegistrationRepository); logoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}"); configure.logoutSuccessHandler(logoutSuccessHandler); }); // make jwt optional String jwtIssuerUri = this.oauth2ResourceServerProperties.getJwt().getIssuerUri(); if (!StringUtils.isBlank(jwtIssuerUri)) { http.oauth2ResourceServer().jwt(); } } } /** * default profile */ @Configuration @ConditionalOnMissingProfile({"ctrip", "auth", "ldap", "oidc"}) static class DefaultAuthAutoConfiguration { @Bean @ConditionalOnMissingBean(SsoHeartbeatHandler.class) public SsoHeartbeatHandler defaultSsoHeartbeatHandler() { return new DefaultSsoHeartbeatHandler(); } @Bean @ConditionalOnMissingBean(UserInfoHolder.class) public DefaultUserInfoHolder defaultUserInfoHolder() { return new DefaultUserInfoHolder(); } @Bean @ConditionalOnMissingBean(LogoutHandler.class) public DefaultLogoutHandler logoutHandler() { return new DefaultLogoutHandler(); } @Bean @ConditionalOnMissingBean(UserService.class) public UserService defaultUserService() { return new DefaultUserService(); } } @ConditionalOnMissingProfile({"auth", "ldap", "oidc"}) @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) static class DefaultWebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.headers().frameOptions().sameOrigin(); } } }
1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/oidc/OidcLocalUserServiceImpl.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.oidc; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.portal.entity.bo.UserInfo; import com.ctrip.framework.apollo.portal.entity.po.UserPO; import com.ctrip.framework.apollo.portal.repository.UserRepository; import java.util.ArrayList; import java.util.Base64; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.JdbcUserDetailsManager; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; /** * @author vdisk <vdisk@foxmail.com> */ public class OidcLocalUserServiceImpl implements OidcLocalUserService { private final Collection<? extends GrantedAuthority> authorities = Collections .singletonList(new SimpleGrantedAuthority("ROLE_USER")); private final JdbcUserDetailsManager userDetailsManager; private final UserRepository userRepository; public OidcLocalUserServiceImpl( JdbcUserDetailsManager userDetailsManager, UserRepository userRepository) { this.userDetailsManager = userDetailsManager; this.userRepository = userRepository; } @Transactional(rollbackFor = Exception.class) @Override public void createLocalUser(UserInfo newUserInfo) { UserDetails user = new User(newUserInfo.getUserId(), "{nonsensical}" + this.nonsensicalPassword(), authorities); userDetailsManager.createUser(user); this.updateUserInfoInternal(newUserInfo); } /** * generate a random password with no meaning */ private String nonsensicalPassword() { byte[] bytes = new byte[32]; ThreadLocalRandom.current().nextBytes(bytes); return Base64.getEncoder().encodeToString(bytes); } private void updateUserInfoInternal(UserInfo newUserInfo) { UserPO managedUser = userRepository.findByUsername(newUserInfo.getUserId()); if (!StringUtils.isBlank(newUserInfo.getEmail())) { managedUser.setEmail(newUserInfo.getEmail()); } if (!StringUtils.isBlank(newUserInfo.getName())) { managedUser.setUserDisplayName(newUserInfo.getName()); } userRepository.save(managedUser); } @Transactional(rollbackFor = Exception.class) @Override public void updateUserInfo(UserInfo newUserInfo) { this.updateUserInfoInternal(newUserInfo); } @Override public List<UserInfo> searchUsers(String keyword, int offset, int limit) { List<UserPO> users = this.findUsers(keyword); if (CollectionUtils.isEmpty(users)) { return Collections.emptyList(); } return users.stream().map(UserPO::toUserInfo) .collect(Collectors.toList()); } private List<UserPO> findUsers(String keyword) { if (StringUtils.isEmpty(keyword)) { return userRepository.findFirst20ByEnabled(1); } List<UserPO> users = new ArrayList<>(); List<UserPO> byUsername = userRepository .findByUsernameLikeAndEnabled("%" + keyword + "%", 1); List<UserPO> byUserDisplayName = userRepository .findByUserDisplayNameLikeAndEnabled("%" + keyword + "%", 1); if (!CollectionUtils.isEmpty(byUsername)) { users.addAll(byUsername); } if (!CollectionUtils.isEmpty(byUserDisplayName)) { users.addAll(byUserDisplayName); } return users; } @Override public UserInfo findByUserId(String userId) { UserPO userPO = userRepository.findByUsername(userId); return userPO == null ? null : userPO.toUserInfo(); } @Override public List<UserInfo> findByUserIds(List<String> userIds) { List<UserPO> users = userRepository.findByUsernameIn(userIds); if (CollectionUtils.isEmpty(users)) { return Collections.emptyList(); } return users.stream().map(UserPO::toUserInfo) .collect(Collectors.toList()); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.oidc; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.portal.entity.bo.UserInfo; import com.ctrip.framework.apollo.portal.entity.po.UserPO; import com.ctrip.framework.apollo.portal.repository.UserRepository; import java.util.ArrayList; import java.util.Base64; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.DelegatingPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.JdbcUserDetailsManager; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; /** * @author vdisk <vdisk@foxmail.com> */ public class OidcLocalUserServiceImpl implements OidcLocalUserService { private final Collection<? extends GrantedAuthority> authorities = Collections .singletonList(new SimpleGrantedAuthority("ROLE_USER")); private final PasswordEncoder placeholderDelegatingPasswordEncoder = new DelegatingPasswordEncoder( PlaceholderPasswordEncoder.ENCODING_ID, Collections .singletonMap(PlaceholderPasswordEncoder.ENCODING_ID, new PlaceholderPasswordEncoder())); private final JdbcUserDetailsManager userDetailsManager; private final UserRepository userRepository; public OidcLocalUserServiceImpl( JdbcUserDetailsManager userDetailsManager, UserRepository userRepository) { this.userDetailsManager = userDetailsManager; this.userRepository = userRepository; } @Transactional(rollbackFor = Exception.class) @Override public void createLocalUser(UserInfo newUserInfo) { UserDetails user = new User(newUserInfo.getUserId(), this.placeholderDelegatingPasswordEncoder.encode(""), authorities); userDetailsManager.createUser(user); this.updateUserInfoInternal(newUserInfo); } private void updateUserInfoInternal(UserInfo newUserInfo) { UserPO managedUser = userRepository.findByUsername(newUserInfo.getUserId()); if (!StringUtils.isBlank(newUserInfo.getEmail())) { managedUser.setEmail(newUserInfo.getEmail()); } if (!StringUtils.isBlank(newUserInfo.getName())) { managedUser.setUserDisplayName(newUserInfo.getName()); } userRepository.save(managedUser); } @Transactional(rollbackFor = Exception.class) @Override public void updateUserInfo(UserInfo newUserInfo) { this.updateUserInfoInternal(newUserInfo); } @Override public List<UserInfo> searchUsers(String keyword, int offset, int limit) { List<UserPO> users = this.findUsers(keyword); if (CollectionUtils.isEmpty(users)) { return Collections.emptyList(); } return users.stream().map(UserPO::toUserInfo) .collect(Collectors.toList()); } private List<UserPO> findUsers(String keyword) { if (StringUtils.isEmpty(keyword)) { return userRepository.findFirst20ByEnabled(1); } List<UserPO> users = new ArrayList<>(); List<UserPO> byUsername = userRepository .findByUsernameLikeAndEnabled("%" + keyword + "%", 1); List<UserPO> byUserDisplayName = userRepository .findByUserDisplayNameLikeAndEnabled("%" + keyword + "%", 1); if (!CollectionUtils.isEmpty(byUsername)) { users.addAll(byUsername); } if (!CollectionUtils.isEmpty(byUserDisplayName)) { users.addAll(byUserDisplayName); } return users; } @Override public UserInfo findByUserId(String userId) { UserPO userPO = userRepository.findByUsername(userId); return userPO == null ? null : userPO.toUserInfo(); } @Override public List<UserInfo> findByUserIds(List<String> userIds) { List<UserPO> users = userRepository.findByUsernameIn(userIds); if (CollectionUtils.isEmpty(users)) { return Collections.emptyList(); } return users.stream().map(UserPO::toUserInfo) .collect(Collectors.toList()); } }
1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/springsecurity/SpringSecurityUserService.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.springsecurity; import com.google.common.collect.Lists; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.portal.entity.bo.UserInfo; import com.ctrip.framework.apollo.portal.entity.po.UserPO; import com.ctrip.framework.apollo.portal.repository.UserRepository; import com.ctrip.framework.apollo.portal.spi.UserService; import java.util.Collections; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.JdbcUserDetailsManager; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import javax.annotation.PostConstruct; /** * @author lepdou 2017-03-10 */ public class SpringSecurityUserService implements UserService { private PasswordEncoder encoder = new BCryptPasswordEncoder(); private List<GrantedAuthority> authorities; @Autowired private JdbcUserDetailsManager userDetailsManager; @Autowired private UserRepository userRepository; @PostConstruct public void init() { authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_user")); } @Transactional public void createOrUpdate(UserPO user) { String username = user.getUsername(); User userDetails = new User(username, encoder.encode(user.getPassword()), authorities); if (userDetailsManager.userExists(username)) { userDetailsManager.updateUser(userDetails); } else { userDetailsManager.createUser(userDetails); } UserPO managedUser = userRepository.findByUsername(username); managedUser.setEmail(user.getEmail()); managedUser.setUserDisplayName(user.getUserDisplayName()); userRepository.save(managedUser); } @Override public List<UserInfo> searchUsers(String keyword, int offset, int limit) { List<UserPO> users = this.findUsers(keyword); if (CollectionUtils.isEmpty(users)) { return Collections.emptyList(); } return users.stream().map(UserPO::toUserInfo) .collect(Collectors.toList()); } private List<UserPO> findUsers(String keyword) { if (StringUtils.isEmpty(keyword)) { return userRepository.findFirst20ByEnabled(1); } List<UserPO> users = new ArrayList<>(); List<UserPO> byUsername = userRepository .findByUsernameLikeAndEnabled("%" + keyword + "%", 1); List<UserPO> byUserDisplayName = userRepository .findByUserDisplayNameLikeAndEnabled("%" + keyword + "%", 1); if (!CollectionUtils.isEmpty(byUsername)) { users.addAll(byUsername); } if (!CollectionUtils.isEmpty(byUserDisplayName)) { users.addAll(byUserDisplayName); } return users; } @Override public UserInfo findByUserId(String userId) { UserPO userPO = userRepository.findByUsername(userId); return userPO == null ? null : userPO.toUserInfo(); } @Override public List<UserInfo> findByUserIds(List<String> userIds) { List<UserPO> users = userRepository.findByUsernameIn(userIds); if (CollectionUtils.isEmpty(users)) { return Collections.emptyList(); } List<UserInfo> result = Lists.newArrayList(); result.addAll(users.stream().map(UserPO::toUserInfo).collect(Collectors.toList())); return result; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.springsecurity; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.portal.entity.bo.UserInfo; import com.ctrip.framework.apollo.portal.entity.po.UserPO; import com.ctrip.framework.apollo.portal.repository.UserRepository; import com.ctrip.framework.apollo.portal.spi.UserService; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.JdbcUserDetailsManager; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** * @author lepdou 2017-03-10 */ public class SpringSecurityUserService implements UserService { private final List<GrantedAuthority> authorities = Collections .unmodifiableList(Arrays.asList(new SimpleGrantedAuthority("ROLE_user"))); private final PasswordEncoder passwordEncoder; private final JdbcUserDetailsManager userDetailsManager; private final UserRepository userRepository; public SpringSecurityUserService( PasswordEncoder passwordEncoder, JdbcUserDetailsManager userDetailsManager, UserRepository userRepository) { this.passwordEncoder = passwordEncoder; this.userDetailsManager = userDetailsManager; this.userRepository = userRepository; } @Transactional public void createOrUpdate(UserPO user) { String username = user.getUsername(); User userDetails = new User(username, passwordEncoder.encode(user.getPassword()), authorities); if (userDetailsManager.userExists(username)) { userDetailsManager.updateUser(userDetails); } else { userDetailsManager.createUser(userDetails); } UserPO managedUser = userRepository.findByUsername(username); managedUser.setEmail(user.getEmail()); managedUser.setUserDisplayName(user.getUserDisplayName()); userRepository.save(managedUser); } @Override public List<UserInfo> searchUsers(String keyword, int offset, int limit) { List<UserPO> users = this.findUsers(keyword); if (CollectionUtils.isEmpty(users)) { return Collections.emptyList(); } return users.stream().map(UserPO::toUserInfo) .collect(Collectors.toList()); } private List<UserPO> findUsers(String keyword) { if (StringUtils.isEmpty(keyword)) { return userRepository.findFirst20ByEnabled(1); } List<UserPO> users = new ArrayList<>(); List<UserPO> byUsername = userRepository .findByUsernameLikeAndEnabled("%" + keyword + "%", 1); List<UserPO> byUserDisplayName = userRepository .findByUserDisplayNameLikeAndEnabled("%" + keyword + "%", 1); if (!CollectionUtils.isEmpty(byUsername)) { users.addAll(byUsername); } if (!CollectionUtils.isEmpty(byUserDisplayName)) { users.addAll(byUserDisplayName); } return users; } @Override public UserInfo findByUserId(String userId) { UserPO userPO = userRepository.findByUsername(userId); return userPO == null ? null : userPO.toUserInfo(); } @Override public List<UserInfo> findByUserIds(List<String> userIds) { List<UserPO> users = userRepository.findByUsernameIn(userIds); if (CollectionUtils.isEmpty(users)) { return Collections.emptyList(); } return users.stream().map(UserPO::toUserInfo).collect(Collectors.toList()); } }
1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./scripts/apollo-on-kubernetes/db/portal-db/apolloportaldb.sql
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Create Database # ------------------------------------------------------------ CREATE DATABASE IF NOT EXISTS ApolloPortalDB DEFAULT CHARACTER SET = utf8mb4; Use ApolloPortalDB; # Dump of table app # ------------------------------------------------------------ DROP TABLE IF EXISTS `App`; CREATE TABLE `App` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Name` (`Name`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用表'; # Dump of table appnamespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `AppNamespace`; CREATE TABLE `AppNamespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT 'namespace名字,注意,需要全局唯一', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'app id', `Format` varchar(32) NOT NULL DEFAULT 'properties' COMMENT 'namespace的format类型', `IsPublic` bit(1) NOT NULL DEFAULT b'0' COMMENT 'namespace是否为公共', `Comment` varchar(64) NOT NULL DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId` (`AppId`), KEY `Name_AppId` (`Name`,`AppId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用namespace定义'; # Dump of table consumer # ------------------------------------------------------------ DROP TABLE IF EXISTS `Consumer`; CREATE TABLE `Consumer` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='开放API消费者'; # Dump of table consumeraudit # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerAudit`; CREATE TABLE `ConsumerAudit` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'Consumer Id', `Uri` varchar(1024) NOT NULL DEFAULT '' COMMENT '访问的Uri', `Method` varchar(16) NOT NULL DEFAULT '' COMMENT '访问的Method', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_ConsumerId` (`ConsumerId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer审计表'; # Dump of table consumerrole # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerRole`; CREATE TABLE `ConsumerRole` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'Consumer Id', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_ConsumerId_RoleId` (`ConsumerId`,`RoleId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer和role的绑定表'; # Dump of table consumertoken # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerToken`; CREATE TABLE `ConsumerToken` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'ConsumerId', `Token` varchar(128) NOT NULL DEFAULT '' COMMENT 'token', `Expires` datetime NOT NULL DEFAULT '2099-01-01 00:00:00' COMMENT 'token失效时间', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_Token` (`Token`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer token表'; # Dump of table favorite # ------------------------------------------------------------ DROP TABLE IF EXISTS `Favorite`; CREATE TABLE `Favorite` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `UserId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '收藏的用户', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Position` int(32) NOT NULL DEFAULT '10000' COMMENT '收藏顺序', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `IX_UserId` (`UserId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8mb4 COMMENT='应用收藏表'; # Dump of table permission # ------------------------------------------------------------ DROP TABLE IF EXISTS `Permission`; CREATE TABLE `Permission` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `PermissionType` varchar(32) NOT NULL DEFAULT '' COMMENT '权限类型', `TargetId` varchar(256) NOT NULL DEFAULT '' COMMENT '权限对象类型', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_TargetId_PermissionType` (`TargetId`(191),`PermissionType`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='permission表'; # Dump of table role # ------------------------------------------------------------ DROP TABLE IF EXISTS `Role`; CREATE TABLE `Role` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `RoleName` varchar(256) NOT NULL DEFAULT '' COMMENT 'Role name', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_RoleName` (`RoleName`(191)), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色表'; # Dump of table rolepermission # ------------------------------------------------------------ DROP TABLE IF EXISTS `RolePermission`; CREATE TABLE `RolePermission` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `PermissionId` int(10) unsigned DEFAULT NULL COMMENT 'Permission Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_PermissionId` (`PermissionId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色和权限的绑定表'; # Dump of table serverconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `ServerConfig`; CREATE TABLE `ServerConfig` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Key` varchar(64) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Value` varchar(2048) NOT NULL DEFAULT 'default' COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Key` (`Key`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置服务自身配置'; # Dump of table userrole # ------------------------------------------------------------ DROP TABLE IF EXISTS `UserRole`; CREATE TABLE `UserRole` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `UserId` varchar(128) DEFAULT '' COMMENT '用户身份标识', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_UserId_RoleId` (`UserId`,`RoleId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户和role的绑定表'; # Dump of table Users # ------------------------------------------------------------ DROP TABLE IF EXISTS `Users`; CREATE TABLE `Users` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Username` varchar(64) NOT NULL DEFAULT 'default' COMMENT '用户登录账户', `Password` varchar(64) NOT NULL DEFAULT 'default' COMMENT '密码', `UserDisplayName` varchar(512) NOT NULL DEFAULT 'default' COMMENT '用户名称', `Email` varchar(64) NOT NULL DEFAULT 'default' COMMENT '邮箱地址', `Enabled` tinyint(4) DEFAULT NULL COMMENT '是否有效', PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表'; # Dump of table Authorities # ------------------------------------------------------------ DROP TABLE IF EXISTS `Authorities`; CREATE TABLE `Authorities` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Username` varchar(64) NOT NULL, `Authority` varchar(50) NOT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; # Config # ------------------------------------------------------------ INSERT INTO `ServerConfig` (`Key`, `Value`, `Comment`) VALUES ('apollo.portal.envs', 'dev, fat, uat, pro', '可支持的环境列表'), ('organizations', '[{\"orgId\":\"TEST1\",\"orgName\":\"样例部门1\"},{\"orgId\":\"TEST2\",\"orgName\":\"样例部门2\"}]', '部门列表'), ('superAdmin', 'apollo', 'Portal超级管理员'), ('api.readTimeout', '10000', 'http接口read timeout'), ('consumer.token.salt', 'someSalt', 'consumer token salt'), ('admin.createPrivateNamespace.switch', 'true', '是否允许项目管理员创建私有namespace'), ('configView.memberOnly.envs', 'pro', '只对项目成员显示配置信息的环境列表,多个env以英文逗号分隔'), ('apollo.portal.meta.servers', '{}', '各环境Meta Service列表'); INSERT INTO `Users` (`Username`, `Password`, `UserDisplayName`, `Email`, `Enabled`) VALUES ('apollo', '$2a$10$7r20uS.BQ9uBpf3Baj3uQOZvMVvB1RN3PYoKE94gtz2.WAOuiiwXS', 'apollo', 'apollo@acme.com', 1); INSERT INTO `Authorities` (`Username`, `Authority`) VALUES ('apollo', 'ROLE_user'); /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Create Database # ------------------------------------------------------------ CREATE DATABASE IF NOT EXISTS ApolloPortalDB DEFAULT CHARACTER SET = utf8mb4; Use ApolloPortalDB; # Dump of table app # ------------------------------------------------------------ DROP TABLE IF EXISTS `App`; CREATE TABLE `App` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Name` (`Name`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用表'; # Dump of table appnamespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `AppNamespace`; CREATE TABLE `AppNamespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT 'namespace名字,注意,需要全局唯一', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'app id', `Format` varchar(32) NOT NULL DEFAULT 'properties' COMMENT 'namespace的format类型', `IsPublic` bit(1) NOT NULL DEFAULT b'0' COMMENT 'namespace是否为公共', `Comment` varchar(64) NOT NULL DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId` (`AppId`), KEY `Name_AppId` (`Name`,`AppId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用namespace定义'; # Dump of table consumer # ------------------------------------------------------------ DROP TABLE IF EXISTS `Consumer`; CREATE TABLE `Consumer` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='开放API消费者'; # Dump of table consumeraudit # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerAudit`; CREATE TABLE `ConsumerAudit` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'Consumer Id', `Uri` varchar(1024) NOT NULL DEFAULT '' COMMENT '访问的Uri', `Method` varchar(16) NOT NULL DEFAULT '' COMMENT '访问的Method', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_ConsumerId` (`ConsumerId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer审计表'; # Dump of table consumerrole # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerRole`; CREATE TABLE `ConsumerRole` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'Consumer Id', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_ConsumerId_RoleId` (`ConsumerId`,`RoleId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer和role的绑定表'; # Dump of table consumertoken # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerToken`; CREATE TABLE `ConsumerToken` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'ConsumerId', `Token` varchar(128) NOT NULL DEFAULT '' COMMENT 'token', `Expires` datetime NOT NULL DEFAULT '2099-01-01 00:00:00' COMMENT 'token失效时间', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_Token` (`Token`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer token表'; # Dump of table favorite # ------------------------------------------------------------ DROP TABLE IF EXISTS `Favorite`; CREATE TABLE `Favorite` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `UserId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '收藏的用户', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Position` int(32) NOT NULL DEFAULT '10000' COMMENT '收藏顺序', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `IX_UserId` (`UserId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8mb4 COMMENT='应用收藏表'; # Dump of table permission # ------------------------------------------------------------ DROP TABLE IF EXISTS `Permission`; CREATE TABLE `Permission` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `PermissionType` varchar(32) NOT NULL DEFAULT '' COMMENT '权限类型', `TargetId` varchar(256) NOT NULL DEFAULT '' COMMENT '权限对象类型', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_TargetId_PermissionType` (`TargetId`(191),`PermissionType`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='permission表'; # Dump of table role # ------------------------------------------------------------ DROP TABLE IF EXISTS `Role`; CREATE TABLE `Role` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `RoleName` varchar(256) NOT NULL DEFAULT '' COMMENT 'Role name', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_RoleName` (`RoleName`(191)), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色表'; # Dump of table rolepermission # ------------------------------------------------------------ DROP TABLE IF EXISTS `RolePermission`; CREATE TABLE `RolePermission` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `PermissionId` int(10) unsigned DEFAULT NULL COMMENT 'Permission Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_PermissionId` (`PermissionId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色和权限的绑定表'; # Dump of table serverconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `ServerConfig`; CREATE TABLE `ServerConfig` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Key` varchar(64) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Value` varchar(2048) NOT NULL DEFAULT 'default' COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Key` (`Key`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置服务自身配置'; # Dump of table userrole # ------------------------------------------------------------ DROP TABLE IF EXISTS `UserRole`; CREATE TABLE `UserRole` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `UserId` varchar(128) DEFAULT '' COMMENT '用户身份标识', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_UserId_RoleId` (`UserId`,`RoleId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户和role的绑定表'; # Dump of table Users # ------------------------------------------------------------ DROP TABLE IF EXISTS `Users`; CREATE TABLE `Users` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Username` varchar(64) NOT NULL DEFAULT 'default' COMMENT '用户登录账户', `Password` varchar(512) NOT NULL DEFAULT 'default' COMMENT '密码', `UserDisplayName` varchar(512) NOT NULL DEFAULT 'default' COMMENT '用户名称', `Email` varchar(64) NOT NULL DEFAULT 'default' COMMENT '邮箱地址', `Enabled` tinyint(4) DEFAULT NULL COMMENT '是否有效', PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表'; # Dump of table Authorities # ------------------------------------------------------------ DROP TABLE IF EXISTS `Authorities`; CREATE TABLE `Authorities` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Username` varchar(64) NOT NULL, `Authority` varchar(50) NOT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; # Config # ------------------------------------------------------------ INSERT INTO `ServerConfig` (`Key`, `Value`, `Comment`) VALUES ('apollo.portal.envs', 'dev, fat, uat, pro', '可支持的环境列表'), ('organizations', '[{\"orgId\":\"TEST1\",\"orgName\":\"样例部门1\"},{\"orgId\":\"TEST2\",\"orgName\":\"样例部门2\"}]', '部门列表'), ('superAdmin', 'apollo', 'Portal超级管理员'), ('api.readTimeout', '10000', 'http接口read timeout'), ('consumer.token.salt', 'someSalt', 'consumer token salt'), ('admin.createPrivateNamespace.switch', 'true', '是否允许项目管理员创建私有namespace'), ('configView.memberOnly.envs', 'pro', '只对项目成员显示配置信息的环境列表,多个env以英文逗号分隔'), ('apollo.portal.meta.servers', '{}', '各环境Meta Service列表'); INSERT INTO `Users` (`Username`, `Password`, `UserDisplayName`, `Email`, `Enabled`) VALUES ('apollo', '$2a$10$7r20uS.BQ9uBpf3Baj3uQOZvMVvB1RN3PYoKE94gtz2.WAOuiiwXS', 'apollo', 'apollo@acme.com', 1); INSERT INTO `Authorities` (`Username`, `Authority`) VALUES ('apollo', 'ROLE_user'); /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./scripts/docker-quick-start/sql/apolloportaldb.sql
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Create Database # ------------------------------------------------------------ CREATE DATABASE IF NOT EXISTS ApolloPortalDB DEFAULT CHARACTER SET = utf8mb4; Use ApolloPortalDB; # Dump of table app # ------------------------------------------------------------ DROP TABLE IF EXISTS `App`; CREATE TABLE `App` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Name` (`Name`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用表'; # Dump of table appnamespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `AppNamespace`; CREATE TABLE `AppNamespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT 'namespace名字,注意,需要全局唯一', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'app id', `Format` varchar(32) NOT NULL DEFAULT 'properties' COMMENT 'namespace的format类型', `IsPublic` bit(1) NOT NULL DEFAULT b'0' COMMENT 'namespace是否为公共', `Comment` varchar(64) NOT NULL DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId` (`AppId`), KEY `Name_AppId` (`Name`,`AppId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用namespace定义'; # Dump of table consumer # ------------------------------------------------------------ DROP TABLE IF EXISTS `Consumer`; CREATE TABLE `Consumer` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='开放API消费者'; # Dump of table consumeraudit # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerAudit`; CREATE TABLE `ConsumerAudit` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'Consumer Id', `Uri` varchar(1024) NOT NULL DEFAULT '' COMMENT '访问的Uri', `Method` varchar(16) NOT NULL DEFAULT '' COMMENT '访问的Method', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_ConsumerId` (`ConsumerId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer审计表'; # Dump of table consumerrole # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerRole`; CREATE TABLE `ConsumerRole` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'Consumer Id', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_ConsumerId_RoleId` (`ConsumerId`,`RoleId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer和role的绑定表'; # Dump of table consumertoken # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerToken`; CREATE TABLE `ConsumerToken` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'ConsumerId', `Token` varchar(128) NOT NULL DEFAULT '' COMMENT 'token', `Expires` datetime NOT NULL DEFAULT '2099-01-01 00:00:00' COMMENT 'token失效时间', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_Token` (`Token`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer token表'; # Dump of table favorite # ------------------------------------------------------------ DROP TABLE IF EXISTS `Favorite`; CREATE TABLE `Favorite` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `UserId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '收藏的用户', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Position` int(32) NOT NULL DEFAULT '10000' COMMENT '收藏顺序', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `IX_UserId` (`UserId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8mb4 COMMENT='应用收藏表'; # Dump of table permission # ------------------------------------------------------------ DROP TABLE IF EXISTS `Permission`; CREATE TABLE `Permission` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `PermissionType` varchar(32) NOT NULL DEFAULT '' COMMENT '权限类型', `TargetId` varchar(256) NOT NULL DEFAULT '' COMMENT '权限对象类型', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_TargetId_PermissionType` (`TargetId`(191),`PermissionType`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='permission表'; # Dump of table role # ------------------------------------------------------------ DROP TABLE IF EXISTS `Role`; CREATE TABLE `Role` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `RoleName` varchar(256) NOT NULL DEFAULT '' COMMENT 'Role name', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_RoleName` (`RoleName`(191)), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色表'; # Dump of table rolepermission # ------------------------------------------------------------ DROP TABLE IF EXISTS `RolePermission`; CREATE TABLE `RolePermission` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `PermissionId` int(10) unsigned DEFAULT NULL COMMENT 'Permission Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_PermissionId` (`PermissionId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色和权限的绑定表'; # Dump of table serverconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `ServerConfig`; CREATE TABLE `ServerConfig` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Key` varchar(64) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Value` varchar(2048) NOT NULL DEFAULT 'default' COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Key` (`Key`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置服务自身配置'; # Dump of table userrole # ------------------------------------------------------------ DROP TABLE IF EXISTS `UserRole`; CREATE TABLE `UserRole` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `UserId` varchar(128) DEFAULT '' COMMENT '用户身份标识', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_UserId_RoleId` (`UserId`,`RoleId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户和role的绑定表'; # Dump of table Users # ------------------------------------------------------------ DROP TABLE IF EXISTS `Users`; CREATE TABLE `Users` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Username` varchar(64) NOT NULL DEFAULT 'default' COMMENT '用户登录账户', `Password` varchar(64) NOT NULL DEFAULT 'default' COMMENT '密码', `UserDisplayName` varchar(512) NOT NULL DEFAULT 'default' COMMENT '用户名称', `Email` varchar(64) NOT NULL DEFAULT 'default' COMMENT '邮箱地址', `Enabled` tinyint(4) DEFAULT NULL COMMENT '是否有效', PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表'; # Dump of table Authorities # ------------------------------------------------------------ DROP TABLE IF EXISTS `Authorities`; CREATE TABLE `Authorities` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Username` varchar(64) NOT NULL, `Authority` varchar(50) NOT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; # Config # ------------------------------------------------------------ INSERT INTO `ServerConfig` (`Key`, `Value`, `Comment`) VALUES ('apollo.portal.envs', 'dev', '可支持的环境列表'), ('organizations', '[{\"orgId\":\"TEST1\",\"orgName\":\"样例部门1\"},{\"orgId\":\"TEST2\",\"orgName\":\"样例部门2\"}]', '部门列表'), ('superAdmin', 'apollo', 'Portal超级管理员'), ('api.readTimeout', '10000', 'http接口read timeout'), ('consumer.token.salt', 'someSalt', 'consumer token salt'), ('admin.createPrivateNamespace.switch', 'true', '是否允许项目管理员创建私有namespace'), ('configView.memberOnly.envs', 'dev', '只对项目成员显示配置信息的环境列表,多个env以英文逗号分隔'), ('apollo.portal.meta.servers', '{}', '各环境Meta Service列表'); INSERT INTO `Users` (`Username`, `Password`, `UserDisplayName`, `Email`, `Enabled`) VALUES ('apollo', '$2a$10$7r20uS.BQ9uBpf3Baj3uQOZvMVvB1RN3PYoKE94gtz2.WAOuiiwXS', 'apollo', 'apollo@acme.com', 1); INSERT INTO `Authorities` (`Username`, `Authority`) VALUES ('apollo', 'ROLE_user'); # Sample Data # ------------------------------------------------------------ INSERT INTO `App` (`AppId`, `Name`, `OrgId`, `OrgName`, `OwnerName`, `OwnerEmail`) VALUES ('SampleApp', 'Sample App', 'TEST1', '样例部门1', 'apollo', 'apollo@acme.com'); INSERT INTO `AppNamespace` (`Name`, `AppId`, `Format`, `IsPublic`, `Comment`) VALUES ('application', 'SampleApp', 'properties', 0, 'default app namespace'); INSERT INTO `Permission` (`Id`, `PermissionType`, `TargetId`) VALUES (1, 'CreateCluster', 'SampleApp'), (2, 'CreateNamespace', 'SampleApp'), (3, 'AssignRole', 'SampleApp'), (4, 'ModifyNamespace', 'SampleApp+application'), (5, 'ReleaseNamespace', 'SampleApp+application'); INSERT INTO `Role` (`Id`, `RoleName`) VALUES (1, 'Master+SampleApp'), (2, 'ModifyNamespace+SampleApp+application'), (3, 'ReleaseNamespace+SampleApp+application'); INSERT INTO `RolePermission` (`RoleId`, `PermissionId`) VALUES (1, 1), (1, 2), (1, 3), (2, 4), (3, 5); INSERT INTO `UserRole` (`UserId`, `RoleId`) VALUES ('apollo', 1), ('apollo', 2), ('apollo', 3); /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Create Database # ------------------------------------------------------------ CREATE DATABASE IF NOT EXISTS ApolloPortalDB DEFAULT CHARACTER SET = utf8mb4; Use ApolloPortalDB; # Dump of table app # ------------------------------------------------------------ DROP TABLE IF EXISTS `App`; CREATE TABLE `App` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Name` (`Name`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用表'; # Dump of table appnamespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `AppNamespace`; CREATE TABLE `AppNamespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT 'namespace名字,注意,需要全局唯一', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'app id', `Format` varchar(32) NOT NULL DEFAULT 'properties' COMMENT 'namespace的format类型', `IsPublic` bit(1) NOT NULL DEFAULT b'0' COMMENT 'namespace是否为公共', `Comment` varchar(64) NOT NULL DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId` (`AppId`), KEY `Name_AppId` (`Name`,`AppId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用namespace定义'; # Dump of table consumer # ------------------------------------------------------------ DROP TABLE IF EXISTS `Consumer`; CREATE TABLE `Consumer` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='开放API消费者'; # Dump of table consumeraudit # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerAudit`; CREATE TABLE `ConsumerAudit` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'Consumer Id', `Uri` varchar(1024) NOT NULL DEFAULT '' COMMENT '访问的Uri', `Method` varchar(16) NOT NULL DEFAULT '' COMMENT '访问的Method', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_ConsumerId` (`ConsumerId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer审计表'; # Dump of table consumerrole # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerRole`; CREATE TABLE `ConsumerRole` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'Consumer Id', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_ConsumerId_RoleId` (`ConsumerId`,`RoleId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer和role的绑定表'; # Dump of table consumertoken # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerToken`; CREATE TABLE `ConsumerToken` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'ConsumerId', `Token` varchar(128) NOT NULL DEFAULT '' COMMENT 'token', `Expires` datetime NOT NULL DEFAULT '2099-01-01 00:00:00' COMMENT 'token失效时间', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_Token` (`Token`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer token表'; # Dump of table favorite # ------------------------------------------------------------ DROP TABLE IF EXISTS `Favorite`; CREATE TABLE `Favorite` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `UserId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '收藏的用户', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Position` int(32) NOT NULL DEFAULT '10000' COMMENT '收藏顺序', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `IX_UserId` (`UserId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8mb4 COMMENT='应用收藏表'; # Dump of table permission # ------------------------------------------------------------ DROP TABLE IF EXISTS `Permission`; CREATE TABLE `Permission` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `PermissionType` varchar(32) NOT NULL DEFAULT '' COMMENT '权限类型', `TargetId` varchar(256) NOT NULL DEFAULT '' COMMENT '权限对象类型', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_TargetId_PermissionType` (`TargetId`(191),`PermissionType`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='permission表'; # Dump of table role # ------------------------------------------------------------ DROP TABLE IF EXISTS `Role`; CREATE TABLE `Role` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `RoleName` varchar(256) NOT NULL DEFAULT '' COMMENT 'Role name', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_RoleName` (`RoleName`(191)), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色表'; # Dump of table rolepermission # ------------------------------------------------------------ DROP TABLE IF EXISTS `RolePermission`; CREATE TABLE `RolePermission` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `PermissionId` int(10) unsigned DEFAULT NULL COMMENT 'Permission Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_PermissionId` (`PermissionId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色和权限的绑定表'; # Dump of table serverconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `ServerConfig`; CREATE TABLE `ServerConfig` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Key` varchar(64) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Value` varchar(2048) NOT NULL DEFAULT 'default' COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Key` (`Key`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置服务自身配置'; # Dump of table userrole # ------------------------------------------------------------ DROP TABLE IF EXISTS `UserRole`; CREATE TABLE `UserRole` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `UserId` varchar(128) DEFAULT '' COMMENT '用户身份标识', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_UserId_RoleId` (`UserId`,`RoleId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户和role的绑定表'; # Dump of table Users # ------------------------------------------------------------ DROP TABLE IF EXISTS `Users`; CREATE TABLE `Users` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Username` varchar(64) NOT NULL DEFAULT 'default' COMMENT '用户登录账户', `Password` varchar(512) NOT NULL DEFAULT 'default' COMMENT '密码', `UserDisplayName` varchar(512) NOT NULL DEFAULT 'default' COMMENT '用户名称', `Email` varchar(64) NOT NULL DEFAULT 'default' COMMENT '邮箱地址', `Enabled` tinyint(4) DEFAULT NULL COMMENT '是否有效', PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表'; # Dump of table Authorities # ------------------------------------------------------------ DROP TABLE IF EXISTS `Authorities`; CREATE TABLE `Authorities` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Username` varchar(64) NOT NULL, `Authority` varchar(50) NOT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; # Config # ------------------------------------------------------------ INSERT INTO `ServerConfig` (`Key`, `Value`, `Comment`) VALUES ('apollo.portal.envs', 'dev', '可支持的环境列表'), ('organizations', '[{\"orgId\":\"TEST1\",\"orgName\":\"样例部门1\"},{\"orgId\":\"TEST2\",\"orgName\":\"样例部门2\"}]', '部门列表'), ('superAdmin', 'apollo', 'Portal超级管理员'), ('api.readTimeout', '10000', 'http接口read timeout'), ('consumer.token.salt', 'someSalt', 'consumer token salt'), ('admin.createPrivateNamespace.switch', 'true', '是否允许项目管理员创建私有namespace'), ('configView.memberOnly.envs', 'dev', '只对项目成员显示配置信息的环境列表,多个env以英文逗号分隔'), ('apollo.portal.meta.servers', '{}', '各环境Meta Service列表'); INSERT INTO `Users` (`Username`, `Password`, `UserDisplayName`, `Email`, `Enabled`) VALUES ('apollo', '$2a$10$7r20uS.BQ9uBpf3Baj3uQOZvMVvB1RN3PYoKE94gtz2.WAOuiiwXS', 'apollo', 'apollo@acme.com', 1); INSERT INTO `Authorities` (`Username`, `Authority`) VALUES ('apollo', 'ROLE_user'); # Sample Data # ------------------------------------------------------------ INSERT INTO `App` (`AppId`, `Name`, `OrgId`, `OrgName`, `OwnerName`, `OwnerEmail`) VALUES ('SampleApp', 'Sample App', 'TEST1', '样例部门1', 'apollo', 'apollo@acme.com'); INSERT INTO `AppNamespace` (`Name`, `AppId`, `Format`, `IsPublic`, `Comment`) VALUES ('application', 'SampleApp', 'properties', 0, 'default app namespace'); INSERT INTO `Permission` (`Id`, `PermissionType`, `TargetId`) VALUES (1, 'CreateCluster', 'SampleApp'), (2, 'CreateNamespace', 'SampleApp'), (3, 'AssignRole', 'SampleApp'), (4, 'ModifyNamespace', 'SampleApp+application'), (5, 'ReleaseNamespace', 'SampleApp+application'); INSERT INTO `Role` (`Id`, `RoleName`) VALUES (1, 'Master+SampleApp'), (2, 'ModifyNamespace+SampleApp+application'), (3, 'ReleaseNamespace+SampleApp+application'); INSERT INTO `RolePermission` (`RoleId`, `PermissionId`) VALUES (1, 1), (1, 2), (1, 3), (2, 4), (3, 5); INSERT INTO `UserRole` (`UserId`, `RoleId`) VALUES ('apollo', 1), ('apollo', 2), ('apollo', 3); /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./scripts/sql/apolloportaldb.sql
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Create Database # ------------------------------------------------------------ CREATE DATABASE IF NOT EXISTS ApolloPortalDB DEFAULT CHARACTER SET = utf8mb4; Use ApolloPortalDB; # Dump of table app # ------------------------------------------------------------ DROP TABLE IF EXISTS `App`; CREATE TABLE `App` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Name` (`Name`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用表'; # Dump of table appnamespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `AppNamespace`; CREATE TABLE `AppNamespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT 'namespace名字,注意,需要全局唯一', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'app id', `Format` varchar(32) NOT NULL DEFAULT 'properties' COMMENT 'namespace的format类型', `IsPublic` bit(1) NOT NULL DEFAULT b'0' COMMENT 'namespace是否为公共', `Comment` varchar(64) NOT NULL DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId` (`AppId`), KEY `Name_AppId` (`Name`,`AppId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用namespace定义'; # Dump of table consumer # ------------------------------------------------------------ DROP TABLE IF EXISTS `Consumer`; CREATE TABLE `Consumer` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='开放API消费者'; # Dump of table consumeraudit # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerAudit`; CREATE TABLE `ConsumerAudit` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'Consumer Id', `Uri` varchar(1024) NOT NULL DEFAULT '' COMMENT '访问的Uri', `Method` varchar(16) NOT NULL DEFAULT '' COMMENT '访问的Method', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_ConsumerId` (`ConsumerId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer审计表'; # Dump of table consumerrole # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerRole`; CREATE TABLE `ConsumerRole` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'Consumer Id', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_ConsumerId_RoleId` (`ConsumerId`,`RoleId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer和role的绑定表'; # Dump of table consumertoken # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerToken`; CREATE TABLE `ConsumerToken` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'ConsumerId', `Token` varchar(128) NOT NULL DEFAULT '' COMMENT 'token', `Expires` datetime NOT NULL DEFAULT '2099-01-01 00:00:00' COMMENT 'token失效时间', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_Token` (`Token`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer token表'; # Dump of table favorite # ------------------------------------------------------------ DROP TABLE IF EXISTS `Favorite`; CREATE TABLE `Favorite` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `UserId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '收藏的用户', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Position` int(32) NOT NULL DEFAULT '10000' COMMENT '收藏顺序', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `IX_UserId` (`UserId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8mb4 COMMENT='应用收藏表'; # Dump of table permission # ------------------------------------------------------------ DROP TABLE IF EXISTS `Permission`; CREATE TABLE `Permission` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `PermissionType` varchar(32) NOT NULL DEFAULT '' COMMENT '权限类型', `TargetId` varchar(256) NOT NULL DEFAULT '' COMMENT '权限对象类型', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_TargetId_PermissionType` (`TargetId`(191),`PermissionType`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='permission表'; # Dump of table role # ------------------------------------------------------------ DROP TABLE IF EXISTS `Role`; CREATE TABLE `Role` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `RoleName` varchar(256) NOT NULL DEFAULT '' COMMENT 'Role name', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_RoleName` (`RoleName`(191)), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色表'; # Dump of table rolepermission # ------------------------------------------------------------ DROP TABLE IF EXISTS `RolePermission`; CREATE TABLE `RolePermission` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `PermissionId` int(10) unsigned DEFAULT NULL COMMENT 'Permission Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_PermissionId` (`PermissionId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色和权限的绑定表'; # Dump of table serverconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `ServerConfig`; CREATE TABLE `ServerConfig` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Key` varchar(64) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Value` varchar(2048) NOT NULL DEFAULT 'default' COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Key` (`Key`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置服务自身配置'; # Dump of table userrole # ------------------------------------------------------------ DROP TABLE IF EXISTS `UserRole`; CREATE TABLE `UserRole` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `UserId` varchar(128) DEFAULT '' COMMENT '用户身份标识', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_UserId_RoleId` (`UserId`,`RoleId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户和role的绑定表'; # Dump of table Users # ------------------------------------------------------------ DROP TABLE IF EXISTS `Users`; CREATE TABLE `Users` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Username` varchar(64) NOT NULL DEFAULT 'default' COMMENT '用户登录账户', `Password` varchar(64) NOT NULL DEFAULT 'default' COMMENT '密码', `UserDisplayName` varchar(512) NOT NULL DEFAULT 'default' COMMENT '用户名称', `Email` varchar(64) NOT NULL DEFAULT 'default' COMMENT '邮箱地址', `Enabled` tinyint(4) DEFAULT NULL COMMENT '是否有效', PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表'; # Dump of table Authorities # ------------------------------------------------------------ DROP TABLE IF EXISTS `Authorities`; CREATE TABLE `Authorities` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Username` varchar(64) NOT NULL, `Authority` varchar(50) NOT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; # Config # ------------------------------------------------------------ INSERT INTO `ServerConfig` (`Key`, `Value`, `Comment`) VALUES ('apollo.portal.envs', 'dev', '可支持的环境列表'), ('organizations', '[{\"orgId\":\"TEST1\",\"orgName\":\"样例部门1\"},{\"orgId\":\"TEST2\",\"orgName\":\"样例部门2\"}]', '部门列表'), ('superAdmin', 'apollo', 'Portal超级管理员'), ('api.readTimeout', '10000', 'http接口read timeout'), ('consumer.token.salt', 'someSalt', 'consumer token salt'), ('admin.createPrivateNamespace.switch', 'true', '是否允许项目管理员创建私有namespace'), ('configView.memberOnly.envs', 'pro', '只对项目成员显示配置信息的环境列表,多个env以英文逗号分隔'), ('apollo.portal.meta.servers', '{}', '各环境Meta Service列表'); INSERT INTO `Users` (`Username`, `Password`, `UserDisplayName`, `Email`, `Enabled`) VALUES ('apollo', '$2a$10$7r20uS.BQ9uBpf3Baj3uQOZvMVvB1RN3PYoKE94gtz2.WAOuiiwXS', 'apollo', 'apollo@acme.com', 1); INSERT INTO `Authorities` (`Username`, `Authority`) VALUES ('apollo', 'ROLE_user'); /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Create Database # ------------------------------------------------------------ CREATE DATABASE IF NOT EXISTS ApolloPortalDB DEFAULT CHARACTER SET = utf8mb4; Use ApolloPortalDB; # Dump of table app # ------------------------------------------------------------ DROP TABLE IF EXISTS `App`; CREATE TABLE `App` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Name` (`Name`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用表'; # Dump of table appnamespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `AppNamespace`; CREATE TABLE `AppNamespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT 'namespace名字,注意,需要全局唯一', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'app id', `Format` varchar(32) NOT NULL DEFAULT 'properties' COMMENT 'namespace的format类型', `IsPublic` bit(1) NOT NULL DEFAULT b'0' COMMENT 'namespace是否为公共', `Comment` varchar(64) NOT NULL DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId` (`AppId`), KEY `Name_AppId` (`Name`,`AppId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用namespace定义'; # Dump of table consumer # ------------------------------------------------------------ DROP TABLE IF EXISTS `Consumer`; CREATE TABLE `Consumer` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='开放API消费者'; # Dump of table consumeraudit # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerAudit`; CREATE TABLE `ConsumerAudit` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'Consumer Id', `Uri` varchar(1024) NOT NULL DEFAULT '' COMMENT '访问的Uri', `Method` varchar(16) NOT NULL DEFAULT '' COMMENT '访问的Method', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_ConsumerId` (`ConsumerId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer审计表'; # Dump of table consumerrole # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerRole`; CREATE TABLE `ConsumerRole` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'Consumer Id', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_ConsumerId_RoleId` (`ConsumerId`,`RoleId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer和role的绑定表'; # Dump of table consumertoken # ------------------------------------------------------------ DROP TABLE IF EXISTS `ConsumerToken`; CREATE TABLE `ConsumerToken` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `ConsumerId` int(11) unsigned DEFAULT NULL COMMENT 'ConsumerId', `Token` varchar(128) NOT NULL DEFAULT '' COMMENT 'token', `Expires` datetime NOT NULL DEFAULT '2099-01-01 00:00:00' COMMENT 'token失效时间', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_Token` (`Token`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='consumer token表'; # Dump of table favorite # ------------------------------------------------------------ DROP TABLE IF EXISTS `Favorite`; CREATE TABLE `Favorite` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `UserId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '收藏的用户', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Position` int(32) NOT NULL DEFAULT '10000' COMMENT '收藏顺序', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `IX_UserId` (`UserId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8mb4 COMMENT='应用收藏表'; # Dump of table permission # ------------------------------------------------------------ DROP TABLE IF EXISTS `Permission`; CREATE TABLE `Permission` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `PermissionType` varchar(32) NOT NULL DEFAULT '' COMMENT '权限类型', `TargetId` varchar(256) NOT NULL DEFAULT '' COMMENT '权限对象类型', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_TargetId_PermissionType` (`TargetId`(191),`PermissionType`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='permission表'; # Dump of table role # ------------------------------------------------------------ DROP TABLE IF EXISTS `Role`; CREATE TABLE `Role` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `RoleName` varchar(256) NOT NULL DEFAULT '' COMMENT 'Role name', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_RoleName` (`RoleName`(191)), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色表'; # Dump of table rolepermission # ------------------------------------------------------------ DROP TABLE IF EXISTS `RolePermission`; CREATE TABLE `RolePermission` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `PermissionId` int(10) unsigned DEFAULT NULL COMMENT 'Permission Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_PermissionId` (`PermissionId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色和权限的绑定表'; # Dump of table serverconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `ServerConfig`; CREATE TABLE `ServerConfig` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Key` varchar(64) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Value` varchar(2048) NOT NULL DEFAULT 'default' COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Key` (`Key`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置服务自身配置'; # Dump of table userrole # ------------------------------------------------------------ DROP TABLE IF EXISTS `UserRole`; CREATE TABLE `UserRole` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `UserId` varchar(128) DEFAULT '' COMMENT '用户身份标识', `RoleId` int(10) unsigned DEFAULT NULL COMMENT 'Role Id', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_RoleId` (`RoleId`), KEY `IX_UserId_RoleId` (`UserId`,`RoleId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户和role的绑定表'; # Dump of table Users # ------------------------------------------------------------ DROP TABLE IF EXISTS `Users`; CREATE TABLE `Users` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Username` varchar(64) NOT NULL DEFAULT 'default' COMMENT '用户登录账户', `Password` varchar(512) NOT NULL DEFAULT 'default' COMMENT '密码', `UserDisplayName` varchar(512) NOT NULL DEFAULT 'default' COMMENT '用户名称', `Email` varchar(64) NOT NULL DEFAULT 'default' COMMENT '邮箱地址', `Enabled` tinyint(4) DEFAULT NULL COMMENT '是否有效', PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表'; # Dump of table Authorities # ------------------------------------------------------------ DROP TABLE IF EXISTS `Authorities`; CREATE TABLE `Authorities` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Username` varchar(64) NOT NULL, `Authority` varchar(50) NOT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; # Config # ------------------------------------------------------------ INSERT INTO `ServerConfig` (`Key`, `Value`, `Comment`) VALUES ('apollo.portal.envs', 'dev', '可支持的环境列表'), ('organizations', '[{\"orgId\":\"TEST1\",\"orgName\":\"样例部门1\"},{\"orgId\":\"TEST2\",\"orgName\":\"样例部门2\"}]', '部门列表'), ('superAdmin', 'apollo', 'Portal超级管理员'), ('api.readTimeout', '10000', 'http接口read timeout'), ('consumer.token.salt', 'someSalt', 'consumer token salt'), ('admin.createPrivateNamespace.switch', 'true', '是否允许项目管理员创建私有namespace'), ('configView.memberOnly.envs', 'pro', '只对项目成员显示配置信息的环境列表,多个env以英文逗号分隔'), ('apollo.portal.meta.servers', '{}', '各环境Meta Service列表'); INSERT INTO `Users` (`Username`, `Password`, `UserDisplayName`, `Email`, `Enabled`) VALUES ('apollo', '$2a$10$7r20uS.BQ9uBpf3Baj3uQOZvMVvB1RN3PYoKE94gtz2.WAOuiiwXS', 'apollo', 'apollo@acme.com', 1); INSERT INTO `Authorities` (`Username`, `Authority`) VALUES ('apollo', 'ROLE_user'); /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./scripts/sql/delta/v180-v190/apolloportaldb-v180-v190.sql
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- # delta schema to upgrade apollo portal db from v1.8.0 to v1.9.0 Use ApolloPortalDB; ALTER TABLE `App` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `AppNamespace` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `Consumer` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `ConsumerRole` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `ConsumerToken` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `Favorite` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `Permission` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `Role` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `RolePermission` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `ServerConfig` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `UserRole` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `Users` MODIFY COLUMN `Username` varchar(64) NOT NULL DEFAULT 'default' COMMENT '用户登录账户', ADD COLUMN `UserDisplayName` varchar(512) NOT NULL DEFAULT 'default' COMMENT '用户名称' AFTER `Password`; UPDATE `Users` SET `UserDisplayName`=`Username` WHERE `UserDisplayName` = 'default';
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- # delta schema to upgrade apollo portal db from v1.8.0 to v1.9.0 Use ApolloPortalDB; ALTER TABLE `App` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `AppNamespace` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `Consumer` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `ConsumerRole` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `ConsumerToken` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `Favorite` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `Permission` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `Role` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `RolePermission` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `ServerConfig` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `UserRole` MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀'; ALTER TABLE `Users` MODIFY COLUMN `Username` varchar(64) NOT NULL DEFAULT 'default' COMMENT '用户登录账户', ADD COLUMN `UserDisplayName` varchar(512) NOT NULL DEFAULT 'default' COMMENT '用户名称' AFTER `Password`; UPDATE `Users` SET `UserDisplayName`=`Username` WHERE `UserDisplayName` = 'default'; ALTER TABLE `Users` MODIFY COLUMN `Password` varchar(512) NOT NULL DEFAULT 'default' COMMENT '密码'; UPDATE `Users` SET `Password` = REPLACE(`Password`, '{nonsensical}', '{placeholder}') WHERE `Password` LIKE '{nonsensical}%'; -- note: add the {bcrypt} prefix for `Users`.`Password` is not mandatory, and it may break the old version of apollo-portal while upgrading. -- 注意: 向 `Users`.`Password` 添加 {bcrypt} 是非必须操作, 并且这个操作会导致升级 apollo-portal 集群的过程中旧版的 apollo-portal 无法使用. -- UPDATE `Users` SET `Password` = CONCAT('{bcrypt}', `Password`) WHERE `Password` NOT LIKE '{%}%';
1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/properties/ApolloClientProperties.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.config.data.extension.properties; import org.springframework.boot.context.properties.NestedConfigurationProperty; /** * @author vdisk <vdisk@foxmail.com> */ public class ApolloClientProperties { /** * extension configuration */ @NestedConfigurationProperty private ApolloClientExtensionProperties extension; public ApolloClientExtensionProperties getExtension() { return extension; } public void setExtension( ApolloClientExtensionProperties extension) { this.extension = extension; } @Override public String toString() { return "ApolloClientProperties{" + "extension=" + extension + '}'; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.config.data.extension.properties; import org.springframework.boot.context.properties.NestedConfigurationProperty; /** * @author vdisk <vdisk@foxmail.com> */ public class ApolloClientProperties { /** * extension configuration */ @NestedConfigurationProperty private ApolloClientExtensionProperties extension; public ApolloClientExtensionProperties getExtension() { return extension; } public void setExtension( ApolloClientExtensionProperties extension) { this.extension = extension; } @Override public String toString() { return "ApolloClientProperties{" + "extension=" + extension + '}'; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/repository/InstanceRepository.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.repository; import com.ctrip.framework.apollo.biz.entity.Instance; import org.springframework.data.repository.PagingAndSortingRepository; public interface InstanceRepository extends PagingAndSortingRepository<Instance, Long> { Instance findByAppIdAndClusterNameAndDataCenterAndIp(String appId, String clusterName, String dataCenter, String ip); }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.repository; import com.ctrip.framework.apollo.biz.entity.Instance; import org.springframework.data.repository.PagingAndSortingRepository; public interface InstanceRepository extends PagingAndSortingRepository<Instance, Long> { Instance findByAppIdAndClusterNameAndDataCenterAndIp(String appId, String clusterName, String dataCenter, String ip); }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/grayReleaseRule/GrayReleaseRulesHolder.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.grayReleaseRule; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import com.ctrip.framework.apollo.biz.config.BizConfig; import com.ctrip.framework.apollo.biz.entity.GrayReleaseRule; import com.ctrip.framework.apollo.biz.entity.ReleaseMessage; import com.ctrip.framework.apollo.biz.message.ReleaseMessageListener; import com.ctrip.framework.apollo.biz.message.Topics; import com.ctrip.framework.apollo.biz.repository.GrayReleaseRuleRepository; import com.ctrip.framework.apollo.common.constants.NamespaceBranchStatus; import com.ctrip.framework.apollo.common.dto.GrayReleaseRuleItemDTO; import com.ctrip.framework.apollo.common.utils.GrayReleaseRuleItemTransformer; import com.ctrip.framework.apollo.core.ConfigConsts; import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; import com.ctrip.framework.apollo.tracer.Tracer; import com.ctrip.framework.apollo.tracer.spi.Transaction; import com.google.common.collect.TreeMultimap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import java.util.List; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * @author Jason Song(song_s@ctrip.com) */ public class GrayReleaseRulesHolder implements ReleaseMessageListener, InitializingBean { private static final Logger logger = LoggerFactory.getLogger(GrayReleaseRulesHolder.class); private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR); private static final Splitter STRING_SPLITTER = Splitter.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR).omitEmptyStrings(); @Autowired private GrayReleaseRuleRepository grayReleaseRuleRepository; @Autowired private BizConfig bizConfig; private int databaseScanInterval; private ScheduledExecutorService executorService; //store configAppId+configCluster+configNamespace -> GrayReleaseRuleCache map private Multimap<String, GrayReleaseRuleCache> grayReleaseRuleCache; //store clientAppId+clientNamespace+ip -> ruleId map private Multimap<String, Long> reversedGrayReleaseRuleCache; //an auto increment version to indicate the age of rules private AtomicLong loadVersion; public GrayReleaseRulesHolder() { loadVersion = new AtomicLong(); grayReleaseRuleCache = Multimaps.synchronizedSetMultimap( TreeMultimap.create(String.CASE_INSENSITIVE_ORDER, Ordering.natural())); reversedGrayReleaseRuleCache = Multimaps.synchronizedSetMultimap( TreeMultimap.create(String.CASE_INSENSITIVE_ORDER, Ordering.natural())); executorService = Executors.newScheduledThreadPool(1, ApolloThreadFactory .create("GrayReleaseRulesHolder", true)); } @Override public void afterPropertiesSet() throws Exception { populateDataBaseInterval(); //force sync load for the first time periodicScanRules(); executorService.scheduleWithFixedDelay(this::periodicScanRules, getDatabaseScanIntervalSecond(), getDatabaseScanIntervalSecond(), getDatabaseScanTimeUnit() ); } @Override public void handleMessage(ReleaseMessage message, String channel) { logger.info("message received - channel: {}, message: {}", channel, message); String releaseMessage = message.getMessage(); if (!Topics.APOLLO_RELEASE_TOPIC.equals(channel) || Strings.isNullOrEmpty(releaseMessage)) { return; } List<String> keys = STRING_SPLITTER.splitToList(releaseMessage); //message should be appId+cluster+namespace if (keys.size() != 3) { logger.error("message format invalid - {}", releaseMessage); return; } String appId = keys.get(0); String cluster = keys.get(1); String namespace = keys.get(2); List<GrayReleaseRule> rules = grayReleaseRuleRepository .findByAppIdAndClusterNameAndNamespaceName(appId, cluster, namespace); mergeGrayReleaseRules(rules); } private void periodicScanRules() { Transaction transaction = Tracer.newTransaction("Apollo.GrayReleaseRulesScanner", "scanGrayReleaseRules"); try { loadVersion.incrementAndGet(); scanGrayReleaseRules(); transaction.setStatus(Transaction.SUCCESS); } catch (Throwable ex) { transaction.setStatus(ex); logger.error("Scan gray release rule failed", ex); } finally { transaction.complete(); } } public Long findReleaseIdFromGrayReleaseRule(String clientAppId, String clientIp, String configAppId, String configCluster, String configNamespaceName) { String key = assembleGrayReleaseRuleKey(configAppId, configCluster, configNamespaceName); if (!grayReleaseRuleCache.containsKey(key)) { return null; } //create a new list to avoid ConcurrentModificationException List<GrayReleaseRuleCache> rules = Lists.newArrayList(grayReleaseRuleCache.get(key)); for (GrayReleaseRuleCache rule : rules) { //check branch status if (rule.getBranchStatus() != NamespaceBranchStatus.ACTIVE) { continue; } if (rule.matches(clientAppId, clientIp)) { return rule.getReleaseId(); } } return null; } /** * Check whether there are gray release rules for the clientAppId, clientIp, namespace * combination. Please note that even there are gray release rules, it doesn't mean it will always * load gray releases. Because gray release rules actually apply to one more dimension - cluster. */ public boolean hasGrayReleaseRule(String clientAppId, String clientIp, String namespaceName) { return reversedGrayReleaseRuleCache.containsKey(assembleReversedGrayReleaseRuleKey(clientAppId, namespaceName, clientIp)) || reversedGrayReleaseRuleCache.containsKey (assembleReversedGrayReleaseRuleKey(clientAppId, namespaceName, GrayReleaseRuleItemDTO .ALL_IP)); } private void scanGrayReleaseRules() { long maxIdScanned = 0; boolean hasMore = true; while (hasMore && !Thread.currentThread().isInterrupted()) { List<GrayReleaseRule> grayReleaseRules = grayReleaseRuleRepository .findFirst500ByIdGreaterThanOrderByIdAsc(maxIdScanned); if (CollectionUtils.isEmpty(grayReleaseRules)) { break; } mergeGrayReleaseRules(grayReleaseRules); int rulesScanned = grayReleaseRules.size(); maxIdScanned = grayReleaseRules.get(rulesScanned - 1).getId(); //batch is 500 hasMore = rulesScanned == 500; } } private void mergeGrayReleaseRules(List<GrayReleaseRule> grayReleaseRules) { if (CollectionUtils.isEmpty(grayReleaseRules)) { return; } for (GrayReleaseRule grayReleaseRule : grayReleaseRules) { if (grayReleaseRule.getReleaseId() == null || grayReleaseRule.getReleaseId() == 0) { //filter rules with no release id, i.e. never released continue; } String key = assembleGrayReleaseRuleKey(grayReleaseRule.getAppId(), grayReleaseRule .getClusterName(), grayReleaseRule.getNamespaceName()); //create a new list to avoid ConcurrentModificationException List<GrayReleaseRuleCache> rules = Lists.newArrayList(grayReleaseRuleCache.get(key)); GrayReleaseRuleCache oldRule = null; for (GrayReleaseRuleCache ruleCache : rules) { if (ruleCache.getBranchName().equals(grayReleaseRule.getBranchName())) { oldRule = ruleCache; break; } } //if old rule is null and new rule's branch status is not active, ignore if (oldRule == null && grayReleaseRule.getBranchStatus() != NamespaceBranchStatus.ACTIVE) { continue; } //use id comparison to avoid synchronization if (oldRule == null || grayReleaseRule.getId() > oldRule.getRuleId()) { addCache(key, transformRuleToRuleCache(grayReleaseRule)); if (oldRule != null) { removeCache(key, oldRule); } } else { if (oldRule.getBranchStatus() == NamespaceBranchStatus.ACTIVE) { //update load version oldRule.setLoadVersion(loadVersion.get()); } else if ((loadVersion.get() - oldRule.getLoadVersion()) > 1) { //remove outdated inactive branch rule after 2 update cycles removeCache(key, oldRule); } } } } private void addCache(String key, GrayReleaseRuleCache ruleCache) { if (ruleCache.getBranchStatus() == NamespaceBranchStatus.ACTIVE) { for (GrayReleaseRuleItemDTO ruleItemDTO : ruleCache.getRuleItems()) { for (String clientIp : ruleItemDTO.getClientIpList()) { reversedGrayReleaseRuleCache.put(assembleReversedGrayReleaseRuleKey(ruleItemDTO .getClientAppId(), ruleCache.getNamespaceName(), clientIp), ruleCache.getRuleId()); } } } grayReleaseRuleCache.put(key, ruleCache); } private void removeCache(String key, GrayReleaseRuleCache ruleCache) { grayReleaseRuleCache.remove(key, ruleCache); for (GrayReleaseRuleItemDTO ruleItemDTO : ruleCache.getRuleItems()) { for (String clientIp : ruleItemDTO.getClientIpList()) { reversedGrayReleaseRuleCache.remove(assembleReversedGrayReleaseRuleKey(ruleItemDTO .getClientAppId(), ruleCache.getNamespaceName(), clientIp), ruleCache.getRuleId()); } } } private GrayReleaseRuleCache transformRuleToRuleCache(GrayReleaseRule grayReleaseRule) { Set<GrayReleaseRuleItemDTO> ruleItems; try { ruleItems = GrayReleaseRuleItemTransformer.batchTransformFromJSON(grayReleaseRule.getRules()); } catch (Throwable ex) { ruleItems = Sets.newHashSet(); Tracer.logError(ex); logger.error("parse rule for gray release rule {} failed", grayReleaseRule.getId(), ex); } GrayReleaseRuleCache ruleCache = new GrayReleaseRuleCache(grayReleaseRule.getId(), grayReleaseRule.getBranchName(), grayReleaseRule.getNamespaceName(), grayReleaseRule .getReleaseId(), grayReleaseRule.getBranchStatus(), loadVersion.get(), ruleItems); return ruleCache; } private void populateDataBaseInterval() { databaseScanInterval = bizConfig.grayReleaseRuleScanInterval(); } private int getDatabaseScanIntervalSecond() { return databaseScanInterval; } private TimeUnit getDatabaseScanTimeUnit() { return TimeUnit.SECONDS; } private String assembleGrayReleaseRuleKey(String configAppId, String configCluster, String configNamespaceName) { return STRING_JOINER.join(configAppId, configCluster, configNamespaceName); } private String assembleReversedGrayReleaseRuleKey(String clientAppId, String clientNamespaceName, String clientIp) { return STRING_JOINER.join(clientAppId, clientNamespaceName, clientIp); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.grayReleaseRule; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import com.ctrip.framework.apollo.biz.config.BizConfig; import com.ctrip.framework.apollo.biz.entity.GrayReleaseRule; import com.ctrip.framework.apollo.biz.entity.ReleaseMessage; import com.ctrip.framework.apollo.biz.message.ReleaseMessageListener; import com.ctrip.framework.apollo.biz.message.Topics; import com.ctrip.framework.apollo.biz.repository.GrayReleaseRuleRepository; import com.ctrip.framework.apollo.common.constants.NamespaceBranchStatus; import com.ctrip.framework.apollo.common.dto.GrayReleaseRuleItemDTO; import com.ctrip.framework.apollo.common.utils.GrayReleaseRuleItemTransformer; import com.ctrip.framework.apollo.core.ConfigConsts; import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; import com.ctrip.framework.apollo.tracer.Tracer; import com.ctrip.framework.apollo.tracer.spi.Transaction; import com.google.common.collect.TreeMultimap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import java.util.List; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * @author Jason Song(song_s@ctrip.com) */ public class GrayReleaseRulesHolder implements ReleaseMessageListener, InitializingBean { private static final Logger logger = LoggerFactory.getLogger(GrayReleaseRulesHolder.class); private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR); private static final Splitter STRING_SPLITTER = Splitter.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR).omitEmptyStrings(); @Autowired private GrayReleaseRuleRepository grayReleaseRuleRepository; @Autowired private BizConfig bizConfig; private int databaseScanInterval; private ScheduledExecutorService executorService; //store configAppId+configCluster+configNamespace -> GrayReleaseRuleCache map private Multimap<String, GrayReleaseRuleCache> grayReleaseRuleCache; //store clientAppId+clientNamespace+ip -> ruleId map private Multimap<String, Long> reversedGrayReleaseRuleCache; //an auto increment version to indicate the age of rules private AtomicLong loadVersion; public GrayReleaseRulesHolder() { loadVersion = new AtomicLong(); grayReleaseRuleCache = Multimaps.synchronizedSetMultimap( TreeMultimap.create(String.CASE_INSENSITIVE_ORDER, Ordering.natural())); reversedGrayReleaseRuleCache = Multimaps.synchronizedSetMultimap( TreeMultimap.create(String.CASE_INSENSITIVE_ORDER, Ordering.natural())); executorService = Executors.newScheduledThreadPool(1, ApolloThreadFactory .create("GrayReleaseRulesHolder", true)); } @Override public void afterPropertiesSet() throws Exception { populateDataBaseInterval(); //force sync load for the first time periodicScanRules(); executorService.scheduleWithFixedDelay(this::periodicScanRules, getDatabaseScanIntervalSecond(), getDatabaseScanIntervalSecond(), getDatabaseScanTimeUnit() ); } @Override public void handleMessage(ReleaseMessage message, String channel) { logger.info("message received - channel: {}, message: {}", channel, message); String releaseMessage = message.getMessage(); if (!Topics.APOLLO_RELEASE_TOPIC.equals(channel) || Strings.isNullOrEmpty(releaseMessage)) { return; } List<String> keys = STRING_SPLITTER.splitToList(releaseMessage); //message should be appId+cluster+namespace if (keys.size() != 3) { logger.error("message format invalid - {}", releaseMessage); return; } String appId = keys.get(0); String cluster = keys.get(1); String namespace = keys.get(2); List<GrayReleaseRule> rules = grayReleaseRuleRepository .findByAppIdAndClusterNameAndNamespaceName(appId, cluster, namespace); mergeGrayReleaseRules(rules); } private void periodicScanRules() { Transaction transaction = Tracer.newTransaction("Apollo.GrayReleaseRulesScanner", "scanGrayReleaseRules"); try { loadVersion.incrementAndGet(); scanGrayReleaseRules(); transaction.setStatus(Transaction.SUCCESS); } catch (Throwable ex) { transaction.setStatus(ex); logger.error("Scan gray release rule failed", ex); } finally { transaction.complete(); } } public Long findReleaseIdFromGrayReleaseRule(String clientAppId, String clientIp, String configAppId, String configCluster, String configNamespaceName) { String key = assembleGrayReleaseRuleKey(configAppId, configCluster, configNamespaceName); if (!grayReleaseRuleCache.containsKey(key)) { return null; } //create a new list to avoid ConcurrentModificationException List<GrayReleaseRuleCache> rules = Lists.newArrayList(grayReleaseRuleCache.get(key)); for (GrayReleaseRuleCache rule : rules) { //check branch status if (rule.getBranchStatus() != NamespaceBranchStatus.ACTIVE) { continue; } if (rule.matches(clientAppId, clientIp)) { return rule.getReleaseId(); } } return null; } /** * Check whether there are gray release rules for the clientAppId, clientIp, namespace * combination. Please note that even there are gray release rules, it doesn't mean it will always * load gray releases. Because gray release rules actually apply to one more dimension - cluster. */ public boolean hasGrayReleaseRule(String clientAppId, String clientIp, String namespaceName) { return reversedGrayReleaseRuleCache.containsKey(assembleReversedGrayReleaseRuleKey(clientAppId, namespaceName, clientIp)) || reversedGrayReleaseRuleCache.containsKey (assembleReversedGrayReleaseRuleKey(clientAppId, namespaceName, GrayReleaseRuleItemDTO .ALL_IP)); } private void scanGrayReleaseRules() { long maxIdScanned = 0; boolean hasMore = true; while (hasMore && !Thread.currentThread().isInterrupted()) { List<GrayReleaseRule> grayReleaseRules = grayReleaseRuleRepository .findFirst500ByIdGreaterThanOrderByIdAsc(maxIdScanned); if (CollectionUtils.isEmpty(grayReleaseRules)) { break; } mergeGrayReleaseRules(grayReleaseRules); int rulesScanned = grayReleaseRules.size(); maxIdScanned = grayReleaseRules.get(rulesScanned - 1).getId(); //batch is 500 hasMore = rulesScanned == 500; } } private void mergeGrayReleaseRules(List<GrayReleaseRule> grayReleaseRules) { if (CollectionUtils.isEmpty(grayReleaseRules)) { return; } for (GrayReleaseRule grayReleaseRule : grayReleaseRules) { if (grayReleaseRule.getReleaseId() == null || grayReleaseRule.getReleaseId() == 0) { //filter rules with no release id, i.e. never released continue; } String key = assembleGrayReleaseRuleKey(grayReleaseRule.getAppId(), grayReleaseRule .getClusterName(), grayReleaseRule.getNamespaceName()); //create a new list to avoid ConcurrentModificationException List<GrayReleaseRuleCache> rules = Lists.newArrayList(grayReleaseRuleCache.get(key)); GrayReleaseRuleCache oldRule = null; for (GrayReleaseRuleCache ruleCache : rules) { if (ruleCache.getBranchName().equals(grayReleaseRule.getBranchName())) { oldRule = ruleCache; break; } } //if old rule is null and new rule's branch status is not active, ignore if (oldRule == null && grayReleaseRule.getBranchStatus() != NamespaceBranchStatus.ACTIVE) { continue; } //use id comparison to avoid synchronization if (oldRule == null || grayReleaseRule.getId() > oldRule.getRuleId()) { addCache(key, transformRuleToRuleCache(grayReleaseRule)); if (oldRule != null) { removeCache(key, oldRule); } } else { if (oldRule.getBranchStatus() == NamespaceBranchStatus.ACTIVE) { //update load version oldRule.setLoadVersion(loadVersion.get()); } else if ((loadVersion.get() - oldRule.getLoadVersion()) > 1) { //remove outdated inactive branch rule after 2 update cycles removeCache(key, oldRule); } } } } private void addCache(String key, GrayReleaseRuleCache ruleCache) { if (ruleCache.getBranchStatus() == NamespaceBranchStatus.ACTIVE) { for (GrayReleaseRuleItemDTO ruleItemDTO : ruleCache.getRuleItems()) { for (String clientIp : ruleItemDTO.getClientIpList()) { reversedGrayReleaseRuleCache.put(assembleReversedGrayReleaseRuleKey(ruleItemDTO .getClientAppId(), ruleCache.getNamespaceName(), clientIp), ruleCache.getRuleId()); } } } grayReleaseRuleCache.put(key, ruleCache); } private void removeCache(String key, GrayReleaseRuleCache ruleCache) { grayReleaseRuleCache.remove(key, ruleCache); for (GrayReleaseRuleItemDTO ruleItemDTO : ruleCache.getRuleItems()) { for (String clientIp : ruleItemDTO.getClientIpList()) { reversedGrayReleaseRuleCache.remove(assembleReversedGrayReleaseRuleKey(ruleItemDTO .getClientAppId(), ruleCache.getNamespaceName(), clientIp), ruleCache.getRuleId()); } } } private GrayReleaseRuleCache transformRuleToRuleCache(GrayReleaseRule grayReleaseRule) { Set<GrayReleaseRuleItemDTO> ruleItems; try { ruleItems = GrayReleaseRuleItemTransformer.batchTransformFromJSON(grayReleaseRule.getRules()); } catch (Throwable ex) { ruleItems = Sets.newHashSet(); Tracer.logError(ex); logger.error("parse rule for gray release rule {} failed", grayReleaseRule.getId(), ex); } GrayReleaseRuleCache ruleCache = new GrayReleaseRuleCache(grayReleaseRule.getId(), grayReleaseRule.getBranchName(), grayReleaseRule.getNamespaceName(), grayReleaseRule .getReleaseId(), grayReleaseRule.getBranchStatus(), loadVersion.get(), ruleItems); return ruleCache; } private void populateDataBaseInterval() { databaseScanInterval = bizConfig.grayReleaseRuleScanInterval(); } private int getDatabaseScanIntervalSecond() { return databaseScanInterval; } private TimeUnit getDatabaseScanTimeUnit() { return TimeUnit.SECONDS; } private String assembleGrayReleaseRuleKey(String configAppId, String configCluster, String configNamespaceName) { return STRING_JOINER.join(configAppId, configCluster, configNamespaceName); } private String assembleReversedGrayReleaseRuleKey(String clientAppId, String clientNamespaceName, String clientIp) { return STRING_JOINER.join(clientAppId, clientNamespaceName, clientIp); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/test/java/com/ctrip/framework/apollo/portal/environment/EnvTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.environment; import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import static org.junit.Assert.*; public class EnvTest { @Test public void exist() { assertFalse(Env.exists("xxxyyy234")); assertTrue(Env.exists("local")); assertTrue(Env.exists("dev")); } @Test public void addEnv() { String name = "someEEEE"; assertFalse(Env.exists(name)); Env.addEnvironment(name); assertTrue(Env.exists(name)); } @Test(expected = IllegalArgumentException.class) public void valueOf() { String name = "notexist"; assertFalse(Env.exists(name)); assertEquals(Env.valueOf(name), Env.UNKNOWN); assertEquals(Env.valueOf("dev"), Env.DEV); assertEquals(Env.valueOf("UAT"), Env.UAT); } @Test public void testEquals() { assertEquals(Env.DEV, Env.valueOf("dEv")); String name = "someEEEE"; Env.addEnvironment(name); assertFalse(Env.valueOf(name).equals(Env.DEV)); } @Test(expected = RuntimeException.class) public void testEqualsWithRuntimeException() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { // get private constructor Constructor<Env> envConstructor = Env.class.getDeclaredConstructor(String.class); // make private constructor accessible envConstructor.setAccessible(true); // make a fake Env Env fakeDevEnv = envConstructor.newInstance(Env.DEV.toString()); // compare, then a RuntimeException will invoke fakeDevEnv.equals(Env.DEV); } @Test public void testEqualWithoutException() { assertTrue(Env.DEV.equals(Env.DEV)); assertTrue(Env.DEV.equals(Env.valueOf("dEV"))); assertFalse(Env.PRO.equals(Env.DEV)); assertFalse(Env.DEV.equals(Env.valueOf("uaT"))); } @Test public void testToString() { assertEquals("DEV", Env.DEV.toString()); } @Test public void name() { assertEquals("DEV", Env.DEV.name()); } @Test public void getName() { String name = "getName"; Env.addEnvironment(name); assertEquals(name.trim().toUpperCase(), Env.valueOf(name).toString()); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.environment; import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import static org.junit.Assert.*; public class EnvTest { @Test public void exist() { assertFalse(Env.exists("xxxyyy234")); assertTrue(Env.exists("local")); assertTrue(Env.exists("dev")); } @Test public void addEnv() { String name = "someEEEE"; assertFalse(Env.exists(name)); Env.addEnvironment(name); assertTrue(Env.exists(name)); } @Test(expected = IllegalArgumentException.class) public void valueOf() { String name = "notexist"; assertFalse(Env.exists(name)); assertEquals(Env.valueOf(name), Env.UNKNOWN); assertEquals(Env.valueOf("dev"), Env.DEV); assertEquals(Env.valueOf("UAT"), Env.UAT); } @Test public void testEquals() { assertEquals(Env.DEV, Env.valueOf("dEv")); String name = "someEEEE"; Env.addEnvironment(name); assertFalse(Env.valueOf(name).equals(Env.DEV)); } @Test(expected = RuntimeException.class) public void testEqualsWithRuntimeException() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { // get private constructor Constructor<Env> envConstructor = Env.class.getDeclaredConstructor(String.class); // make private constructor accessible envConstructor.setAccessible(true); // make a fake Env Env fakeDevEnv = envConstructor.newInstance(Env.DEV.toString()); // compare, then a RuntimeException will invoke fakeDevEnv.equals(Env.DEV); } @Test public void testEqualWithoutException() { assertTrue(Env.DEV.equals(Env.DEV)); assertTrue(Env.DEV.equals(Env.valueOf("dEV"))); assertFalse(Env.PRO.equals(Env.DEV)); assertFalse(Env.DEV.equals(Env.valueOf("uaT"))); } @Test public void testToString() { assertEquals("DEV", Env.DEV.toString()); } @Test public void name() { assertEquals("DEV", Env.DEV.name()); } @Test public void getName() { String name = "getName"; Env.addEnvironment(name); assertEquals(name.trim().toUpperCase(), Env.valueOf(name).toString()); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-configservice/src/test/java/com/ctrip/framework/apollo/metaservice/service/KubernetesDiscoveryServiceTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.metaservice.service; import static org.junit.Assert.*; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.ctrip.framework.apollo.biz.config.BizConfig; import com.ctrip.framework.apollo.core.ServiceNameConsts; import com.ctrip.framework.apollo.core.dto.ServiceDTO; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class KubernetesDiscoveryServiceTest { private String configServiceConfigName = "apollo.config-service.url"; private String adminServiceConfigName = "apollo.admin-service.url"; @Mock private BizConfig bizConfig; private KubernetesDiscoveryService kubernetesDiscoveryService; @Before public void setUp() throws Exception { kubernetesDiscoveryService = new KubernetesDiscoveryService(bizConfig); } @Test public void testGetServiceInstancesWithInvalidServiceId() { String someInvalidServiceId = "someInvalidServiceId"; assertTrue(kubernetesDiscoveryService.getServiceInstances(someInvalidServiceId).isEmpty()); } @Test public void testGetServiceInstancesWithNullConfig() { when(bizConfig.getValue(configServiceConfigName)).thenReturn(null); assertTrue( kubernetesDiscoveryService.getServiceInstances(ServiceNameConsts.APOLLO_CONFIGSERVICE) .isEmpty()); verify(bizConfig, times(1)).getValue(configServiceConfigName); } @Test public void testGetConfigServiceInstances() { String someUrl = "http://some-host/some-path"; when(bizConfig.getValue(configServiceConfigName)).thenReturn(someUrl); List<ServiceDTO> serviceDTOList = kubernetesDiscoveryService .getServiceInstances(ServiceNameConsts.APOLLO_CONFIGSERVICE); assertEquals(1, serviceDTOList.size()); ServiceDTO serviceDTO = serviceDTOList.get(0); assertEquals(ServiceNameConsts.APOLLO_CONFIGSERVICE, serviceDTO.getAppName()); assertEquals(String.format("%s:%s", ServiceNameConsts.APOLLO_CONFIGSERVICE, someUrl), serviceDTO.getInstanceId()); assertEquals(someUrl, serviceDTO.getHomepageUrl()); } @Test public void testGetAdminServiceInstances() { String someUrl = "http://some-host/some-path"; String anotherUrl = "http://another-host/another-path"; when(bizConfig.getValue(adminServiceConfigName)) .thenReturn(String.format("%s,%s", someUrl, anotherUrl)); List<ServiceDTO> serviceDTOList = kubernetesDiscoveryService .getServiceInstances(ServiceNameConsts.APOLLO_ADMINSERVICE); assertEquals(2, serviceDTOList.size()); ServiceDTO serviceDTO = serviceDTOList.get(0); assertEquals(ServiceNameConsts.APOLLO_ADMINSERVICE, serviceDTO.getAppName()); assertEquals(String.format("%s:%s", ServiceNameConsts.APOLLO_ADMINSERVICE, someUrl), serviceDTO.getInstanceId()); assertEquals(someUrl, serviceDTO.getHomepageUrl()); ServiceDTO anotherServiceDTO = serviceDTOList.get(1); assertEquals(ServiceNameConsts.APOLLO_ADMINSERVICE, anotherServiceDTO.getAppName()); assertEquals(String.format("%s:%s", ServiceNameConsts.APOLLO_ADMINSERVICE, anotherUrl), anotherServiceDTO.getInstanceId()); assertEquals(anotherUrl, anotherServiceDTO.getHomepageUrl()); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.metaservice.service; import static org.junit.Assert.*; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.ctrip.framework.apollo.biz.config.BizConfig; import com.ctrip.framework.apollo.core.ServiceNameConsts; import com.ctrip.framework.apollo.core.dto.ServiceDTO; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class KubernetesDiscoveryServiceTest { private String configServiceConfigName = "apollo.config-service.url"; private String adminServiceConfigName = "apollo.admin-service.url"; @Mock private BizConfig bizConfig; private KubernetesDiscoveryService kubernetesDiscoveryService; @Before public void setUp() throws Exception { kubernetesDiscoveryService = new KubernetesDiscoveryService(bizConfig); } @Test public void testGetServiceInstancesWithInvalidServiceId() { String someInvalidServiceId = "someInvalidServiceId"; assertTrue(kubernetesDiscoveryService.getServiceInstances(someInvalidServiceId).isEmpty()); } @Test public void testGetServiceInstancesWithNullConfig() { when(bizConfig.getValue(configServiceConfigName)).thenReturn(null); assertTrue( kubernetesDiscoveryService.getServiceInstances(ServiceNameConsts.APOLLO_CONFIGSERVICE) .isEmpty()); verify(bizConfig, times(1)).getValue(configServiceConfigName); } @Test public void testGetConfigServiceInstances() { String someUrl = "http://some-host/some-path"; when(bizConfig.getValue(configServiceConfigName)).thenReturn(someUrl); List<ServiceDTO> serviceDTOList = kubernetesDiscoveryService .getServiceInstances(ServiceNameConsts.APOLLO_CONFIGSERVICE); assertEquals(1, serviceDTOList.size()); ServiceDTO serviceDTO = serviceDTOList.get(0); assertEquals(ServiceNameConsts.APOLLO_CONFIGSERVICE, serviceDTO.getAppName()); assertEquals(String.format("%s:%s", ServiceNameConsts.APOLLO_CONFIGSERVICE, someUrl), serviceDTO.getInstanceId()); assertEquals(someUrl, serviceDTO.getHomepageUrl()); } @Test public void testGetAdminServiceInstances() { String someUrl = "http://some-host/some-path"; String anotherUrl = "http://another-host/another-path"; when(bizConfig.getValue(adminServiceConfigName)) .thenReturn(String.format("%s,%s", someUrl, anotherUrl)); List<ServiceDTO> serviceDTOList = kubernetesDiscoveryService .getServiceInstances(ServiceNameConsts.APOLLO_ADMINSERVICE); assertEquals(2, serviceDTOList.size()); ServiceDTO serviceDTO = serviceDTOList.get(0); assertEquals(ServiceNameConsts.APOLLO_ADMINSERVICE, serviceDTO.getAppName()); assertEquals(String.format("%s:%s", ServiceNameConsts.APOLLO_ADMINSERVICE, someUrl), serviceDTO.getInstanceId()); assertEquals(someUrl, serviceDTO.getHomepageUrl()); ServiceDTO anotherServiceDTO = serviceDTOList.get(1); assertEquals(ServiceNameConsts.APOLLO_ADMINSERVICE, anotherServiceDTO.getAppName()); assertEquals(String.format("%s:%s", ServiceNameConsts.APOLLO_ADMINSERVICE, anotherUrl), anotherServiceDTO.getInstanceId()); assertEquals(anotherUrl, anotherServiceDTO.getHomepageUrl()); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-demo/src/main/java/com/ctrip/framework/apollo/demo/api/SimpleApolloConfigDemo.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.demo.api; import com.google.common.base.Charsets; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigChangeListener; import com.ctrip.framework.apollo.ConfigService; import com.ctrip.framework.apollo.model.ConfigChange; import com.ctrip.framework.apollo.model.ConfigChangeEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author Jason Song(song_s@ctrip.com) */ public class SimpleApolloConfigDemo { private static final Logger logger = LoggerFactory.getLogger(SimpleApolloConfigDemo.class); private String DEFAULT_VALUE = "undefined"; private Config config; public SimpleApolloConfigDemo() { ConfigChangeListener changeListener = new ConfigChangeListener() { @Override public void onChange(ConfigChangeEvent changeEvent) { logger.info("Changes for namespace {}", changeEvent.getNamespace()); for (String key : changeEvent.changedKeys()) { ConfigChange change = changeEvent.getChange(key); logger.info("Change - key: {}, oldValue: {}, newValue: {}, changeType: {}", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()); } } }; config = ConfigService.getAppConfig(); config.addChangeListener(changeListener); } private String getConfig(String key) { String result = config.getProperty(key, DEFAULT_VALUE); logger.info(String.format("Loading key : %s with value: %s", key, result)); return result; } public static void main(String[] args) throws IOException { SimpleApolloConfigDemo apolloConfigDemo = new SimpleApolloConfigDemo(); System.out.println( "Apollo Config Demo. Please input key to get the value. Input quit to exit."); while (true) { System.out.print("> "); String input = new BufferedReader(new InputStreamReader(System.in, Charsets.UTF_8)).readLine(); if (input == null || input.length() == 0) { continue; } input = input.trim(); if (input.equalsIgnoreCase("quit")) { System.exit(0); } apolloConfigDemo.getConfig(input); } } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.demo.api; import com.google.common.base.Charsets; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigChangeListener; import com.ctrip.framework.apollo.ConfigService; import com.ctrip.framework.apollo.model.ConfigChange; import com.ctrip.framework.apollo.model.ConfigChangeEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author Jason Song(song_s@ctrip.com) */ public class SimpleApolloConfigDemo { private static final Logger logger = LoggerFactory.getLogger(SimpleApolloConfigDemo.class); private String DEFAULT_VALUE = "undefined"; private Config config; public SimpleApolloConfigDemo() { ConfigChangeListener changeListener = new ConfigChangeListener() { @Override public void onChange(ConfigChangeEvent changeEvent) { logger.info("Changes for namespace {}", changeEvent.getNamespace()); for (String key : changeEvent.changedKeys()) { ConfigChange change = changeEvent.getChange(key); logger.info("Change - key: {}, oldValue: {}, newValue: {}, changeType: {}", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()); } } }; config = ConfigService.getAppConfig(); config.addChangeListener(changeListener); } private String getConfig(String key) { String result = config.getProperty(key, DEFAULT_VALUE); logger.info(String.format("Loading key : %s with value: %s", key, result)); return result; } public static void main(String[] args) throws IOException { SimpleApolloConfigDemo apolloConfigDemo = new SimpleApolloConfigDemo(); System.out.println( "Apollo Config Demo. Please input key to get the value. Input quit to exit."); while (true) { System.out.print("> "); String input = new BufferedReader(new InputStreamReader(System.in, Charsets.UTF_8)).readLine(); if (input == null || input.length() == 0) { continue; } input = input.trim(); if (input.equalsIgnoreCase("quit")) { System.exit(0); } apolloConfigDemo.getConfig(input); } } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-common/src/main/java/com/ctrip/framework/apollo/common/dto/InstanceConfigDTO.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.common.dto; import java.util.Date; /** * @author Jason Song(song_s@ctrip.com) */ public class InstanceConfigDTO { private ReleaseDTO release; private Date releaseDeliveryTime; private Date dataChangeLastModifiedTime; public ReleaseDTO getRelease() { return release; } public void setRelease(ReleaseDTO release) { this.release = release; } public Date getDataChangeLastModifiedTime() { return dataChangeLastModifiedTime; } public void setDataChangeLastModifiedTime(Date dataChangeLastModifiedTime) { this.dataChangeLastModifiedTime = dataChangeLastModifiedTime; } public Date getReleaseDeliveryTime() { return releaseDeliveryTime; } public void setReleaseDeliveryTime(Date releaseDeliveryTime) { this.releaseDeliveryTime = releaseDeliveryTime; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.common.dto; import java.util.Date; /** * @author Jason Song(song_s@ctrip.com) */ public class InstanceConfigDTO { private ReleaseDTO release; private Date releaseDeliveryTime; private Date dataChangeLastModifiedTime; public ReleaseDTO getRelease() { return release; } public void setRelease(ReleaseDTO release) { this.release = release; } public Date getDataChangeLastModifiedTime() { return dataChangeLastModifiedTime; } public void setDataChangeLastModifiedTime(Date dataChangeLastModifiedTime) { this.dataChangeLastModifiedTime = dataChangeLastModifiedTime; } public Date getReleaseDeliveryTime() { return releaseDeliveryTime; } public void setReleaseDeliveryTime(Date releaseDeliveryTime) { this.releaseDeliveryTime = releaseDeliveryTime; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-core/src/main/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProvider.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.core.internals; import com.ctrip.framework.apollo.core.enums.Env; import com.ctrip.framework.apollo.core.spi.MetaServerProvider; import com.ctrip.framework.apollo.core.utils.ResourceUtils; import com.google.common.base.Strings; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * For legacy meta server configuration use, i.e. apollo-env.properties */ public class LegacyMetaServerProvider implements MetaServerProvider { // make it as lowest as possible, yet not the lowest public static final int ORDER = MetaServerProvider.LOWEST_PRECEDENCE - 1; private static final Map<Env, String> domains = new HashMap<>(); public LegacyMetaServerProvider() { initialize(); } private void initialize() { Properties prop = new Properties(); prop = ResourceUtils.readConfigFile("apollo-env.properties", prop); domains.put(Env.LOCAL, getMetaServerAddress(prop, "local_meta", "local.meta")); domains.put(Env.DEV, getMetaServerAddress(prop, "dev_meta", "dev.meta")); domains.put(Env.FAT, getMetaServerAddress(prop, "fat_meta", "fat.meta")); domains.put(Env.UAT, getMetaServerAddress(prop, "uat_meta", "uat.meta")); domains.put(Env.LPT, getMetaServerAddress(prop, "lpt_meta", "lpt.meta")); domains.put(Env.PRO, getMetaServerAddress(prop, "pro_meta", "pro.meta")); } private String getMetaServerAddress(Properties prop, String sourceName, String propName) { // 1. Get from System Property. String metaAddress = System.getProperty(sourceName); if (Strings.isNullOrEmpty(metaAddress)) { // 2. Get from OS environment variable, which could not contain dot and is normally in UPPER case,like DEV_META. metaAddress = System.getenv(sourceName.toUpperCase()); } if (Strings.isNullOrEmpty(metaAddress)) { // 3. Get from properties file. metaAddress = prop.getProperty(propName); } return metaAddress; } @Override public String getMetaServerAddress(Env targetEnv) { String metaServerAddress = domains.get(targetEnv); return metaServerAddress == null ? null : metaServerAddress.trim(); } @Override public int getOrder() { return ORDER; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.core.internals; import com.ctrip.framework.apollo.core.enums.Env; import com.ctrip.framework.apollo.core.spi.MetaServerProvider; import com.ctrip.framework.apollo.core.utils.ResourceUtils; import com.google.common.base.Strings; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * For legacy meta server configuration use, i.e. apollo-env.properties */ public class LegacyMetaServerProvider implements MetaServerProvider { // make it as lowest as possible, yet not the lowest public static final int ORDER = MetaServerProvider.LOWEST_PRECEDENCE - 1; private static final Map<Env, String> domains = new HashMap<>(); public LegacyMetaServerProvider() { initialize(); } private void initialize() { Properties prop = new Properties(); prop = ResourceUtils.readConfigFile("apollo-env.properties", prop); domains.put(Env.LOCAL, getMetaServerAddress(prop, "local_meta", "local.meta")); domains.put(Env.DEV, getMetaServerAddress(prop, "dev_meta", "dev.meta")); domains.put(Env.FAT, getMetaServerAddress(prop, "fat_meta", "fat.meta")); domains.put(Env.UAT, getMetaServerAddress(prop, "uat_meta", "uat.meta")); domains.put(Env.LPT, getMetaServerAddress(prop, "lpt_meta", "lpt.meta")); domains.put(Env.PRO, getMetaServerAddress(prop, "pro_meta", "pro.meta")); } private String getMetaServerAddress(Properties prop, String sourceName, String propName) { // 1. Get from System Property. String metaAddress = System.getProperty(sourceName); if (Strings.isNullOrEmpty(metaAddress)) { // 2. Get from OS environment variable, which could not contain dot and is normally in UPPER case,like DEV_META. metaAddress = System.getenv(sourceName.toUpperCase()); } if (Strings.isNullOrEmpty(metaAddress)) { // 3. Get from properties file. metaAddress = prop.getProperty(propName); } return metaAddress; } @Override public String getMetaServerAddress(Env targetEnv) { String metaServerAddress = domains.get(targetEnv); return metaServerAddress == null ? null : metaServerAddress.trim(); } @Override public int getOrder() { return ORDER; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-biz/src/test/java/com/ctrip/framework/apollo/biz/repository/AppNamespaceRepositoryTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.repository; import com.ctrip.framework.apollo.biz.AbstractIntegrationTest; import com.ctrip.framework.apollo.common.entity.AppNamespace; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class AppNamespaceRepositoryTest extends AbstractIntegrationTest{ @Autowired private AppNamespaceRepository repository; @Test public void testFindByNameAndIsPublicTrue() throws Exception { AppNamespace appNamespace = repository.findByNameAndIsPublicTrue("fx.apollo.config"); assertEquals("100003171", appNamespace.getAppId()); } @Test public void testFindByNameAndNoPublicNamespace() throws Exception { AppNamespace appNamespace = repository.findByNameAndIsPublicTrue("application"); assertNull(appNamespace); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.repository; import com.ctrip.framework.apollo.biz.AbstractIntegrationTest; import com.ctrip.framework.apollo.common.entity.AppNamespace; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class AppNamespaceRepositoryTest extends AbstractIntegrationTest{ @Autowired private AppNamespaceRepository repository; @Test public void testFindByNameAndIsPublicTrue() throws Exception { AppNamespace appNamespace = repository.findByNameAndIsPublicTrue("fx.apollo.config"); assertEquals("100003171", appNamespace.getAppId()); } @Test public void testFindByNameAndNoPublicNamespace() throws Exception { AppNamespace appNamespace = repository.findByNameAndIsPublicTrue("application"); assertNull(appNamespace); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./scripts/apollo-on-kubernetes/db/config-db-test-alpha/apolloconfigdb.sql
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Create Database # ------------------------------------------------------------ CREATE DATABASE IF NOT EXISTS TestAlphaApolloConfigDB DEFAULT CHARACTER SET = utf8mb4; Use TestAlphaApolloConfigDB; # Dump of table app # ------------------------------------------------------------ DROP TABLE IF EXISTS `App`; CREATE TABLE `App` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Name` (`Name`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用表'; # Dump of table appnamespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `AppNamespace`; CREATE TABLE `AppNamespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT 'namespace名字,注意,需要全局唯一', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'app id', `Format` varchar(32) NOT NULL DEFAULT 'properties' COMMENT 'namespace的format类型', `IsPublic` bit(1) NOT NULL DEFAULT b'0' COMMENT 'namespace是否为公共', `Comment` varchar(64) NOT NULL DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId` (`AppId`), KEY `Name_AppId` (`Name`,`AppId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用namespace定义'; # Dump of table audit # ------------------------------------------------------------ DROP TABLE IF EXISTS `Audit`; CREATE TABLE `Audit` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `EntityName` varchar(50) NOT NULL DEFAULT 'default' COMMENT '表名', `EntityId` int(10) unsigned DEFAULT NULL COMMENT '记录ID', `OpName` varchar(50) NOT NULL DEFAULT 'default' COMMENT '操作类型', `Comment` varchar(500) DEFAULT NULL COMMENT '备注', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='日志审计表'; # Dump of table cluster # ------------------------------------------------------------ DROP TABLE IF EXISTS `Cluster`; CREATE TABLE `Cluster` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT '集群名字', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'App id', `ParentClusterId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '父cluster', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId_Name` (`AppId`,`Name`), KEY `IX_ParentClusterId` (`ParentClusterId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='集群'; # Dump of table commit # ------------------------------------------------------------ DROP TABLE IF EXISTS `Commit`; CREATE TABLE `Commit` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `ChangeSets` longtext NOT NULL COMMENT '修改变更集', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `NamespaceName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'namespaceName', `Comment` varchar(500) DEFAULT NULL COMMENT '备注', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `AppId` (`AppId`(191)), KEY `ClusterName` (`ClusterName`(191)), KEY `NamespaceName` (`NamespaceName`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='commit 历史表'; # Dump of table grayreleaserule # ------------------------------------------------------------ DROP TABLE IF EXISTS `GrayReleaseRule`; CREATE TABLE `GrayReleaseRule` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Cluster Name', `NamespaceName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Namespace Name', `BranchName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'branch name', `Rules` varchar(16000) DEFAULT '[]' COMMENT '灰度规则', `ReleaseId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '灰度对应的release', `BranchStatus` tinyint(2) DEFAULT '1' COMMENT '灰度分支状态: 0:删除分支,1:正在使用的规则 2:全量发布', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Namespace` (`AppId`,`ClusterName`,`NamespaceName`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='灰度规则表'; # Dump of table instance # ------------------------------------------------------------ DROP TABLE IF EXISTS `Instance`; CREATE TABLE `Instance` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `DataCenter` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'Data Center Name', `Ip` varchar(32) NOT NULL DEFAULT '' COMMENT 'instance ip', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_UNIQUE_KEY` (`AppId`,`ClusterName`,`Ip`,`DataCenter`), KEY `IX_IP` (`Ip`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='使用配置的应用实例'; # Dump of table instanceconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `InstanceConfig`; CREATE TABLE `InstanceConfig` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `InstanceId` int(11) unsigned DEFAULT NULL COMMENT 'Instance Id', `ConfigAppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'Config App Id', `ConfigClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Config Cluster Name', `ConfigNamespaceName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Config Namespace Name', `ReleaseKey` varchar(64) NOT NULL DEFAULT '' COMMENT '发布的Key', `ReleaseDeliveryTime` timestamp NULL DEFAULT NULL COMMENT '配置获取时间', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_UNIQUE_KEY` (`InstanceId`,`ConfigAppId`,`ConfigNamespaceName`), KEY `IX_ReleaseKey` (`ReleaseKey`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Valid_Namespace` (`ConfigAppId`,`ConfigClusterName`,`ConfigNamespaceName`,`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用实例的配置信息'; # Dump of table item # ------------------------------------------------------------ DROP TABLE IF EXISTS `Item`; CREATE TABLE `Item` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `NamespaceId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '集群NamespaceId', `Key` varchar(128) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Value` longtext NOT NULL COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `LineNum` int(10) unsigned DEFAULT '0' COMMENT '行号', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_GroupId` (`NamespaceId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置项目'; # Dump of table namespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `Namespace`; CREATE TABLE `Namespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'Cluster Name', `NamespaceName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'Namespace Name', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId_ClusterName_NamespaceName` (`AppId`(191),`ClusterName`(191),`NamespaceName`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_NamespaceName` (`NamespaceName`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='命名空间'; # Dump of table namespacelock # ------------------------------------------------------------ DROP TABLE IF EXISTS `NamespaceLock`; CREATE TABLE `NamespaceLock` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id', `NamespaceId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '集群NamespaceId', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', `IsDeleted` bit(1) DEFAULT b'0' COMMENT '软删除', PRIMARY KEY (`Id`), UNIQUE KEY `IX_NamespaceId` (`NamespaceId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='namespace的编辑锁'; # Dump of table release # ------------------------------------------------------------ DROP TABLE IF EXISTS `Release`; CREATE TABLE `Release` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `ReleaseKey` varchar(64) NOT NULL DEFAULT '' COMMENT '发布的Key', `Name` varchar(64) NOT NULL DEFAULT 'default' COMMENT '发布名字', `Comment` varchar(256) DEFAULT NULL COMMENT '发布说明', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `NamespaceName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'namespaceName', `Configurations` longtext NOT NULL COMMENT '发布配置', `IsAbandoned` bit(1) NOT NULL DEFAULT b'0' COMMENT '是否废弃', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId_ClusterName_GroupName` (`AppId`(191),`ClusterName`(191),`NamespaceName`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_ReleaseKey` (`ReleaseKey`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发布'; # Dump of table releasehistory # ------------------------------------------------------------ DROP TABLE IF EXISTS `ReleaseHistory`; CREATE TABLE `ReleaseHistory` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `NamespaceName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'namespaceName', `BranchName` varchar(32) NOT NULL DEFAULT 'default' COMMENT '发布分支名', `ReleaseId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '关联的Release Id', `PreviousReleaseId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '前一次发布的ReleaseId', `Operation` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '发布类型,0: 普通发布,1: 回滚,2: 灰度发布,3: 灰度规则更新,4: 灰度合并回主分支发布,5: 主分支发布灰度自动发布,6: 主分支回滚灰度自动发布,7: 放弃灰度', `OperationContext` longtext NOT NULL COMMENT '发布上下文信息', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Namespace` (`AppId`,`ClusterName`,`NamespaceName`,`BranchName`), KEY `IX_ReleaseId` (`ReleaseId`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发布历史'; # Dump of table releasemessage # ------------------------------------------------------------ DROP TABLE IF EXISTS `ReleaseMessage`; CREATE TABLE `ReleaseMessage` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Message` varchar(1024) NOT NULL DEFAULT '' COMMENT '发布的消息内容', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Message` (`Message`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发布消息'; # Dump of table serverconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `ServerConfig`; CREATE TABLE `ServerConfig` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Key` varchar(64) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Cluster` varchar(32) NOT NULL DEFAULT 'default' COMMENT '配置对应的集群,default为不针对特定的集群', `Value` varchar(2048) NOT NULL DEFAULT 'default' COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Key` (`Key`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置服务自身配置'; # Dump of table accesskey # ------------------------------------------------------------ DROP TABLE IF EXISTS `AccessKey`; CREATE TABLE `AccessKey` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Secret` varchar(128) NOT NULL DEFAULT '' COMMENT 'Secret', `IsEnabled` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: enabled, 0: disabled', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='访问密钥'; # Config # ------------------------------------------------------------ INSERT INTO `ServerConfig` (`Key`, `Cluster`, `Value`, `Comment`) VALUES ('eureka.service.url', 'default', 'http://statefulset-apollo-config-server-test-alpha-0.service-apollo-meta-server-test-alpha:8080/eureka/,http://statefulset-apollo-config-server-test-alpha-1.service-apollo-meta-server-test-alpha:8080/eureka/,http://statefulset-apollo-config-server-test-alpha-2.service-apollo-meta-server-test-alpha:8080/eureka/', 'Eureka服务Url,多个service以英文逗号分隔'), ('namespace.lock.switch', 'default', 'false', '一次发布只能有一个人修改开关'), ('item.key.length.limit', 'default', '128', 'item key 最大长度限制'), ('item.value.length.limit', 'default', '20000', 'item value最大长度限制'), ('config-service.cache.enabled', 'default', 'false', 'ConfigService是否开启缓存,开启后能提高性能,但是会增大内存消耗!'); /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Create Database # ------------------------------------------------------------ CREATE DATABASE IF NOT EXISTS TestAlphaApolloConfigDB DEFAULT CHARACTER SET = utf8mb4; Use TestAlphaApolloConfigDB; # Dump of table app # ------------------------------------------------------------ DROP TABLE IF EXISTS `App`; CREATE TABLE `App` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Name` varchar(500) NOT NULL DEFAULT 'default' COMMENT '应用名', `OrgId` varchar(32) NOT NULL DEFAULT 'default' COMMENT '部门Id', `OrgName` varchar(64) NOT NULL DEFAULT 'default' COMMENT '部门名字', `OwnerName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerName', `OwnerEmail` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ownerEmail', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Name` (`Name`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用表'; # Dump of table appnamespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `AppNamespace`; CREATE TABLE `AppNamespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT 'namespace名字,注意,需要全局唯一', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'app id', `Format` varchar(32) NOT NULL DEFAULT 'properties' COMMENT 'namespace的format类型', `IsPublic` bit(1) NOT NULL DEFAULT b'0' COMMENT 'namespace是否为公共', `Comment` varchar(64) NOT NULL DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId` (`AppId`), KEY `Name_AppId` (`Name`,`AppId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用namespace定义'; # Dump of table audit # ------------------------------------------------------------ DROP TABLE IF EXISTS `Audit`; CREATE TABLE `Audit` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `EntityName` varchar(50) NOT NULL DEFAULT 'default' COMMENT '表名', `EntityId` int(10) unsigned DEFAULT NULL COMMENT '记录ID', `OpName` varchar(50) NOT NULL DEFAULT 'default' COMMENT '操作类型', `Comment` varchar(500) DEFAULT NULL COMMENT '备注', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='日志审计表'; # Dump of table cluster # ------------------------------------------------------------ DROP TABLE IF EXISTS `Cluster`; CREATE TABLE `Cluster` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Name` varchar(32) NOT NULL DEFAULT '' COMMENT '集群名字', `AppId` varchar(64) NOT NULL DEFAULT '' COMMENT 'App id', `ParentClusterId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '父cluster', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_AppId_Name` (`AppId`,`Name`), KEY `IX_ParentClusterId` (`ParentClusterId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='集群'; # Dump of table commit # ------------------------------------------------------------ DROP TABLE IF EXISTS `Commit`; CREATE TABLE `Commit` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `ChangeSets` longtext NOT NULL COMMENT '修改变更集', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `NamespaceName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'namespaceName', `Comment` varchar(500) DEFAULT NULL COMMENT '备注', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `AppId` (`AppId`(191)), KEY `ClusterName` (`ClusterName`(191)), KEY `NamespaceName` (`NamespaceName`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='commit 历史表'; # Dump of table grayreleaserule # ------------------------------------------------------------ DROP TABLE IF EXISTS `GrayReleaseRule`; CREATE TABLE `GrayReleaseRule` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `AppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Cluster Name', `NamespaceName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Namespace Name', `BranchName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'branch name', `Rules` varchar(16000) DEFAULT '[]' COMMENT '灰度规则', `ReleaseId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '灰度对应的release', `BranchStatus` tinyint(2) DEFAULT '1' COMMENT '灰度分支状态: 0:删除分支,1:正在使用的规则 2:全量发布', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Namespace` (`AppId`,`ClusterName`,`NamespaceName`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='灰度规则表'; # Dump of table instance # ------------------------------------------------------------ DROP TABLE IF EXISTS `Instance`; CREATE TABLE `Instance` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `DataCenter` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'Data Center Name', `Ip` varchar(32) NOT NULL DEFAULT '' COMMENT 'instance ip', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_UNIQUE_KEY` (`AppId`,`ClusterName`,`Ip`,`DataCenter`), KEY `IX_IP` (`Ip`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='使用配置的应用实例'; # Dump of table instanceconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `InstanceConfig`; CREATE TABLE `InstanceConfig` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `InstanceId` int(11) unsigned DEFAULT NULL COMMENT 'Instance Id', `ConfigAppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'Config App Id', `ConfigClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Config Cluster Name', `ConfigNamespaceName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'Config Namespace Name', `ReleaseKey` varchar(64) NOT NULL DEFAULT '' COMMENT '发布的Key', `ReleaseDeliveryTime` timestamp NULL DEFAULT NULL COMMENT '配置获取时间', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), UNIQUE KEY `IX_UNIQUE_KEY` (`InstanceId`,`ConfigAppId`,`ConfigNamespaceName`), KEY `IX_ReleaseKey` (`ReleaseKey`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Valid_Namespace` (`ConfigAppId`,`ConfigClusterName`,`ConfigNamespaceName`,`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='应用实例的配置信息'; # Dump of table item # ------------------------------------------------------------ DROP TABLE IF EXISTS `Item`; CREATE TABLE `Item` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `NamespaceId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '集群NamespaceId', `Key` varchar(128) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Value` longtext NOT NULL COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `LineNum` int(10) unsigned DEFAULT '0' COMMENT '行号', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_GroupId` (`NamespaceId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置项目'; # Dump of table namespace # ------------------------------------------------------------ DROP TABLE IF EXISTS `Namespace`; CREATE TABLE `Namespace` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'Cluster Name', `NamespaceName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'Namespace Name', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId_ClusterName_NamespaceName` (`AppId`(191),`ClusterName`(191),`NamespaceName`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_NamespaceName` (`NamespaceName`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='命名空间'; # Dump of table namespacelock # ------------------------------------------------------------ DROP TABLE IF EXISTS `NamespaceLock`; CREATE TABLE `NamespaceLock` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增id', `NamespaceId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '集群NamespaceId', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', `IsDeleted` bit(1) DEFAULT b'0' COMMENT '软删除', PRIMARY KEY (`Id`), UNIQUE KEY `IX_NamespaceId` (`NamespaceId`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='namespace的编辑锁'; # Dump of table release # ------------------------------------------------------------ DROP TABLE IF EXISTS `Release`; CREATE TABLE `Release` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `ReleaseKey` varchar(64) NOT NULL DEFAULT '' COMMENT '发布的Key', `Name` varchar(64) NOT NULL DEFAULT 'default' COMMENT '发布名字', `Comment` varchar(256) DEFAULT NULL COMMENT '发布说明', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `NamespaceName` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'namespaceName', `Configurations` longtext NOT NULL COMMENT '发布配置', `IsAbandoned` bit(1) NOT NULL DEFAULT b'0' COMMENT '是否废弃', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId_ClusterName_GroupName` (`AppId`(191),`ClusterName`(191),`NamespaceName`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_ReleaseKey` (`ReleaseKey`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发布'; # Dump of table releasehistory # ------------------------------------------------------------ DROP TABLE IF EXISTS `ReleaseHistory`; CREATE TABLE `ReleaseHistory` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `AppId` varchar(64) NOT NULL DEFAULT 'default' COMMENT 'AppID', `ClusterName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'ClusterName', `NamespaceName` varchar(32) NOT NULL DEFAULT 'default' COMMENT 'namespaceName', `BranchName` varchar(32) NOT NULL DEFAULT 'default' COMMENT '发布分支名', `ReleaseId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '关联的Release Id', `PreviousReleaseId` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '前一次发布的ReleaseId', `Operation` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '发布类型,0: 普通发布,1: 回滚,2: 灰度发布,3: 灰度规则更新,4: 灰度合并回主分支发布,5: 主分支发布灰度自动发布,6: 主分支回滚灰度自动发布,7: 放弃灰度', `OperationContext` longtext NOT NULL COMMENT '发布上下文信息', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Namespace` (`AppId`,`ClusterName`,`NamespaceName`,`BranchName`), KEY `IX_ReleaseId` (`ReleaseId`), KEY `IX_DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发布历史'; # Dump of table releasemessage # ------------------------------------------------------------ DROP TABLE IF EXISTS `ReleaseMessage`; CREATE TABLE `ReleaseMessage` ( `Id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `Message` varchar(1024) NOT NULL DEFAULT '' COMMENT '发布的消息内容', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `DataChange_LastTime` (`DataChange_LastTime`), KEY `IX_Message` (`Message`(191)) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发布消息'; # Dump of table serverconfig # ------------------------------------------------------------ DROP TABLE IF EXISTS `ServerConfig`; CREATE TABLE `ServerConfig` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增Id', `Key` varchar(64) NOT NULL DEFAULT 'default' COMMENT '配置项Key', `Cluster` varchar(32) NOT NULL DEFAULT 'default' COMMENT '配置对应的集群,default为不针对特定的集群', `Value` varchar(2048) NOT NULL DEFAULT 'default' COMMENT '配置项值', `Comment` varchar(1024) DEFAULT '' COMMENT '注释', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `IX_Key` (`Key`), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置服务自身配置'; # Dump of table accesskey # ------------------------------------------------------------ DROP TABLE IF EXISTS `AccessKey`; CREATE TABLE `AccessKey` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `AppId` varchar(500) NOT NULL DEFAULT 'default' COMMENT 'AppID', `Secret` varchar(128) NOT NULL DEFAULT '' COMMENT 'Secret', `IsEnabled` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: enabled, 0: disabled', `IsDeleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '1: deleted, 0: normal', `DataChange_CreatedBy` varchar(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀', `DataChange_CreatedTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `DataChange_LastModifiedBy` varchar(64) DEFAULT '' COMMENT '最后修改人邮箱前缀', `DataChange_LastTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后修改时间', PRIMARY KEY (`Id`), KEY `AppId` (`AppId`(191)), KEY `DataChange_LastTime` (`DataChange_LastTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='访问密钥'; # Config # ------------------------------------------------------------ INSERT INTO `ServerConfig` (`Key`, `Cluster`, `Value`, `Comment`) VALUES ('eureka.service.url', 'default', 'http://statefulset-apollo-config-server-test-alpha-0.service-apollo-meta-server-test-alpha:8080/eureka/,http://statefulset-apollo-config-server-test-alpha-1.service-apollo-meta-server-test-alpha:8080/eureka/,http://statefulset-apollo-config-server-test-alpha-2.service-apollo-meta-server-test-alpha:8080/eureka/', 'Eureka服务Url,多个service以英文逗号分隔'), ('namespace.lock.switch', 'default', 'false', '一次发布只能有一个人修改开关'), ('item.key.length.limit', 'default', '128', 'item key 最大长度限制'), ('item.value.length.limit', 'default', '20000', 'item value最大长度限制'), ('config-service.cache.enabled', 'default', 'false', 'ConfigService是否开启缓存,开启后能提高性能,但是会增大内存消耗!'); /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ConfigRegistry.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.spi; /** * The manually config registry, use with caution! * * @author Jason Song(song_s@ctrip.com) */ public interface ConfigRegistry { /** * Register the config factory for the namespace specified. * * @param namespace the namespace * @param factory the factory for this namespace */ void register(String namespace, ConfigFactory factory); /** * Get the registered config factory for the namespace. * * @param namespace the namespace * @return the factory registered for this namespace */ ConfigFactory getFactory(String namespace); }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.spi; /** * The manually config registry, use with caution! * * @author Jason Song(song_s@ctrip.com) */ public interface ConfigRegistry { /** * Register the config factory for the namespace specified. * * @param namespace the namespace * @param factory the factory for this namespace */ void register(String namespace, ConfigFactory factory); /** * Get the registered config factory for the namespace. * * @param namespace the namespace * @return the factory registered for this namespace */ ConfigFactory getFactory(String namespace); }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/extension/initialize/ApolloClientPropertiesFactoryTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.config.data.extension.initialize; import com.ctrip.framework.apollo.config.data.extension.enums.ApolloClientMessagingType; import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientProperties; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.source.MapConfigurationPropertySource; /** * @author vdisk <vdisk@foxmail.com> */ public class ApolloClientPropertiesFactoryTest { @Test public void testCreateApolloClientProperties() throws IOException { Map<String, String> map = new LinkedHashMap<>(); map.put("apollo.client.extension.enabled", "true"); map.put("apollo.client.extension.messaging-type", "long_polling"); MapConfigurationPropertySource propertySource = new MapConfigurationPropertySource(map); Binder binder = new Binder(propertySource); ApolloClientPropertiesFactory factory = new ApolloClientPropertiesFactory(); ApolloClientProperties apolloClientProperties = factory .createApolloClientProperties(binder, null); Assert.assertEquals(apolloClientProperties.getExtension().getEnabled(), true); Assert.assertEquals(apolloClientProperties.getExtension().getMessagingType(), ApolloClientMessagingType.LONG_POLLING); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.config.data.extension.initialize; import com.ctrip.framework.apollo.config.data.extension.enums.ApolloClientMessagingType; import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientProperties; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.source.MapConfigurationPropertySource; /** * @author vdisk <vdisk@foxmail.com> */ public class ApolloClientPropertiesFactoryTest { @Test public void testCreateApolloClientProperties() throws IOException { Map<String, String> map = new LinkedHashMap<>(); map.put("apollo.client.extension.enabled", "true"); map.put("apollo.client.extension.messaging-type", "long_polling"); MapConfigurationPropertySource propertySource = new MapConfigurationPropertySource(map); Binder binder = new Binder(propertySource); ApolloClientPropertiesFactory factory = new ApolloClientPropertiesFactory(); ApolloClientProperties apolloClientProperties = factory .createApolloClientProperties(binder, null); Assert.assertEquals(apolloClientProperties.getExtension().getEnabled(), true); Assert.assertEquals(apolloClientProperties.getExtension().getMessagingType(), ApolloClientMessagingType.LONG_POLLING); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-core/src/main/java/com/ctrip/framework/foundation/internals/DefaultProviderManager.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.foundation.internals; import java.util.LinkedHashMap; import java.util.Map; import com.ctrip.framework.foundation.internals.provider.DefaultApplicationProvider; import com.ctrip.framework.foundation.internals.provider.DefaultNetworkProvider; import com.ctrip.framework.foundation.internals.provider.DefaultServerProvider; import com.ctrip.framework.foundation.spi.ProviderManager; import com.ctrip.framework.foundation.spi.provider.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DefaultProviderManager implements ProviderManager { private static final Logger logger = LoggerFactory.getLogger(DefaultProviderManager.class); private Map<Class<? extends Provider>, Provider> m_providers = new LinkedHashMap<>(); public DefaultProviderManager() { // Load per-application configuration, like app id, from classpath://META-INF/app.properties Provider applicationProvider = new DefaultApplicationProvider(); applicationProvider.initialize(); register(applicationProvider); // Load network parameters Provider networkProvider = new DefaultNetworkProvider(); networkProvider.initialize(); register(networkProvider); // Load environment (fat, fws, uat, prod ...) and dc, from /opt/settings/server.properties, JVM property and/or OS // environment variables. Provider serverProvider = new DefaultServerProvider(); serverProvider.initialize(); register(serverProvider); } public synchronized void register(Provider provider) { m_providers.put(provider.getType(), provider); } @Override @SuppressWarnings("unchecked") public <T extends Provider> T provider(Class<T> clazz) { Provider provider = m_providers.get(clazz); if (provider != null) { return (T) provider; } logger.error("No provider [{}] found in DefaultProviderManager, please make sure it is registered in DefaultProviderManager ", clazz.getName()); return (T) NullProviderManager.provider; } @Override public String getProperty(String name, String defaultValue) { for (Provider provider : m_providers.values()) { String value = provider.getProperty(name, null); if (value != null) { return value; } } return defaultValue; } @Override public String toString() { StringBuilder sb = new StringBuilder(512); if (null != m_providers) { for (Map.Entry<Class<? extends Provider>, Provider> entry : m_providers.entrySet()) { sb.append(entry.getValue()).append("\n"); } } sb.append("(DefaultProviderManager)").append("\n"); return sb.toString(); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.foundation.internals; import java.util.LinkedHashMap; import java.util.Map; import com.ctrip.framework.foundation.internals.provider.DefaultApplicationProvider; import com.ctrip.framework.foundation.internals.provider.DefaultNetworkProvider; import com.ctrip.framework.foundation.internals.provider.DefaultServerProvider; import com.ctrip.framework.foundation.spi.ProviderManager; import com.ctrip.framework.foundation.spi.provider.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DefaultProviderManager implements ProviderManager { private static final Logger logger = LoggerFactory.getLogger(DefaultProviderManager.class); private Map<Class<? extends Provider>, Provider> m_providers = new LinkedHashMap<>(); public DefaultProviderManager() { // Load per-application configuration, like app id, from classpath://META-INF/app.properties Provider applicationProvider = new DefaultApplicationProvider(); applicationProvider.initialize(); register(applicationProvider); // Load network parameters Provider networkProvider = new DefaultNetworkProvider(); networkProvider.initialize(); register(networkProvider); // Load environment (fat, fws, uat, prod ...) and dc, from /opt/settings/server.properties, JVM property and/or OS // environment variables. Provider serverProvider = new DefaultServerProvider(); serverProvider.initialize(); register(serverProvider); } public synchronized void register(Provider provider) { m_providers.put(provider.getType(), provider); } @Override @SuppressWarnings("unchecked") public <T extends Provider> T provider(Class<T> clazz) { Provider provider = m_providers.get(clazz); if (provider != null) { return (T) provider; } logger.error("No provider [{}] found in DefaultProviderManager, please make sure it is registered in DefaultProviderManager ", clazz.getName()); return (T) NullProviderManager.provider; } @Override public String getProperty(String name, String defaultValue) { for (Provider provider : m_providers.values()) { String value = provider.getProperty(name, null); if (value != null) { return value; } } return defaultValue; } @Override public String toString() { StringBuilder sb = new StringBuilder(512); if (null != m_providers) { for (Map.Entry<Class<? extends Provider>, Provider> entry : m_providers.entrySet()) { sb.append(entry.getValue()).append("\n"); } } sb.append("(DefaultProviderManager)").append("\n"); return sb.toString(); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-client/src/main/java/com/ctrip/framework/apollo/util/OrderedProperties.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.util; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; /** * An OrderedProperties instance will keep appearance order in config file. * * <strong> * Warnings: 1. It should be noticed that stream APIs or JDk1.8 APIs( listed in * https://github.com/ctripcorp/apollo/pull/2861) are not implemented here. 2. {@link Properties} * implementation are different between JDK1.8 and later JDKs. At least, {@link Properties} have an * individual implementation in JDK10. Hence, there should be an individual putAll method here. * </strong> * * @author songdragon@zts.io */ public class OrderedProperties extends Properties { private static final long serialVersionUID = -1741073539526213291L; private final Set<String> propertyNames; public OrderedProperties() { propertyNames = Collections.synchronizedSet(new LinkedHashSet<String>()); } @Override public synchronized Object put(Object key, Object value) { addPropertyName(key); return super.put(key, value); } private void addPropertyName(Object key) { if (key instanceof String) { propertyNames.add((String) key); } } @Override public Set<String> stringPropertyNames() { return propertyNames; } @Override public Enumeration<?> propertyNames() { return Collections.enumeration(propertyNames); } @Override public synchronized Enumeration<Object> keys() { return new Enumeration<Object>() { private final Iterator<String> i = propertyNames.iterator(); @Override public boolean hasMoreElements() { return i.hasNext(); } @Override public Object nextElement() { return i.next(); } }; } @Override public Set<Object> keySet() { return new LinkedHashSet<Object>(propertyNames); } @Override public Set<Entry<Object, Object>> entrySet() { Set<Entry<Object, Object>> original = super.entrySet(); LinkedHashMap<Object, Entry<Object, Object>> entryMap = new LinkedHashMap<>(); for (String propertyName : propertyNames) { entryMap.put(propertyName, null); } for (Entry<Object, Object> entry : original) { entryMap.put(entry.getKey(), entry); } return new LinkedHashSet<>(entryMap.values()); } @Override public synchronized void putAll(Map<?, ?> t) { super.putAll(t); for (Object name : t.keySet()) { addPropertyName(name); } } @Override public synchronized void clear() { super.clear(); this.propertyNames.clear(); } @Override public synchronized Object remove(Object key) { if (key instanceof String) { this.propertyNames.remove(key); } return super.remove(key); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.util; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; /** * An OrderedProperties instance will keep appearance order in config file. * * <strong> * Warnings: 1. It should be noticed that stream APIs or JDk1.8 APIs( listed in * https://github.com/ctripcorp/apollo/pull/2861) are not implemented here. 2. {@link Properties} * implementation are different between JDK1.8 and later JDKs. At least, {@link Properties} have an * individual implementation in JDK10. Hence, there should be an individual putAll method here. * </strong> * * @author songdragon@zts.io */ public class OrderedProperties extends Properties { private static final long serialVersionUID = -1741073539526213291L; private final Set<String> propertyNames; public OrderedProperties() { propertyNames = Collections.synchronizedSet(new LinkedHashSet<String>()); } @Override public synchronized Object put(Object key, Object value) { addPropertyName(key); return super.put(key, value); } private void addPropertyName(Object key) { if (key instanceof String) { propertyNames.add((String) key); } } @Override public Set<String> stringPropertyNames() { return propertyNames; } @Override public Enumeration<?> propertyNames() { return Collections.enumeration(propertyNames); } @Override public synchronized Enumeration<Object> keys() { return new Enumeration<Object>() { private final Iterator<String> i = propertyNames.iterator(); @Override public boolean hasMoreElements() { return i.hasNext(); } @Override public Object nextElement() { return i.next(); } }; } @Override public Set<Object> keySet() { return new LinkedHashSet<Object>(propertyNames); } @Override public Set<Entry<Object, Object>> entrySet() { Set<Entry<Object, Object>> original = super.entrySet(); LinkedHashMap<Object, Entry<Object, Object>> entryMap = new LinkedHashMap<>(); for (String propertyName : propertyNames) { entryMap.put(propertyName, null); } for (Entry<Object, Object> entry : original) { entryMap.put(entry.getKey(), entry); } return new LinkedHashSet<>(entryMap.values()); } @Override public synchronized void putAll(Map<?, ?> t) { super.putAll(t); for (Object name : t.keySet()) { addPropertyName(name); } } @Override public synchronized void clear() { super.clear(); this.propertyNames.clear(); } @Override public synchronized Object remove(Object key) { if (key instanceof String) { this.propertyNames.remove(key); } return super.remove(key); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-biz/src/test/java/com/ctrip/framework/apollo/biz/MockBeanFactory.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz; import com.ctrip.framework.apollo.biz.entity.Item; import com.ctrip.framework.apollo.biz.entity.Namespace; import com.ctrip.framework.apollo.biz.entity.Release; import com.ctrip.framework.apollo.biz.entity.ServerConfig; import com.ctrip.framework.apollo.common.entity.AppNamespace; public class MockBeanFactory { public static Namespace mockNamespace(String appId, String clusterName, String namespaceName) { Namespace instance = new Namespace(); instance.setAppId(appId); instance.setClusterName(clusterName); instance.setNamespaceName(namespaceName); return instance; } public static AppNamespace mockAppNamespace(String appId, String name, boolean isPublic) { AppNamespace instance = new AppNamespace(); instance.setAppId(appId); instance.setName(name); instance.setPublic(isPublic); return instance; } public static ServerConfig mockServerConfig(String key, String value, String cluster) { ServerConfig instance = new ServerConfig(); instance.setKey(key); instance.setValue(value); instance.setCluster(cluster); return instance; } public static Release mockRelease(long releaseId, String releaseKey, String appId, String clusterName, String groupName, String configurations) { Release instance = new Release(); instance.setId(releaseId); instance.setReleaseKey(releaseKey); instance.setAppId(appId); instance.setClusterName(clusterName); instance.setNamespaceName(groupName); instance.setConfigurations(configurations); return instance; } public static Item mockItem(long id, long namespaceId, String itemKey, String itemValue, int lineNum) { Item item = new Item(); item.setId(id); item.setKey(itemKey); item.setValue(itemValue); item.setLineNum(lineNum); item.setNamespaceId(namespaceId); return item; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz; import com.ctrip.framework.apollo.biz.entity.Item; import com.ctrip.framework.apollo.biz.entity.Namespace; import com.ctrip.framework.apollo.biz.entity.Release; import com.ctrip.framework.apollo.biz.entity.ServerConfig; import com.ctrip.framework.apollo.common.entity.AppNamespace; public class MockBeanFactory { public static Namespace mockNamespace(String appId, String clusterName, String namespaceName) { Namespace instance = new Namespace(); instance.setAppId(appId); instance.setClusterName(clusterName); instance.setNamespaceName(namespaceName); return instance; } public static AppNamespace mockAppNamespace(String appId, String name, boolean isPublic) { AppNamespace instance = new AppNamespace(); instance.setAppId(appId); instance.setName(name); instance.setPublic(isPublic); return instance; } public static ServerConfig mockServerConfig(String key, String value, String cluster) { ServerConfig instance = new ServerConfig(); instance.setKey(key); instance.setValue(value); instance.setCluster(cluster); return instance; } public static Release mockRelease(long releaseId, String releaseKey, String appId, String clusterName, String groupName, String configurations) { Release instance = new Release(); instance.setId(releaseId); instance.setReleaseKey(releaseKey); instance.setAppId(appId); instance.setClusterName(clusterName); instance.setNamespaceName(groupName); instance.setConfigurations(configurations); return instance; } public static Item mockItem(long id, long namespaceId, String itemKey, String itemValue, int lineNum) { Item item = new Item(); item.setId(id); item.setKey(itemKey); item.setValue(itemValue); item.setLineNum(lineNum); item.setNamespaceId(namespaceId); return item; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DNSUtil.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.core.utils; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; public class DNSUtil { public static List<String> resolve(String domainName) throws UnknownHostException { List<String> result = new ArrayList<>(); InetAddress[] addresses = InetAddress.getAllByName(domainName); if (addresses != null) { for (InetAddress addr : addresses) { result.add(addr.getHostAddress()); } } return result; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.core.utils; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; public class DNSUtil { public static List<String> resolve(String domainName) throws UnknownHostException { List<String> result = new ArrayList<>(); InetAddress[] addresses = InetAddress.getAllByName(domainName); if (addresses != null) { for (InetAddress addr : addresses) { result.add(addr.getHostAddress()); } } return result; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/configuration/EmailConfiguration.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.configuration; import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile; import com.ctrip.framework.apollo.portal.spi.EmailService; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripEmailService; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripEmailRequestBuilder; import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultEmailService; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration public class EmailConfiguration { /** * spring.profiles.active = ctrip */ @Configuration @Profile("ctrip") public static class CtripEmailConfiguration { @Bean public EmailService ctripEmailService() { return new CtripEmailService(); } @Bean public CtripEmailRequestBuilder emailRequestBuilder() { return new CtripEmailRequestBuilder(); } } /** * spring.profiles.active != ctrip */ @Configuration @ConditionalOnMissingProfile({"ctrip"}) public static class DefaultEmailConfiguration { @Bean @ConditionalOnMissingBean(EmailService.class) public EmailService defaultEmailService() { return new DefaultEmailService(); } } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.configuration; import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile; import com.ctrip.framework.apollo.portal.spi.EmailService; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripEmailService; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripEmailRequestBuilder; import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultEmailService; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration public class EmailConfiguration { /** * spring.profiles.active = ctrip */ @Configuration @Profile("ctrip") public static class CtripEmailConfiguration { @Bean public EmailService ctripEmailService() { return new CtripEmailService(); } @Bean public CtripEmailRequestBuilder emailRequestBuilder() { return new CtripEmailRequestBuilder(); } } /** * spring.profiles.active != ctrip */ @Configuration @ConditionalOnMissingProfile({"ctrip"}) public static class DefaultEmailConfiguration { @Bean @ConditionalOnMissingBean(EmailService.class) public EmailService defaultEmailService() { return new DefaultEmailService(); } } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/NamespaceController.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.controller; import com.ctrip.framework.apollo.common.dto.AppNamespaceDTO; import com.ctrip.framework.apollo.common.dto.NamespaceDTO; import com.ctrip.framework.apollo.common.entity.AppNamespace; import com.ctrip.framework.apollo.common.exception.BadRequestException; import com.ctrip.framework.apollo.common.http.MultiResponseEntity; import com.ctrip.framework.apollo.common.http.RichResponseEntity; import com.ctrip.framework.apollo.common.utils.BeanUtils; import com.ctrip.framework.apollo.common.utils.InputValidator; import com.ctrip.framework.apollo.common.utils.RequestPrecondition; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.portal.api.AdminServiceAPI; import com.ctrip.framework.apollo.portal.component.PermissionValidator; import com.ctrip.framework.apollo.portal.component.config.PortalConfig; import com.ctrip.framework.apollo.portal.entity.bo.NamespaceBO; import com.ctrip.framework.apollo.portal.entity.model.NamespaceCreationModel; import com.ctrip.framework.apollo.portal.listener.AppNamespaceCreationEvent; import com.ctrip.framework.apollo.portal.listener.AppNamespaceDeletionEvent; import com.ctrip.framework.apollo.portal.service.AppNamespaceService; import com.ctrip.framework.apollo.portal.service.NamespaceService; import com.ctrip.framework.apollo.portal.service.RoleInitializationService; import com.ctrip.framework.apollo.portal.spi.UserInfoHolder; import com.ctrip.framework.apollo.tracer.Tracer; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import static com.ctrip.framework.apollo.common.utils.RequestPrecondition.checkModel; @RestController public class NamespaceController { private static final Logger logger = LoggerFactory.getLogger(NamespaceController.class); private final ApplicationEventPublisher publisher; private final UserInfoHolder userInfoHolder; private final NamespaceService namespaceService; private final AppNamespaceService appNamespaceService; private final RoleInitializationService roleInitializationService; private final PortalConfig portalConfig; private final PermissionValidator permissionValidator; private final AdminServiceAPI.NamespaceAPI namespaceAPI; public NamespaceController( final ApplicationEventPublisher publisher, final UserInfoHolder userInfoHolder, final NamespaceService namespaceService, final AppNamespaceService appNamespaceService, final RoleInitializationService roleInitializationService, final PortalConfig portalConfig, final PermissionValidator permissionValidator, final AdminServiceAPI.NamespaceAPI namespaceAPI) { this.publisher = publisher; this.userInfoHolder = userInfoHolder; this.namespaceService = namespaceService; this.appNamespaceService = appNamespaceService; this.roleInitializationService = roleInitializationService; this.portalConfig = portalConfig; this.permissionValidator = permissionValidator; this.namespaceAPI = namespaceAPI; } @GetMapping("/appnamespaces/public") public List<AppNamespace> findPublicAppNamespaces() { return appNamespaceService.findPublicAppNamespaces(); } @GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces") public List<NamespaceBO> findNamespaces(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName) { List<NamespaceBO> namespaceBOs = namespaceService.findNamespaceBOs(appId, Env.valueOf(env), clusterName); for (NamespaceBO namespaceBO : namespaceBOs) { if (permissionValidator.shouldHideConfigToCurrentUser(appId, env, namespaceBO.getBaseInfo().getNamespaceName())) { namespaceBO.hideItems(); } } return namespaceBOs; } @GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName:.+}") public NamespaceBO findNamespace(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName) { NamespaceBO namespaceBO = namespaceService.loadNamespaceBO(appId, Env.valueOf(env), clusterName, namespaceName); if (namespaceBO != null && permissionValidator.shouldHideConfigToCurrentUser(appId, env, namespaceName)) { namespaceBO.hideItems(); } return namespaceBO; } @GetMapping("/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/associated-public-namespace") public NamespaceBO findPublicNamespaceForAssociatedNamespace(@PathVariable String env, @PathVariable String appId, @PathVariable String namespaceName, @PathVariable String clusterName) { return namespaceService.findPublicNamespaceForAssociatedNamespace(Env.valueOf(env), appId, clusterName, namespaceName); } @PreAuthorize(value = "@permissionValidator.hasCreateNamespacePermission(#appId)") @PostMapping("/apps/{appId}/namespaces") public ResponseEntity<Void> createNamespace(@PathVariable String appId, @RequestBody List<NamespaceCreationModel> models) { checkModel(!CollectionUtils.isEmpty(models)); String namespaceName = models.get(0).getNamespace().getNamespaceName(); String operator = userInfoHolder.getUser().getUserId(); roleInitializationService.initNamespaceRoles(appId, namespaceName, operator); roleInitializationService.initNamespaceEnvRoles(appId, namespaceName, operator); for (NamespaceCreationModel model : models) { NamespaceDTO namespace = model.getNamespace(); RequestPrecondition.checkArgumentsNotEmpty(model.getEnv(), namespace.getAppId(), namespace.getClusterName(), namespace.getNamespaceName()); try { namespaceService.createNamespace(Env.valueOf(model.getEnv()), namespace); } catch (Exception e) { logger.error("create namespace fail.", e); Tracer.logError( String.format("create namespace fail. (env=%s namespace=%s)", model.getEnv(), namespace.getNamespaceName()), e); } } namespaceService.assignNamespaceRoleToOperator(appId, namespaceName,userInfoHolder.getUser().getUserId()); return ResponseEntity.ok().build(); } @PreAuthorize(value = "@permissionValidator.hasDeleteNamespacePermission(#appId)") @DeleteMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName:.+}") public ResponseEntity<Void> deleteNamespace(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName) { namespaceService.deleteNamespace(appId, Env.valueOf(env), clusterName, namespaceName); return ResponseEntity.ok().build(); } @PreAuthorize(value = "@permissionValidator.isSuperAdmin()") @DeleteMapping("/apps/{appId}/appnamespaces/{namespaceName:.+}") public ResponseEntity<Void> deleteAppNamespace(@PathVariable String appId, @PathVariable String namespaceName) { AppNamespace appNamespace = appNamespaceService.deleteAppNamespace(appId, namespaceName); publisher.publishEvent(new AppNamespaceDeletionEvent(appNamespace)); return ResponseEntity.ok().build(); } @GetMapping("/apps/{appId}/appnamespaces/{namespaceName:.+}") public AppNamespaceDTO findAppNamespace(@PathVariable String appId, @PathVariable String namespaceName) { AppNamespace appNamespace = appNamespaceService.findByAppIdAndName(appId, namespaceName); if (appNamespace == null) { throw new BadRequestException( String.format("AppNamespace not exists. AppId = %s, NamespaceName = %s", appId, namespaceName)); } return BeanUtils.transform(AppNamespaceDTO.class, appNamespace); } @PreAuthorize(value = "@permissionValidator.hasCreateAppNamespacePermission(#appId, #appNamespace)") @PostMapping("/apps/{appId}/appnamespaces") public AppNamespace createAppNamespace(@PathVariable String appId, @RequestParam(defaultValue = "true") boolean appendNamespacePrefix, @Valid @RequestBody AppNamespace appNamespace) { if (!InputValidator.isValidAppNamespace(appNamespace.getName())) { throw new BadRequestException(String.format("Invalid Namespace format: %s", InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE + " & " + InputValidator.INVALID_NAMESPACE_NAMESPACE_MESSAGE)); } AppNamespace createdAppNamespace = appNamespaceService.createAppNamespaceInLocal(appNamespace, appendNamespacePrefix); if (portalConfig.canAppAdminCreatePrivateNamespace() || createdAppNamespace.isPublic()) { namespaceService.assignNamespaceRoleToOperator(appId, appNamespace.getName(), userInfoHolder.getUser().getUserId()); } publisher.publishEvent(new AppNamespaceCreationEvent(createdAppNamespace)); return createdAppNamespace; } /** * env -> cluster -> cluster has not published namespace? * Example: * dev -> * default -> true (default cluster has not published namespace) * customCluster -> false (customCluster cluster's all namespaces had published) */ @GetMapping("/apps/{appId}/namespaces/publish_info") public Map<String, Map<String, Boolean>> getNamespacesPublishInfo(@PathVariable String appId) { return namespaceService.getNamespacesPublishInfo(appId); } @GetMapping("/envs/{env}/appnamespaces/{publicNamespaceName}/namespaces") public List<NamespaceDTO> getPublicAppNamespaceAllNamespaces(@PathVariable String env, @PathVariable String publicNamespaceName, @RequestParam(name = "page", defaultValue = "0") int page, @RequestParam(name = "size", defaultValue = "10") int size) { return namespaceService.getPublicAppNamespaceAllNamespaces(Env.valueOf(env), publicNamespaceName, page, size); } @GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/missing-namespaces") public MultiResponseEntity<String> findMissingNamespaces(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName) { MultiResponseEntity<String> response = MultiResponseEntity.ok(); Set<String> missingNamespaces = findMissingNamespaceNames(appId, env, clusterName); for (String missingNamespace : missingNamespaces) { response.addResponseEntity(RichResponseEntity.ok(missingNamespace)); } return response; } @PostMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/missing-namespaces") public ResponseEntity<Void> createMissingNamespaces(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName) { Set<String> missingNamespaces = findMissingNamespaceNames(appId, env, clusterName); for (String missingNamespace : missingNamespaces) { namespaceAPI.createMissingAppNamespace(Env.valueOf(env), findAppNamespace(appId, missingNamespace)); } return ResponseEntity.ok().build(); } private Set<String> findMissingNamespaceNames(String appId, String env, String clusterName) { List<AppNamespaceDTO> configDbAppNamespaces = namespaceAPI.getAppNamespaces(appId, Env.valueOf(env)); List<NamespaceDTO> configDbNamespaces = namespaceService.findNamespaces(appId, Env.valueOf(env), clusterName); List<AppNamespace> portalDbAppNamespaces = appNamespaceService.findByAppId(appId); Set<String> configDbAppNamespaceNames = configDbAppNamespaces.stream().map(AppNamespaceDTO::getName) .collect(Collectors.toSet()); Set<String> configDbNamespaceNames = configDbNamespaces.stream().map(NamespaceDTO::getNamespaceName) .collect(Collectors.toSet()); Set<String> portalDbAllAppNamespaceNames = Sets.newHashSet(); Set<String> portalDbPrivateAppNamespaceNames = Sets.newHashSet(); for (AppNamespace appNamespace : portalDbAppNamespaces) { portalDbAllAppNamespaceNames.add(appNamespace.getName()); if (!appNamespace.isPublic()) { portalDbPrivateAppNamespaceNames.add(appNamespace.getName()); } } // AppNamespaces should be the same Set<String> missingAppNamespaceNames = Sets.difference(portalDbAllAppNamespaceNames, configDbAppNamespaceNames); // Private namespaces should all exist Set<String> missingNamespaceNames = Sets.difference(portalDbPrivateAppNamespaceNames, configDbNamespaceNames); return Sets.union(missingAppNamespaceNames, missingNamespaceNames); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.controller; import com.ctrip.framework.apollo.common.dto.AppNamespaceDTO; import com.ctrip.framework.apollo.common.dto.NamespaceDTO; import com.ctrip.framework.apollo.common.entity.AppNamespace; import com.ctrip.framework.apollo.common.exception.BadRequestException; import com.ctrip.framework.apollo.common.http.MultiResponseEntity; import com.ctrip.framework.apollo.common.http.RichResponseEntity; import com.ctrip.framework.apollo.common.utils.BeanUtils; import com.ctrip.framework.apollo.common.utils.InputValidator; import com.ctrip.framework.apollo.common.utils.RequestPrecondition; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.portal.api.AdminServiceAPI; import com.ctrip.framework.apollo.portal.component.PermissionValidator; import com.ctrip.framework.apollo.portal.component.config.PortalConfig; import com.ctrip.framework.apollo.portal.entity.bo.NamespaceBO; import com.ctrip.framework.apollo.portal.entity.model.NamespaceCreationModel; import com.ctrip.framework.apollo.portal.listener.AppNamespaceCreationEvent; import com.ctrip.framework.apollo.portal.listener.AppNamespaceDeletionEvent; import com.ctrip.framework.apollo.portal.service.AppNamespaceService; import com.ctrip.framework.apollo.portal.service.NamespaceService; import com.ctrip.framework.apollo.portal.service.RoleInitializationService; import com.ctrip.framework.apollo.portal.spi.UserInfoHolder; import com.ctrip.framework.apollo.tracer.Tracer; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import static com.ctrip.framework.apollo.common.utils.RequestPrecondition.checkModel; @RestController public class NamespaceController { private static final Logger logger = LoggerFactory.getLogger(NamespaceController.class); private final ApplicationEventPublisher publisher; private final UserInfoHolder userInfoHolder; private final NamespaceService namespaceService; private final AppNamespaceService appNamespaceService; private final RoleInitializationService roleInitializationService; private final PortalConfig portalConfig; private final PermissionValidator permissionValidator; private final AdminServiceAPI.NamespaceAPI namespaceAPI; public NamespaceController( final ApplicationEventPublisher publisher, final UserInfoHolder userInfoHolder, final NamespaceService namespaceService, final AppNamespaceService appNamespaceService, final RoleInitializationService roleInitializationService, final PortalConfig portalConfig, final PermissionValidator permissionValidator, final AdminServiceAPI.NamespaceAPI namespaceAPI) { this.publisher = publisher; this.userInfoHolder = userInfoHolder; this.namespaceService = namespaceService; this.appNamespaceService = appNamespaceService; this.roleInitializationService = roleInitializationService; this.portalConfig = portalConfig; this.permissionValidator = permissionValidator; this.namespaceAPI = namespaceAPI; } @GetMapping("/appnamespaces/public") public List<AppNamespace> findPublicAppNamespaces() { return appNamespaceService.findPublicAppNamespaces(); } @GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces") public List<NamespaceBO> findNamespaces(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName) { List<NamespaceBO> namespaceBOs = namespaceService.findNamespaceBOs(appId, Env.valueOf(env), clusterName); for (NamespaceBO namespaceBO : namespaceBOs) { if (permissionValidator.shouldHideConfigToCurrentUser(appId, env, namespaceBO.getBaseInfo().getNamespaceName())) { namespaceBO.hideItems(); } } return namespaceBOs; } @GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName:.+}") public NamespaceBO findNamespace(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName) { NamespaceBO namespaceBO = namespaceService.loadNamespaceBO(appId, Env.valueOf(env), clusterName, namespaceName); if (namespaceBO != null && permissionValidator.shouldHideConfigToCurrentUser(appId, env, namespaceName)) { namespaceBO.hideItems(); } return namespaceBO; } @GetMapping("/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/associated-public-namespace") public NamespaceBO findPublicNamespaceForAssociatedNamespace(@PathVariable String env, @PathVariable String appId, @PathVariable String namespaceName, @PathVariable String clusterName) { return namespaceService.findPublicNamespaceForAssociatedNamespace(Env.valueOf(env), appId, clusterName, namespaceName); } @PreAuthorize(value = "@permissionValidator.hasCreateNamespacePermission(#appId)") @PostMapping("/apps/{appId}/namespaces") public ResponseEntity<Void> createNamespace(@PathVariable String appId, @RequestBody List<NamespaceCreationModel> models) { checkModel(!CollectionUtils.isEmpty(models)); String namespaceName = models.get(0).getNamespace().getNamespaceName(); String operator = userInfoHolder.getUser().getUserId(); roleInitializationService.initNamespaceRoles(appId, namespaceName, operator); roleInitializationService.initNamespaceEnvRoles(appId, namespaceName, operator); for (NamespaceCreationModel model : models) { NamespaceDTO namespace = model.getNamespace(); RequestPrecondition.checkArgumentsNotEmpty(model.getEnv(), namespace.getAppId(), namespace.getClusterName(), namespace.getNamespaceName()); try { namespaceService.createNamespace(Env.valueOf(model.getEnv()), namespace); } catch (Exception e) { logger.error("create namespace fail.", e); Tracer.logError( String.format("create namespace fail. (env=%s namespace=%s)", model.getEnv(), namespace.getNamespaceName()), e); } } namespaceService.assignNamespaceRoleToOperator(appId, namespaceName,userInfoHolder.getUser().getUserId()); return ResponseEntity.ok().build(); } @PreAuthorize(value = "@permissionValidator.hasDeleteNamespacePermission(#appId)") @DeleteMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName:.+}") public ResponseEntity<Void> deleteNamespace(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName) { namespaceService.deleteNamespace(appId, Env.valueOf(env), clusterName, namespaceName); return ResponseEntity.ok().build(); } @PreAuthorize(value = "@permissionValidator.isSuperAdmin()") @DeleteMapping("/apps/{appId}/appnamespaces/{namespaceName:.+}") public ResponseEntity<Void> deleteAppNamespace(@PathVariable String appId, @PathVariable String namespaceName) { AppNamespace appNamespace = appNamespaceService.deleteAppNamespace(appId, namespaceName); publisher.publishEvent(new AppNamespaceDeletionEvent(appNamespace)); return ResponseEntity.ok().build(); } @GetMapping("/apps/{appId}/appnamespaces/{namespaceName:.+}") public AppNamespaceDTO findAppNamespace(@PathVariable String appId, @PathVariable String namespaceName) { AppNamespace appNamespace = appNamespaceService.findByAppIdAndName(appId, namespaceName); if (appNamespace == null) { throw new BadRequestException( String.format("AppNamespace not exists. AppId = %s, NamespaceName = %s", appId, namespaceName)); } return BeanUtils.transform(AppNamespaceDTO.class, appNamespace); } @PreAuthorize(value = "@permissionValidator.hasCreateAppNamespacePermission(#appId, #appNamespace)") @PostMapping("/apps/{appId}/appnamespaces") public AppNamespace createAppNamespace(@PathVariable String appId, @RequestParam(defaultValue = "true") boolean appendNamespacePrefix, @Valid @RequestBody AppNamespace appNamespace) { if (!InputValidator.isValidAppNamespace(appNamespace.getName())) { throw new BadRequestException(String.format("Invalid Namespace format: %s", InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE + " & " + InputValidator.INVALID_NAMESPACE_NAMESPACE_MESSAGE)); } AppNamespace createdAppNamespace = appNamespaceService.createAppNamespaceInLocal(appNamespace, appendNamespacePrefix); if (portalConfig.canAppAdminCreatePrivateNamespace() || createdAppNamespace.isPublic()) { namespaceService.assignNamespaceRoleToOperator(appId, appNamespace.getName(), userInfoHolder.getUser().getUserId()); } publisher.publishEvent(new AppNamespaceCreationEvent(createdAppNamespace)); return createdAppNamespace; } /** * env -> cluster -> cluster has not published namespace? * Example: * dev -> * default -> true (default cluster has not published namespace) * customCluster -> false (customCluster cluster's all namespaces had published) */ @GetMapping("/apps/{appId}/namespaces/publish_info") public Map<String, Map<String, Boolean>> getNamespacesPublishInfo(@PathVariable String appId) { return namespaceService.getNamespacesPublishInfo(appId); } @GetMapping("/envs/{env}/appnamespaces/{publicNamespaceName}/namespaces") public List<NamespaceDTO> getPublicAppNamespaceAllNamespaces(@PathVariable String env, @PathVariable String publicNamespaceName, @RequestParam(name = "page", defaultValue = "0") int page, @RequestParam(name = "size", defaultValue = "10") int size) { return namespaceService.getPublicAppNamespaceAllNamespaces(Env.valueOf(env), publicNamespaceName, page, size); } @GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/missing-namespaces") public MultiResponseEntity<String> findMissingNamespaces(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName) { MultiResponseEntity<String> response = MultiResponseEntity.ok(); Set<String> missingNamespaces = findMissingNamespaceNames(appId, env, clusterName); for (String missingNamespace : missingNamespaces) { response.addResponseEntity(RichResponseEntity.ok(missingNamespace)); } return response; } @PostMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/missing-namespaces") public ResponseEntity<Void> createMissingNamespaces(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName) { Set<String> missingNamespaces = findMissingNamespaceNames(appId, env, clusterName); for (String missingNamespace : missingNamespaces) { namespaceAPI.createMissingAppNamespace(Env.valueOf(env), findAppNamespace(appId, missingNamespace)); } return ResponseEntity.ok().build(); } private Set<String> findMissingNamespaceNames(String appId, String env, String clusterName) { List<AppNamespaceDTO> configDbAppNamespaces = namespaceAPI.getAppNamespaces(appId, Env.valueOf(env)); List<NamespaceDTO> configDbNamespaces = namespaceService.findNamespaces(appId, Env.valueOf(env), clusterName); List<AppNamespace> portalDbAppNamespaces = appNamespaceService.findByAppId(appId); Set<String> configDbAppNamespaceNames = configDbAppNamespaces.stream().map(AppNamespaceDTO::getName) .collect(Collectors.toSet()); Set<String> configDbNamespaceNames = configDbNamespaces.stream().map(NamespaceDTO::getNamespaceName) .collect(Collectors.toSet()); Set<String> portalDbAllAppNamespaceNames = Sets.newHashSet(); Set<String> portalDbPrivateAppNamespaceNames = Sets.newHashSet(); for (AppNamespace appNamespace : portalDbAppNamespaces) { portalDbAllAppNamespaceNames.add(appNamespace.getName()); if (!appNamespace.isPublic()) { portalDbPrivateAppNamespaceNames.add(appNamespace.getName()); } } // AppNamespaces should be the same Set<String> missingAppNamespaceNames = Sets.difference(portalDbAllAppNamespaceNames, configDbAppNamespaceNames); // Private namespaces should all exist Set<String> missingNamespaceNames = Sets.difference(portalDbPrivateAppNamespaceNames, configDbNamespaceNames); return Sets.union(missingAppNamespaceNames, missingNamespaceNames); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-mockserver/src/main/java/com/ctrip/framework/apollo/mockserver/EmbeddedApollo.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.mockserver; import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; import com.ctrip.framework.apollo.core.dto.ApolloConfig; import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification; import com.ctrip.framework.apollo.core.utils.ResourceUtils; import com.ctrip.framework.apollo.internals.ConfigServiceLocator; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.rules.ExternalResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Create by zhangzheng on 8/22/18 Email:zhangzheng@youzan.com */ public class EmbeddedApollo extends ExternalResource { private static final Logger logger = LoggerFactory.getLogger(EmbeddedApollo.class); private static final Type notificationType = new TypeToken<List<ApolloConfigNotification>>() { }.getType(); private static Method CONFIG_SERVICE_LOCATOR_CLEAR; private static ConfigServiceLocator CONFIG_SERVICE_LOCATOR; private static final Gson GSON = new Gson(); private final Map<String, Map<String, String>> addedOrModifiedPropertiesOfNamespace = Maps.newConcurrentMap(); private final Map<String, Set<String>> deletedKeysOfNamespace = Maps.newConcurrentMap(); private MockWebServer server; static { try { System.setProperty("apollo.longPollingInitialDelayInMills", "0"); CONFIG_SERVICE_LOCATOR = ApolloInjector.getInstance(ConfigServiceLocator.class); CONFIG_SERVICE_LOCATOR_CLEAR = ConfigServiceLocator.class.getDeclaredMethod("initConfigServices"); CONFIG_SERVICE_LOCATOR_CLEAR.setAccessible(true); } catch (NoSuchMethodException e) { e.printStackTrace(); } } @Override protected void before() throws Throwable { clear(); server = new MockWebServer(); final Dispatcher dispatcher = new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { if (request.getPath().startsWith("/notifications/v2")) { String notifications = request.getRequestUrl().queryParameter("notifications"); return new MockResponse().setResponseCode(200).setBody(mockLongPollBody(notifications)); } if (request.getPath().startsWith("/configs")) { List<String> pathSegments = request.getRequestUrl().pathSegments(); // appId and cluster might be used in the future String appId = pathSegments.get(1); String cluster = pathSegments.get(2); String namespace = pathSegments.get(3); return new MockResponse().setResponseCode(200).setBody(loadConfigFor(namespace)); } return new MockResponse().setResponseCode(404); } }; server.setDispatcher(dispatcher); server.start(); mockConfigServiceUrl("http://localhost:" + server.getPort()); super.before(); } @Override protected void after() { try { clear(); server.close(); } catch (Exception e) { logger.error("stop apollo server error", e); } } private void clear() throws Exception { resetOverriddenProperties(); } private void mockConfigServiceUrl(String url) throws Exception { System.setProperty(ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE, url); CONFIG_SERVICE_LOCATOR_CLEAR.invoke(CONFIG_SERVICE_LOCATOR); } private String loadConfigFor(String namespace) { String filename = String.format("mockdata-%s.properties", namespace); final Properties prop = ResourceUtils.readConfigFile(filename, new Properties()); Map<String, String> configurations = Maps.newHashMap(); for (String propertyName : prop.stringPropertyNames()) { configurations.put(propertyName, prop.getProperty(propertyName)); } ApolloConfig apolloConfig = new ApolloConfig("someAppId", "someCluster", namespace, "someReleaseKey"); Map<String, String> mergedConfigurations = mergeOverriddenProperties(namespace, configurations); apolloConfig.setConfigurations(mergedConfigurations); return GSON.toJson(apolloConfig); } private String mockLongPollBody(String notificationsStr) { List<ApolloConfigNotification> oldNotifications = GSON.fromJson(notificationsStr, notificationType); List<ApolloConfigNotification> newNotifications = new ArrayList<>(); for (ApolloConfigNotification notification : oldNotifications) { newNotifications .add(new ApolloConfigNotification(notification.getNamespaceName(), notification.getNotificationId() + 1)); } return GSON.toJson(newNotifications); } /** * 合并用户对namespace的修改 */ private Map<String, String> mergeOverriddenProperties(String namespace, Map<String, String> configurations) { if (addedOrModifiedPropertiesOfNamespace.containsKey(namespace)) { configurations.putAll(addedOrModifiedPropertiesOfNamespace.get(namespace)); } if (deletedKeysOfNamespace.containsKey(namespace)) { for (String k : deletedKeysOfNamespace.get(namespace)) { configurations.remove(k); } } return configurations; } /** * Add new property or update existed property */ public void addOrModifyProperty(String namespace, String someKey, String someValue) { if (addedOrModifiedPropertiesOfNamespace.containsKey(namespace)) { addedOrModifiedPropertiesOfNamespace.get(namespace).put(someKey, someValue); } else { Map<String, String> m = Maps.newConcurrentMap(); m.put(someKey, someValue); addedOrModifiedPropertiesOfNamespace.put(namespace, m); } } /** * Delete existed property */ public void deleteProperty(String namespace, String someKey) { if (deletedKeysOfNamespace.containsKey(namespace)) { deletedKeysOfNamespace.get(namespace).add(someKey); } else { Set<String> m = Sets.newConcurrentHashSet(); m.add(someKey); deletedKeysOfNamespace.put(namespace, m); } } /** * reset overridden properties */ public void resetOverriddenProperties() { addedOrModifiedPropertiesOfNamespace.clear(); deletedKeysOfNamespace.clear(); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.mockserver; import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; import com.ctrip.framework.apollo.core.dto.ApolloConfig; import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification; import com.ctrip.framework.apollo.core.utils.ResourceUtils; import com.ctrip.framework.apollo.internals.ConfigServiceLocator; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.rules.ExternalResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Create by zhangzheng on 8/22/18 Email:zhangzheng@youzan.com */ public class EmbeddedApollo extends ExternalResource { private static final Logger logger = LoggerFactory.getLogger(EmbeddedApollo.class); private static final Type notificationType = new TypeToken<List<ApolloConfigNotification>>() { }.getType(); private static Method CONFIG_SERVICE_LOCATOR_CLEAR; private static ConfigServiceLocator CONFIG_SERVICE_LOCATOR; private static final Gson GSON = new Gson(); private final Map<String, Map<String, String>> addedOrModifiedPropertiesOfNamespace = Maps.newConcurrentMap(); private final Map<String, Set<String>> deletedKeysOfNamespace = Maps.newConcurrentMap(); private MockWebServer server; static { try { System.setProperty("apollo.longPollingInitialDelayInMills", "0"); CONFIG_SERVICE_LOCATOR = ApolloInjector.getInstance(ConfigServiceLocator.class); CONFIG_SERVICE_LOCATOR_CLEAR = ConfigServiceLocator.class.getDeclaredMethod("initConfigServices"); CONFIG_SERVICE_LOCATOR_CLEAR.setAccessible(true); } catch (NoSuchMethodException e) { e.printStackTrace(); } } @Override protected void before() throws Throwable { clear(); server = new MockWebServer(); final Dispatcher dispatcher = new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { if (request.getPath().startsWith("/notifications/v2")) { String notifications = request.getRequestUrl().queryParameter("notifications"); return new MockResponse().setResponseCode(200).setBody(mockLongPollBody(notifications)); } if (request.getPath().startsWith("/configs")) { List<String> pathSegments = request.getRequestUrl().pathSegments(); // appId and cluster might be used in the future String appId = pathSegments.get(1); String cluster = pathSegments.get(2); String namespace = pathSegments.get(3); return new MockResponse().setResponseCode(200).setBody(loadConfigFor(namespace)); } return new MockResponse().setResponseCode(404); } }; server.setDispatcher(dispatcher); server.start(); mockConfigServiceUrl("http://localhost:" + server.getPort()); super.before(); } @Override protected void after() { try { clear(); server.close(); } catch (Exception e) { logger.error("stop apollo server error", e); } } private void clear() throws Exception { resetOverriddenProperties(); } private void mockConfigServiceUrl(String url) throws Exception { System.setProperty(ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE, url); CONFIG_SERVICE_LOCATOR_CLEAR.invoke(CONFIG_SERVICE_LOCATOR); } private String loadConfigFor(String namespace) { String filename = String.format("mockdata-%s.properties", namespace); final Properties prop = ResourceUtils.readConfigFile(filename, new Properties()); Map<String, String> configurations = Maps.newHashMap(); for (String propertyName : prop.stringPropertyNames()) { configurations.put(propertyName, prop.getProperty(propertyName)); } ApolloConfig apolloConfig = new ApolloConfig("someAppId", "someCluster", namespace, "someReleaseKey"); Map<String, String> mergedConfigurations = mergeOverriddenProperties(namespace, configurations); apolloConfig.setConfigurations(mergedConfigurations); return GSON.toJson(apolloConfig); } private String mockLongPollBody(String notificationsStr) { List<ApolloConfigNotification> oldNotifications = GSON.fromJson(notificationsStr, notificationType); List<ApolloConfigNotification> newNotifications = new ArrayList<>(); for (ApolloConfigNotification notification : oldNotifications) { newNotifications .add(new ApolloConfigNotification(notification.getNamespaceName(), notification.getNotificationId() + 1)); } return GSON.toJson(newNotifications); } /** * 合并用户对namespace的修改 */ private Map<String, String> mergeOverriddenProperties(String namespace, Map<String, String> configurations) { if (addedOrModifiedPropertiesOfNamespace.containsKey(namespace)) { configurations.putAll(addedOrModifiedPropertiesOfNamespace.get(namespace)); } if (deletedKeysOfNamespace.containsKey(namespace)) { for (String k : deletedKeysOfNamespace.get(namespace)) { configurations.remove(k); } } return configurations; } /** * Add new property or update existed property */ public void addOrModifyProperty(String namespace, String someKey, String someValue) { if (addedOrModifiedPropertiesOfNamespace.containsKey(namespace)) { addedOrModifiedPropertiesOfNamespace.get(namespace).put(someKey, someValue); } else { Map<String, String> m = Maps.newConcurrentMap(); m.put(someKey, someValue); addedOrModifiedPropertiesOfNamespace.put(namespace, m); } } /** * Delete existed property */ public void deleteProperty(String namespace, String someKey) { if (deletedKeysOfNamespace.containsKey(namespace)) { deletedKeysOfNamespace.get(namespace).add(someKey); } else { Set<String> m = Sets.newConcurrentHashSet(); m.add(someKey); deletedKeysOfNamespace.put(namespace, m); } } /** * reset overridden properties */ public void resetOverriddenProperties() { addedOrModifiedPropertiesOfNamespace.clear(); deletedKeysOfNamespace.clear(); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/SpringValueProcessor.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.spring.annotation; import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.spring.property.PlaceholderHelper; import com.ctrip.framework.apollo.spring.property.SpringValue; import com.ctrip.framework.apollo.spring.property.SpringValueDefinition; import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor; import com.ctrip.framework.apollo.spring.property.SpringValueRegistry; import com.ctrip.framework.apollo.spring.util.SpringInjector; import com.ctrip.framework.apollo.util.ConfigUtil; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.Multimap; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.Bean; /** * Spring value processor of field or method which has @Value and xml config placeholders. * * @author github.com/zhegexiaohuozi seimimaster@gmail.com * @since 2017/12/20. */ public class SpringValueProcessor extends ApolloProcessor implements BeanFactoryPostProcessor, BeanFactoryAware { private static final Logger logger = LoggerFactory.getLogger(SpringValueProcessor.class); private final ConfigUtil configUtil; private final PlaceholderHelper placeholderHelper; private final SpringValueRegistry springValueRegistry; private BeanFactory beanFactory; private Multimap<String, SpringValueDefinition> beanName2SpringValueDefinitions; public SpringValueProcessor() { configUtil = ApolloInjector.getInstance(ConfigUtil.class); placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class); springValueRegistry = SpringInjector.getInstance(SpringValueRegistry.class); beanName2SpringValueDefinitions = LinkedListMultimap.create(); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled() && beanFactory instanceof BeanDefinitionRegistry) { beanName2SpringValueDefinitions = SpringValueDefinitionProcessor .getBeanName2SpringValueDefinitions((BeanDefinitionRegistry) beanFactory); } } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) { super.postProcessBeforeInitialization(bean, beanName); processBeanPropertyValues(bean, beanName); } return bean; } @Override protected void processField(Object bean, String beanName, Field field) { // register @Value on field Value value = field.getAnnotation(Value.class); if (value == null) { return; } Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value()); if (keys.isEmpty()) { return; } for (String key : keys) { SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, field, false); springValueRegistry.register(beanFactory, key, springValue); logger.debug("Monitoring {}", springValue); } } @Override protected void processMethod(Object bean, String beanName, Method method) { //register @Value on method Value value = method.getAnnotation(Value.class); if (value == null) { return; } //skip Configuration bean methods if (method.getAnnotation(Bean.class) != null) { return; } if (method.getParameterTypes().length != 1) { logger.error("Ignore @Value setter {}.{}, expecting 1 parameter, actual {} parameters", bean.getClass().getName(), method.getName(), method.getParameterTypes().length); return; } Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value()); if (keys.isEmpty()) { return; } for (String key : keys) { SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, method, false); springValueRegistry.register(beanFactory, key, springValue); logger.info("Monitoring {}", springValue); } } private void processBeanPropertyValues(Object bean, String beanName) { Collection<SpringValueDefinition> propertySpringValues = beanName2SpringValueDefinitions .get(beanName); if (propertySpringValues == null || propertySpringValues.isEmpty()) { return; } for (SpringValueDefinition definition : propertySpringValues) { try { PropertyDescriptor pd = BeanUtils .getPropertyDescriptor(bean.getClass(), definition.getPropertyName()); Method method = pd.getWriteMethod(); if (method == null) { continue; } SpringValue springValue = new SpringValue(definition.getKey(), definition.getPlaceholder(), bean, beanName, method, false); springValueRegistry.register(beanFactory, definition.getKey(), springValue); logger.debug("Monitoring {}", springValue); } catch (Throwable ex) { logger.error("Failed to enable auto update feature for {}.{}", bean.getClass(), definition.getPropertyName()); } } // clear beanName2SpringValueDefinitions.removeAll(beanName); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.spring.annotation; import com.ctrip.framework.apollo.build.ApolloInjector; import com.ctrip.framework.apollo.spring.property.PlaceholderHelper; import com.ctrip.framework.apollo.spring.property.SpringValue; import com.ctrip.framework.apollo.spring.property.SpringValueDefinition; import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor; import com.ctrip.framework.apollo.spring.property.SpringValueRegistry; import com.ctrip.framework.apollo.spring.util.SpringInjector; import com.ctrip.framework.apollo.util.ConfigUtil; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.Multimap; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.Bean; /** * Spring value processor of field or method which has @Value and xml config placeholders. * * @author github.com/zhegexiaohuozi seimimaster@gmail.com * @since 2017/12/20. */ public class SpringValueProcessor extends ApolloProcessor implements BeanFactoryPostProcessor, BeanFactoryAware { private static final Logger logger = LoggerFactory.getLogger(SpringValueProcessor.class); private final ConfigUtil configUtil; private final PlaceholderHelper placeholderHelper; private final SpringValueRegistry springValueRegistry; private BeanFactory beanFactory; private Multimap<String, SpringValueDefinition> beanName2SpringValueDefinitions; public SpringValueProcessor() { configUtil = ApolloInjector.getInstance(ConfigUtil.class); placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class); springValueRegistry = SpringInjector.getInstance(SpringValueRegistry.class); beanName2SpringValueDefinitions = LinkedListMultimap.create(); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled() && beanFactory instanceof BeanDefinitionRegistry) { beanName2SpringValueDefinitions = SpringValueDefinitionProcessor .getBeanName2SpringValueDefinitions((BeanDefinitionRegistry) beanFactory); } } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) { super.postProcessBeforeInitialization(bean, beanName); processBeanPropertyValues(bean, beanName); } return bean; } @Override protected void processField(Object bean, String beanName, Field field) { // register @Value on field Value value = field.getAnnotation(Value.class); if (value == null) { return; } Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value()); if (keys.isEmpty()) { return; } for (String key : keys) { SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, field, false); springValueRegistry.register(beanFactory, key, springValue); logger.debug("Monitoring {}", springValue); } } @Override protected void processMethod(Object bean, String beanName, Method method) { //register @Value on method Value value = method.getAnnotation(Value.class); if (value == null) { return; } //skip Configuration bean methods if (method.getAnnotation(Bean.class) != null) { return; } if (method.getParameterTypes().length != 1) { logger.error("Ignore @Value setter {}.{}, expecting 1 parameter, actual {} parameters", bean.getClass().getName(), method.getName(), method.getParameterTypes().length); return; } Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value()); if (keys.isEmpty()) { return; } for (String key : keys) { SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, method, false); springValueRegistry.register(beanFactory, key, springValue); logger.info("Monitoring {}", springValue); } } private void processBeanPropertyValues(Object bean, String beanName) { Collection<SpringValueDefinition> propertySpringValues = beanName2SpringValueDefinitions .get(beanName); if (propertySpringValues == null || propertySpringValues.isEmpty()) { return; } for (SpringValueDefinition definition : propertySpringValues) { try { PropertyDescriptor pd = BeanUtils .getPropertyDescriptor(bean.getClass(), definition.getPropertyName()); Method method = pd.getWriteMethod(); if (method == null) { continue; } SpringValue springValue = new SpringValue(definition.getKey(), definition.getPlaceholder(), bean, beanName, method, false); springValueRegistry.register(beanFactory, definition.getKey(), springValue); logger.debug("Monitoring {}", springValue); } catch (Throwable ex) { logger.error("Failed to enable auto update feature for {}.{}", bean.getClass(), definition.getPropertyName()); } } // clear beanName2SpringValueDefinitions.removeAll(beanName); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientPropertyCompatibleTestConfiguration.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.config.data.system; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Configuration; /** * @author vdisk <vdisk@foxmail.com> */ @Configuration @EnableAutoConfiguration public class ApolloClientPropertyCompatibleTestConfiguration { }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.config.data.system; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Configuration; /** * @author vdisk <vdisk@foxmail.com> */ @Configuration @EnableAutoConfiguration public class ApolloClientPropertyCompatibleTestConfiguration { }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/customize/BizLoggingCustomizer.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.customize; import com.ctrip.framework.apollo.biz.config.BizConfig; import com.ctrip.framework.apollo.common.customize.LoggingCustomizer; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Profile("ctrip") public class BizLoggingCustomizer extends LoggingCustomizer{ private final BizConfig bizConfig; public BizLoggingCustomizer(final BizConfig bizConfig) { this.bizConfig = bizConfig; } @Override protected String cloggingUrl() { return bizConfig.cloggingUrl(); } @Override protected String cloggingPort() { return bizConfig.cloggingPort(); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.customize; import com.ctrip.framework.apollo.biz.config.BizConfig; import com.ctrip.framework.apollo.common.customize.LoggingCustomizer; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Profile("ctrip") public class BizLoggingCustomizer extends LoggingCustomizer{ private final BizConfig bizConfig; public BizLoggingCustomizer(final BizConfig bizConfig) { this.bizConfig = bizConfig; } @Override protected String cloggingUrl() { return bizConfig.cloggingUrl(); } @Override protected String cloggingPort() { return bizConfig.cloggingPort(); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-core/src/main/java/com/ctrip/framework/foundation/internals/ServiceBootstrap.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.foundation.internals; import com.ctrip.framework.apollo.core.spi.Ordered; import com.google.common.collect.Lists; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; public class ServiceBootstrap { public static <S> S loadFirst(Class<S> clazz) { Iterator<S> iterator = loadAll(clazz); if (!iterator.hasNext()) { throw new IllegalStateException(String.format( "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!", clazz.getName())); } return iterator.next(); } public static <S> Iterator<S> loadAll(Class<S> clazz) { ServiceLoader<S> loader = ServiceLoader.load(clazz); return loader.iterator(); } public static <S extends Ordered> List<S> loadAllOrdered(Class<S> clazz) { Iterator<S> iterator = loadAll(clazz); List<S> candidates = Lists.newArrayList(iterator); Collections.sort(candidates, new Comparator<S>() { @Override public int compare(S o1, S o2) { // the smaller order has higher priority return Integer.compare(o1.getOrder(), o2.getOrder()); } }); return candidates; } public static <S extends Ordered> S loadPrimary(Class<S> clazz) { List<S> candidates = loadAllOrdered(clazz); if (candidates.isEmpty()) { throw new IllegalStateException(String.format( "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!", clazz.getName())); } return candidates.get(0); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.foundation.internals; import com.ctrip.framework.apollo.core.spi.Ordered; import com.google.common.collect.Lists; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; public class ServiceBootstrap { public static <S> S loadFirst(Class<S> clazz) { Iterator<S> iterator = loadAll(clazz); if (!iterator.hasNext()) { throw new IllegalStateException(String.format( "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!", clazz.getName())); } return iterator.next(); } public static <S> Iterator<S> loadAll(Class<S> clazz) { ServiceLoader<S> loader = ServiceLoader.load(clazz); return loader.iterator(); } public static <S extends Ordered> List<S> loadAllOrdered(Class<S> clazz) { Iterator<S> iterator = loadAll(clazz); List<S> candidates = Lists.newArrayList(iterator); Collections.sort(candidates, new Comparator<S>() { @Override public int compare(S o1, S o2) { // the smaller order has higher priority return Integer.compare(o1.getOrder(), o2.getOrder()); } }); return candidates; } public static <S extends Ordered> S loadPrimary(Class<S> clazz) { List<S> candidates = loadAllOrdered(clazz); if (candidates.isEmpty()) { throw new IllegalStateException(String.format( "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!", clazz.getName())); } return candidates.get(0); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-adminservice/src/test/java/com/ctrip/framework/apollo/adminservice/controller/ReleaseControllerTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.adminservice.controller; import com.ctrip.framework.apollo.biz.entity.Namespace; import com.ctrip.framework.apollo.biz.message.MessageSender; import com.ctrip.framework.apollo.biz.message.Topics; import com.ctrip.framework.apollo.biz.repository.ReleaseRepository; import com.ctrip.framework.apollo.biz.service.NamespaceService; import com.ctrip.framework.apollo.biz.service.ReleaseService; import com.ctrip.framework.apollo.common.dto.AppDTO; import com.ctrip.framework.apollo.common.dto.ClusterDTO; import com.ctrip.framework.apollo.common.dto.ItemDTO; import com.ctrip.framework.apollo.common.dto.NamespaceDTO; import com.ctrip.framework.apollo.common.dto.ReleaseDTO; import com.ctrip.framework.apollo.core.ConfigConsts; import com.google.common.base.Joiner; import com.google.gson.Gson; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.Sql.ExecutionPhase; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import java.util.HashMap; import java.util.Map; import static org.mockito.Mockito.*; public class ReleaseControllerTest extends AbstractControllerTest { private static final Gson GSON = new Gson(); @Autowired ReleaseRepository releaseRepository; @Test @Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD) public void testReleaseBuild() { String appId = "someAppId"; AppDTO app = restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class); ClusterDTO cluster = restTemplate.getForObject( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default", ClusterDTO.class); NamespaceDTO namespace = restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class); Assert.assertEquals("someAppId", app.getAppId()); Assert.assertEquals("default", cluster.getName()); Assert.assertEquals("application", namespace.getNamespaceName()); ItemDTO[] items = restTemplate.getForObject( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/items", ItemDTO[].class); Assert.assertEquals(3, items.length); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.add("name", "someReleaseName"); parameters.add("comment", "someComment"); parameters.add("operator", "test"); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(parameters, headers); ResponseEntity<ReleaseDTO> response = restTemplate.postForEntity( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/releases", entity, ReleaseDTO.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); ReleaseDTO release = response.getBody(); Assert.assertEquals("someReleaseName", release.getName()); Assert.assertEquals("someComment", release.getComment()); Assert.assertEquals("someAppId", release.getAppId()); Assert.assertEquals("default", release.getClusterName()); Assert.assertEquals("application", release.getNamespaceName()); Map<String, String> configurations = new HashMap<>(); configurations.put("k1", "v1"); configurations.put("k2", "v2"); configurations.put("k3", "v3"); Assert.assertEquals(GSON.toJson(configurations), release.getConfigurations()); } @Test public void testMessageSendAfterBuildRelease() throws Exception { String someAppId = "someAppId"; String someNamespaceName = "someNamespace"; String someCluster = "someCluster"; String someName = "someName"; String someComment = "someComment"; String someUserName = "someUser"; NamespaceService someNamespaceService = mock(NamespaceService.class); ReleaseService someReleaseService = mock(ReleaseService.class); MessageSender someMessageSender = mock(MessageSender.class); Namespace someNamespace = mock(Namespace.class); ReleaseController releaseController = new ReleaseController(someReleaseService, someNamespaceService, someMessageSender, null); when(someNamespaceService.findOne(someAppId, someCluster, someNamespaceName)) .thenReturn(someNamespace); releaseController .publish(someAppId, someCluster, someNamespaceName, someName, someComment, "test", false); verify(someMessageSender, times(1)) .sendMessage(Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR) .join(someAppId, someCluster, someNamespaceName), Topics.APOLLO_RELEASE_TOPIC); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.adminservice.controller; import com.ctrip.framework.apollo.biz.entity.Namespace; import com.ctrip.framework.apollo.biz.message.MessageSender; import com.ctrip.framework.apollo.biz.message.Topics; import com.ctrip.framework.apollo.biz.repository.ReleaseRepository; import com.ctrip.framework.apollo.biz.service.NamespaceService; import com.ctrip.framework.apollo.biz.service.ReleaseService; import com.ctrip.framework.apollo.common.dto.AppDTO; import com.ctrip.framework.apollo.common.dto.ClusterDTO; import com.ctrip.framework.apollo.common.dto.ItemDTO; import com.ctrip.framework.apollo.common.dto.NamespaceDTO; import com.ctrip.framework.apollo.common.dto.ReleaseDTO; import com.ctrip.framework.apollo.core.ConfigConsts; import com.google.common.base.Joiner; import com.google.gson.Gson; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.Sql.ExecutionPhase; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import java.util.HashMap; import java.util.Map; import static org.mockito.Mockito.*; public class ReleaseControllerTest extends AbstractControllerTest { private static final Gson GSON = new Gson(); @Autowired ReleaseRepository releaseRepository; @Test @Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD) @Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD) public void testReleaseBuild() { String appId = "someAppId"; AppDTO app = restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class); ClusterDTO cluster = restTemplate.getForObject( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default", ClusterDTO.class); NamespaceDTO namespace = restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class); Assert.assertEquals("someAppId", app.getAppId()); Assert.assertEquals("default", cluster.getName()); Assert.assertEquals("application", namespace.getNamespaceName()); ItemDTO[] items = restTemplate.getForObject( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/items", ItemDTO[].class); Assert.assertEquals(3, items.length); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.add("name", "someReleaseName"); parameters.add("comment", "someComment"); parameters.add("operator", "test"); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(parameters, headers); ResponseEntity<ReleaseDTO> response = restTemplate.postForEntity( "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/releases", entity, ReleaseDTO.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); ReleaseDTO release = response.getBody(); Assert.assertEquals("someReleaseName", release.getName()); Assert.assertEquals("someComment", release.getComment()); Assert.assertEquals("someAppId", release.getAppId()); Assert.assertEquals("default", release.getClusterName()); Assert.assertEquals("application", release.getNamespaceName()); Map<String, String> configurations = new HashMap<>(); configurations.put("k1", "v1"); configurations.put("k2", "v2"); configurations.put("k3", "v3"); Assert.assertEquals(GSON.toJson(configurations), release.getConfigurations()); } @Test public void testMessageSendAfterBuildRelease() throws Exception { String someAppId = "someAppId"; String someNamespaceName = "someNamespace"; String someCluster = "someCluster"; String someName = "someName"; String someComment = "someComment"; String someUserName = "someUser"; NamespaceService someNamespaceService = mock(NamespaceService.class); ReleaseService someReleaseService = mock(ReleaseService.class); MessageSender someMessageSender = mock(MessageSender.class); Namespace someNamespace = mock(Namespace.class); ReleaseController releaseController = new ReleaseController(someReleaseService, someNamespaceService, someMessageSender, null); when(someNamespaceService.findOne(someAppId, someCluster, someNamespaceName)) .thenReturn(someNamespace); releaseController .publish(someAppId, someCluster, someNamespaceName, someName, someComment, "test", false); verify(someMessageSender, times(1)) .sendMessage(Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR) .join(someAppId, someCluster, someNamespaceName), Topics.APOLLO_RELEASE_TOPIC); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenItemDTO.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.openapi.dto; public class OpenItemDTO extends BaseDTO { private String key; private String value; private String comment; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } @Override public String toString() { return "OpenItemDTO{" + "key='" + key + '\'' + ", value='" + value + '\'' + ", comment='" + comment + '\'' + ", dataChangeCreatedBy='" + dataChangeCreatedBy + '\'' + ", dataChangeLastModifiedBy='" + dataChangeLastModifiedBy + '\'' + ", dataChangeCreatedTime=" + dataChangeCreatedTime + ", dataChangeLastModifiedTime=" + dataChangeLastModifiedTime + '}'; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.openapi.dto; public class OpenItemDTO extends BaseDTO { private String key; private String value; private String comment; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } @Override public String toString() { return "OpenItemDTO{" + "key='" + key + '\'' + ", value='" + value + '\'' + ", comment='" + comment + '\'' + ", dataChangeCreatedBy='" + dataChangeCreatedBy + '\'' + ", dataChangeLastModifiedBy='" + dataChangeLastModifiedBy + '\'' + ", dataChangeCreatedTime=" + dataChangeCreatedTime + ", dataChangeLastModifiedTime=" + dataChangeLastModifiedTime + '}'; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-biz/src/test/java/com/ctrip/framework/apollo/biz/service/ReleaseServiceTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.service; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.ctrip.framework.apollo.biz.AbstractUnitTest; import com.ctrip.framework.apollo.biz.MockBeanFactory; import com.ctrip.framework.apollo.biz.entity.Release; import com.ctrip.framework.apollo.biz.repository.ReleaseRepository; import com.ctrip.framework.apollo.common.exception.BadRequestException; import java.util.ArrayList; import java.util.Optional; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.data.domain.PageRequest; import java.util.Arrays; import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ReleaseServiceTest extends AbstractUnitTest { @Mock private ReleaseRepository releaseRepository; @Mock private NamespaceService namespaceService; @Mock private ReleaseHistoryService releaseHistoryService; @Mock private ItemSetService itemSetService; @InjectMocks private ReleaseService releaseService; private String appId = "appId-test"; private String clusterName = "cluster-test"; private String namespaceName = "namespace-test"; private String user = "user-test"; private long releaseId = 1; private Release firstRelease; private Release secondRelease; private PageRequest pageRequest; @Before public void init() { firstRelease = new Release(); firstRelease.setId(releaseId); firstRelease.setAppId(appId); firstRelease.setClusterName(clusterName); firstRelease.setNamespaceName(namespaceName); firstRelease.setAbandoned(false); secondRelease = new Release(); secondRelease.setAppId(appId); secondRelease.setClusterName(clusterName); secondRelease.setNamespaceName(namespaceName); secondRelease.setAbandoned(false); pageRequest = PageRequest.of(0, 2); } @Test(expected = BadRequestException.class) public void testNamespaceNotExist() { when(releaseRepository.findById(releaseId)).thenReturn(Optional.of(firstRelease)); releaseService.rollback(releaseId, user); } @Test(expected = BadRequestException.class) public void testHasNoRelease() { when(releaseRepository.findById(releaseId)).thenReturn(Optional.of(firstRelease)); when(releaseRepository.findByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(appId, clusterName, namespaceName, pageRequest)) .thenReturn(null); releaseService.rollback(releaseId, user); } @Test public void testRollback() { when(releaseRepository.findById(releaseId)).thenReturn(Optional.of(firstRelease)); when(releaseRepository.findByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(appId, clusterName, namespaceName, pageRequest)) .thenReturn( Arrays.asList(firstRelease, secondRelease)); releaseService.rollback(releaseId, user); verify(releaseRepository).save(firstRelease); Assert.assertEquals(true, firstRelease.isAbandoned()); Assert.assertEquals(user, firstRelease.getDataChangeLastModifiedBy()); } @Test public void testRollbackTo() { List<Release> releaseList = new ArrayList<>(); for (int i = 0; i < 3; i++) { Release release = new Release(); release.setId(3 - i); release.setAppId(appId); release.setClusterName(clusterName); release.setNamespaceName(namespaceName); release.setAbandoned(false); releaseList.add(release); } long releaseId1 = 1; long releaseId3 = 3; when(releaseRepository.findById(releaseId1)).thenReturn(Optional.of(releaseList.get(2))); when(releaseRepository.findById(releaseId3)).thenReturn(Optional.of(releaseList.get(0))); when(releaseRepository.findByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseAndIdBetweenOrderByIdDesc(appId, clusterName, namespaceName, releaseId1, releaseId3)) .thenReturn(releaseList); releaseService.rollbackTo(releaseId3, releaseId1, user); verify(releaseRepository).saveAll(releaseList); Assert.assertTrue(releaseList.get(0).isAbandoned()); Assert.assertTrue(releaseList.get(1).isAbandoned()); Assert.assertFalse(releaseList.get(2).isAbandoned()); Assert.assertEquals(user, releaseList.get(0).getDataChangeLastModifiedBy()); Assert.assertEquals(user, releaseList.get(1).getDataChangeLastModifiedBy()); } @Test public void testFindRelease() throws Exception { String someAppId = "1"; String someClusterName = "someClusterName"; String someNamespaceName = "someNamespaceName"; long someReleaseId = 1; String someReleaseKey = "someKey"; String someValidConfiguration = "{\"apollo.bar\": \"foo\"}"; Release someRelease = MockBeanFactory.mockRelease(someReleaseId, someReleaseKey, someAppId, someClusterName, someNamespaceName, someValidConfiguration); when(releaseRepository.findFirstByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(someAppId, someClusterName, someNamespaceName)) .thenReturn(someRelease); Release result = releaseService.findLatestActiveRelease(someAppId, someClusterName, someNamespaceName); verify(releaseRepository, times(1)) .findFirstByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(someAppId, someClusterName, someNamespaceName); assertEquals(someAppId, result.getAppId()); assertEquals(someClusterName, result.getClusterName()); assertEquals(someReleaseId, result.getId()); assertEquals(someReleaseKey, result.getReleaseKey()); assertEquals(someValidConfiguration, result.getConfigurations()); } @Test public void testLoadConfigWithConfigNotFound() throws Exception { String someAppId = "1"; String someClusterName = "someClusterName"; String someNamespaceName = "someNamespaceName"; when(releaseRepository.findFirstByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(someAppId, someClusterName, someNamespaceName)) .thenReturn(null); Release result = releaseService.findLatestActiveRelease(someAppId, someClusterName, someNamespaceName); assertNull(result); verify(releaseRepository, times(1)).findFirstByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc( someAppId, someClusterName, someNamespaceName); } @Test public void testFindByReleaseIds() throws Exception { Release someRelease = mock(Release.class); Release anotherRelease = mock(Release.class); long someReleaseId = 1; long anotherReleaseId = 2; List<Release> someReleases = Lists.newArrayList(someRelease, anotherRelease); Set<Long> someReleaseIds = Sets.newHashSet(someReleaseId, anotherReleaseId); when(releaseRepository.findAllById(someReleaseIds)).thenReturn(someReleases); List<Release> result = releaseService.findByReleaseIds(someReleaseIds); assertEquals(someReleases, result); } @Test public void testFindByReleaseKeys() throws Exception { Release someRelease = mock(Release.class); Release anotherRelease = mock(Release.class); String someReleaseKey = "key1"; String anotherReleaseKey = "key2"; List<Release> someReleases = Lists.newArrayList(someRelease, anotherRelease); Set<String> someReleaseKeys = Sets.newHashSet(someReleaseKey, anotherReleaseKey); when(releaseRepository.findByReleaseKeyIn(someReleaseKeys)).thenReturn(someReleases); List<Release> result = releaseService.findByReleaseKeys(someReleaseKeys); assertEquals(someReleases, result); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.service; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.ctrip.framework.apollo.biz.AbstractUnitTest; import com.ctrip.framework.apollo.biz.MockBeanFactory; import com.ctrip.framework.apollo.biz.entity.Release; import com.ctrip.framework.apollo.biz.repository.ReleaseRepository; import com.ctrip.framework.apollo.common.exception.BadRequestException; import java.util.ArrayList; import java.util.Optional; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.data.domain.PageRequest; import java.util.Arrays; import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ReleaseServiceTest extends AbstractUnitTest { @Mock private ReleaseRepository releaseRepository; @Mock private NamespaceService namespaceService; @Mock private ReleaseHistoryService releaseHistoryService; @Mock private ItemSetService itemSetService; @InjectMocks private ReleaseService releaseService; private String appId = "appId-test"; private String clusterName = "cluster-test"; private String namespaceName = "namespace-test"; private String user = "user-test"; private long releaseId = 1; private Release firstRelease; private Release secondRelease; private PageRequest pageRequest; @Before public void init() { firstRelease = new Release(); firstRelease.setId(releaseId); firstRelease.setAppId(appId); firstRelease.setClusterName(clusterName); firstRelease.setNamespaceName(namespaceName); firstRelease.setAbandoned(false); secondRelease = new Release(); secondRelease.setAppId(appId); secondRelease.setClusterName(clusterName); secondRelease.setNamespaceName(namespaceName); secondRelease.setAbandoned(false); pageRequest = PageRequest.of(0, 2); } @Test(expected = BadRequestException.class) public void testNamespaceNotExist() { when(releaseRepository.findById(releaseId)).thenReturn(Optional.of(firstRelease)); releaseService.rollback(releaseId, user); } @Test(expected = BadRequestException.class) public void testHasNoRelease() { when(releaseRepository.findById(releaseId)).thenReturn(Optional.of(firstRelease)); when(releaseRepository.findByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(appId, clusterName, namespaceName, pageRequest)) .thenReturn(null); releaseService.rollback(releaseId, user); } @Test public void testRollback() { when(releaseRepository.findById(releaseId)).thenReturn(Optional.of(firstRelease)); when(releaseRepository.findByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(appId, clusterName, namespaceName, pageRequest)) .thenReturn( Arrays.asList(firstRelease, secondRelease)); releaseService.rollback(releaseId, user); verify(releaseRepository).save(firstRelease); Assert.assertEquals(true, firstRelease.isAbandoned()); Assert.assertEquals(user, firstRelease.getDataChangeLastModifiedBy()); } @Test public void testRollbackTo() { List<Release> releaseList = new ArrayList<>(); for (int i = 0; i < 3; i++) { Release release = new Release(); release.setId(3 - i); release.setAppId(appId); release.setClusterName(clusterName); release.setNamespaceName(namespaceName); release.setAbandoned(false); releaseList.add(release); } long releaseId1 = 1; long releaseId3 = 3; when(releaseRepository.findById(releaseId1)).thenReturn(Optional.of(releaseList.get(2))); when(releaseRepository.findById(releaseId3)).thenReturn(Optional.of(releaseList.get(0))); when(releaseRepository.findByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseAndIdBetweenOrderByIdDesc(appId, clusterName, namespaceName, releaseId1, releaseId3)) .thenReturn(releaseList); releaseService.rollbackTo(releaseId3, releaseId1, user); verify(releaseRepository).saveAll(releaseList); Assert.assertTrue(releaseList.get(0).isAbandoned()); Assert.assertTrue(releaseList.get(1).isAbandoned()); Assert.assertFalse(releaseList.get(2).isAbandoned()); Assert.assertEquals(user, releaseList.get(0).getDataChangeLastModifiedBy()); Assert.assertEquals(user, releaseList.get(1).getDataChangeLastModifiedBy()); } @Test public void testFindRelease() throws Exception { String someAppId = "1"; String someClusterName = "someClusterName"; String someNamespaceName = "someNamespaceName"; long someReleaseId = 1; String someReleaseKey = "someKey"; String someValidConfiguration = "{\"apollo.bar\": \"foo\"}"; Release someRelease = MockBeanFactory.mockRelease(someReleaseId, someReleaseKey, someAppId, someClusterName, someNamespaceName, someValidConfiguration); when(releaseRepository.findFirstByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(someAppId, someClusterName, someNamespaceName)) .thenReturn(someRelease); Release result = releaseService.findLatestActiveRelease(someAppId, someClusterName, someNamespaceName); verify(releaseRepository, times(1)) .findFirstByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(someAppId, someClusterName, someNamespaceName); assertEquals(someAppId, result.getAppId()); assertEquals(someClusterName, result.getClusterName()); assertEquals(someReleaseId, result.getId()); assertEquals(someReleaseKey, result.getReleaseKey()); assertEquals(someValidConfiguration, result.getConfigurations()); } @Test public void testLoadConfigWithConfigNotFound() throws Exception { String someAppId = "1"; String someClusterName = "someClusterName"; String someNamespaceName = "someNamespaceName"; when(releaseRepository.findFirstByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc(someAppId, someClusterName, someNamespaceName)) .thenReturn(null); Release result = releaseService.findLatestActiveRelease(someAppId, someClusterName, someNamespaceName); assertNull(result); verify(releaseRepository, times(1)).findFirstByAppIdAndClusterNameAndNamespaceNameAndIsAbandonedFalseOrderByIdDesc( someAppId, someClusterName, someNamespaceName); } @Test public void testFindByReleaseIds() throws Exception { Release someRelease = mock(Release.class); Release anotherRelease = mock(Release.class); long someReleaseId = 1; long anotherReleaseId = 2; List<Release> someReleases = Lists.newArrayList(someRelease, anotherRelease); Set<Long> someReleaseIds = Sets.newHashSet(someReleaseId, anotherReleaseId); when(releaseRepository.findAllById(someReleaseIds)).thenReturn(someReleases); List<Release> result = releaseService.findByReleaseIds(someReleaseIds); assertEquals(someReleases, result); } @Test public void testFindByReleaseKeys() throws Exception { Release someRelease = mock(Release.class); Release anotherRelease = mock(Release.class); String someReleaseKey = "key1"; String anotherReleaseKey = "key2"; List<Release> someReleases = Lists.newArrayList(someRelease, anotherRelease); Set<String> someReleaseKeys = Sets.newHashSet(someReleaseKey, anotherReleaseKey); when(releaseRepository.findByReleaseKeyIn(someReleaseKeys)).thenReturn(someReleases); List<Release> result = releaseService.findByReleaseKeys(someReleaseKeys); assertEquals(someReleases, result); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-adminservice/src/main/java/com/ctrip/framework/apollo/adminservice/controller/InstanceConfigController.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.adminservice.controller; import com.ctrip.framework.apollo.biz.entity.Instance; import com.ctrip.framework.apollo.biz.entity.InstanceConfig; import com.ctrip.framework.apollo.biz.entity.Release; import com.ctrip.framework.apollo.biz.service.InstanceService; import com.ctrip.framework.apollo.biz.service.ReleaseService; import com.ctrip.framework.apollo.common.dto.InstanceConfigDTO; import com.ctrip.framework.apollo.common.dto.InstanceDTO; import com.ctrip.framework.apollo.common.dto.PageDTO; import com.ctrip.framework.apollo.common.dto.ReleaseDTO; import com.ctrip.framework.apollo.common.exception.NotFoundException; import com.ctrip.framework.apollo.common.utils.BeanUtils; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.HashMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * @author Jason Song(song_s@ctrip.com) */ @RestController @RequestMapping("/instances") public class InstanceConfigController { private static final Splitter RELEASES_SPLITTER = Splitter.on(",").omitEmptyStrings() .trimResults(); private final ReleaseService releaseService; private final InstanceService instanceService; public InstanceConfigController(final ReleaseService releaseService, final InstanceService instanceService) { this.releaseService = releaseService; this.instanceService = instanceService; } @GetMapping("/by-release") public PageDTO<InstanceDTO> getByRelease(@RequestParam("releaseId") long releaseId, Pageable pageable) { Release release = releaseService.findOne(releaseId); if (release == null) { throw new NotFoundException(String.format("release not found for %s", releaseId)); } Page<InstanceConfig> instanceConfigsPage = instanceService.findActiveInstanceConfigsByReleaseKey (release.getReleaseKey(), pageable); List<InstanceDTO> instanceDTOs = Collections.emptyList(); if (instanceConfigsPage.hasContent()) { Multimap<Long, InstanceConfig> instanceConfigMap = HashMultimap.create(); Set<String> otherReleaseKeys = Sets.newHashSet(); for (InstanceConfig instanceConfig : instanceConfigsPage.getContent()) { instanceConfigMap.put(instanceConfig.getInstanceId(), instanceConfig); otherReleaseKeys.add(instanceConfig.getReleaseKey()); } Set<Long> instanceIds = instanceConfigMap.keySet(); List<Instance> instances = instanceService.findInstancesByIds(instanceIds); if (!CollectionUtils.isEmpty(instances)) { instanceDTOs = BeanUtils.batchTransform(InstanceDTO.class, instances); } for (InstanceDTO instanceDTO : instanceDTOs) { Collection<InstanceConfig> configs = instanceConfigMap.get(instanceDTO.getId()); List<InstanceConfigDTO> configDTOs = configs.stream().map(instanceConfig -> { InstanceConfigDTO instanceConfigDTO = new InstanceConfigDTO(); //to save some space instanceConfigDTO.setRelease(null); instanceConfigDTO.setReleaseDeliveryTime(instanceConfig.getReleaseDeliveryTime()); instanceConfigDTO.setDataChangeLastModifiedTime(instanceConfig .getDataChangeLastModifiedTime()); return instanceConfigDTO; }).collect(Collectors.toList()); instanceDTO.setConfigs(configDTOs); } } return new PageDTO<>(instanceDTOs, pageable, instanceConfigsPage.getTotalElements()); } @GetMapping("/by-namespace-and-releases-not-in") public List<InstanceDTO> getByReleasesNotIn(@RequestParam("appId") String appId, @RequestParam("clusterName") String clusterName, @RequestParam("namespaceName") String namespaceName, @RequestParam("releaseIds") String releaseIds) { Set<Long> releaseIdSet = RELEASES_SPLITTER.splitToList(releaseIds).stream().map(Long::parseLong) .collect(Collectors.toSet()); List<Release> releases = releaseService.findByReleaseIds(releaseIdSet); if (CollectionUtils.isEmpty(releases)) { throw new NotFoundException(String.format("releases not found for %s", releaseIds)); } Set<String> releaseKeys = releases.stream().map(Release::getReleaseKey).collect(Collectors .toSet()); List<InstanceConfig> instanceConfigs = instanceService .findInstanceConfigsByNamespaceWithReleaseKeysNotIn(appId, clusterName, namespaceName, releaseKeys); Multimap<Long, InstanceConfig> instanceConfigMap = HashMultimap.create(); Set<String> otherReleaseKeys = Sets.newHashSet(); for (InstanceConfig instanceConfig : instanceConfigs) { instanceConfigMap.put(instanceConfig.getInstanceId(), instanceConfig); otherReleaseKeys.add(instanceConfig.getReleaseKey()); } List<Instance> instances = instanceService.findInstancesByIds(instanceConfigMap.keySet()); if (CollectionUtils.isEmpty(instances)) { return Collections.emptyList(); } List<InstanceDTO> instanceDTOs = BeanUtils.batchTransform(InstanceDTO.class, instances); List<Release> otherReleases = releaseService.findByReleaseKeys(otherReleaseKeys); Map<String, ReleaseDTO> releaseMap = Maps.newHashMap(); for (Release release : otherReleases) { //unset configurations to save space release.setConfigurations(null); ReleaseDTO releaseDTO = BeanUtils.transform(ReleaseDTO.class, release); releaseMap.put(release.getReleaseKey(), releaseDTO); } for (InstanceDTO instanceDTO : instanceDTOs) { Collection<InstanceConfig> configs = instanceConfigMap.get(instanceDTO.getId()); List<InstanceConfigDTO> configDTOs = configs.stream().map(instanceConfig -> { InstanceConfigDTO instanceConfigDTO = new InstanceConfigDTO(); instanceConfigDTO.setRelease(releaseMap.get(instanceConfig.getReleaseKey())); instanceConfigDTO.setReleaseDeliveryTime(instanceConfig.getReleaseDeliveryTime()); instanceConfigDTO.setDataChangeLastModifiedTime(instanceConfig .getDataChangeLastModifiedTime()); return instanceConfigDTO; }).collect(Collectors.toList()); instanceDTO.setConfigs(configDTOs); } return instanceDTOs; } @GetMapping("/by-namespace") public PageDTO<InstanceDTO> getInstancesByNamespace( @RequestParam("appId") String appId, @RequestParam("clusterName") String clusterName, @RequestParam("namespaceName") String namespaceName, @RequestParam(value = "instanceAppId", required = false) String instanceAppId, Pageable pageable) { Page<Instance> instances; if (Strings.isNullOrEmpty(instanceAppId)) { instances = instanceService.findInstancesByNamespace(appId, clusterName, namespaceName, pageable); } else { instances = instanceService.findInstancesByNamespaceAndInstanceAppId(instanceAppId, appId, clusterName, namespaceName, pageable); } List<InstanceDTO> instanceDTOs = BeanUtils.batchTransform(InstanceDTO.class, instances.getContent()); return new PageDTO<>(instanceDTOs, pageable, instances.getTotalElements()); } @GetMapping("/by-namespace/count") public long getInstancesCountByNamespace(@RequestParam("appId") String appId, @RequestParam("clusterName") String clusterName, @RequestParam("namespaceName") String namespaceName) { Page<Instance> instances = instanceService.findInstancesByNamespace(appId, clusterName, namespaceName, PageRequest.of(0, 1)); return instances.getTotalElements(); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.adminservice.controller; import com.ctrip.framework.apollo.biz.entity.Instance; import com.ctrip.framework.apollo.biz.entity.InstanceConfig; import com.ctrip.framework.apollo.biz.entity.Release; import com.ctrip.framework.apollo.biz.service.InstanceService; import com.ctrip.framework.apollo.biz.service.ReleaseService; import com.ctrip.framework.apollo.common.dto.InstanceConfigDTO; import com.ctrip.framework.apollo.common.dto.InstanceDTO; import com.ctrip.framework.apollo.common.dto.PageDTO; import com.ctrip.framework.apollo.common.dto.ReleaseDTO; import com.ctrip.framework.apollo.common.exception.NotFoundException; import com.ctrip.framework.apollo.common.utils.BeanUtils; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.HashMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * @author Jason Song(song_s@ctrip.com) */ @RestController @RequestMapping("/instances") public class InstanceConfigController { private static final Splitter RELEASES_SPLITTER = Splitter.on(",").omitEmptyStrings() .trimResults(); private final ReleaseService releaseService; private final InstanceService instanceService; public InstanceConfigController(final ReleaseService releaseService, final InstanceService instanceService) { this.releaseService = releaseService; this.instanceService = instanceService; } @GetMapping("/by-release") public PageDTO<InstanceDTO> getByRelease(@RequestParam("releaseId") long releaseId, Pageable pageable) { Release release = releaseService.findOne(releaseId); if (release == null) { throw new NotFoundException(String.format("release not found for %s", releaseId)); } Page<InstanceConfig> instanceConfigsPage = instanceService.findActiveInstanceConfigsByReleaseKey (release.getReleaseKey(), pageable); List<InstanceDTO> instanceDTOs = Collections.emptyList(); if (instanceConfigsPage.hasContent()) { Multimap<Long, InstanceConfig> instanceConfigMap = HashMultimap.create(); Set<String> otherReleaseKeys = Sets.newHashSet(); for (InstanceConfig instanceConfig : instanceConfigsPage.getContent()) { instanceConfigMap.put(instanceConfig.getInstanceId(), instanceConfig); otherReleaseKeys.add(instanceConfig.getReleaseKey()); } Set<Long> instanceIds = instanceConfigMap.keySet(); List<Instance> instances = instanceService.findInstancesByIds(instanceIds); if (!CollectionUtils.isEmpty(instances)) { instanceDTOs = BeanUtils.batchTransform(InstanceDTO.class, instances); } for (InstanceDTO instanceDTO : instanceDTOs) { Collection<InstanceConfig> configs = instanceConfigMap.get(instanceDTO.getId()); List<InstanceConfigDTO> configDTOs = configs.stream().map(instanceConfig -> { InstanceConfigDTO instanceConfigDTO = new InstanceConfigDTO(); //to save some space instanceConfigDTO.setRelease(null); instanceConfigDTO.setReleaseDeliveryTime(instanceConfig.getReleaseDeliveryTime()); instanceConfigDTO.setDataChangeLastModifiedTime(instanceConfig .getDataChangeLastModifiedTime()); return instanceConfigDTO; }).collect(Collectors.toList()); instanceDTO.setConfigs(configDTOs); } } return new PageDTO<>(instanceDTOs, pageable, instanceConfigsPage.getTotalElements()); } @GetMapping("/by-namespace-and-releases-not-in") public List<InstanceDTO> getByReleasesNotIn(@RequestParam("appId") String appId, @RequestParam("clusterName") String clusterName, @RequestParam("namespaceName") String namespaceName, @RequestParam("releaseIds") String releaseIds) { Set<Long> releaseIdSet = RELEASES_SPLITTER.splitToList(releaseIds).stream().map(Long::parseLong) .collect(Collectors.toSet()); List<Release> releases = releaseService.findByReleaseIds(releaseIdSet); if (CollectionUtils.isEmpty(releases)) { throw new NotFoundException(String.format("releases not found for %s", releaseIds)); } Set<String> releaseKeys = releases.stream().map(Release::getReleaseKey).collect(Collectors .toSet()); List<InstanceConfig> instanceConfigs = instanceService .findInstanceConfigsByNamespaceWithReleaseKeysNotIn(appId, clusterName, namespaceName, releaseKeys); Multimap<Long, InstanceConfig> instanceConfigMap = HashMultimap.create(); Set<String> otherReleaseKeys = Sets.newHashSet(); for (InstanceConfig instanceConfig : instanceConfigs) { instanceConfigMap.put(instanceConfig.getInstanceId(), instanceConfig); otherReleaseKeys.add(instanceConfig.getReleaseKey()); } List<Instance> instances = instanceService.findInstancesByIds(instanceConfigMap.keySet()); if (CollectionUtils.isEmpty(instances)) { return Collections.emptyList(); } List<InstanceDTO> instanceDTOs = BeanUtils.batchTransform(InstanceDTO.class, instances); List<Release> otherReleases = releaseService.findByReleaseKeys(otherReleaseKeys); Map<String, ReleaseDTO> releaseMap = Maps.newHashMap(); for (Release release : otherReleases) { //unset configurations to save space release.setConfigurations(null); ReleaseDTO releaseDTO = BeanUtils.transform(ReleaseDTO.class, release); releaseMap.put(release.getReleaseKey(), releaseDTO); } for (InstanceDTO instanceDTO : instanceDTOs) { Collection<InstanceConfig> configs = instanceConfigMap.get(instanceDTO.getId()); List<InstanceConfigDTO> configDTOs = configs.stream().map(instanceConfig -> { InstanceConfigDTO instanceConfigDTO = new InstanceConfigDTO(); instanceConfigDTO.setRelease(releaseMap.get(instanceConfig.getReleaseKey())); instanceConfigDTO.setReleaseDeliveryTime(instanceConfig.getReleaseDeliveryTime()); instanceConfigDTO.setDataChangeLastModifiedTime(instanceConfig .getDataChangeLastModifiedTime()); return instanceConfigDTO; }).collect(Collectors.toList()); instanceDTO.setConfigs(configDTOs); } return instanceDTOs; } @GetMapping("/by-namespace") public PageDTO<InstanceDTO> getInstancesByNamespace( @RequestParam("appId") String appId, @RequestParam("clusterName") String clusterName, @RequestParam("namespaceName") String namespaceName, @RequestParam(value = "instanceAppId", required = false) String instanceAppId, Pageable pageable) { Page<Instance> instances; if (Strings.isNullOrEmpty(instanceAppId)) { instances = instanceService.findInstancesByNamespace(appId, clusterName, namespaceName, pageable); } else { instances = instanceService.findInstancesByNamespaceAndInstanceAppId(instanceAppId, appId, clusterName, namespaceName, pageable); } List<InstanceDTO> instanceDTOs = BeanUtils.batchTransform(InstanceDTO.class, instances.getContent()); return new PageDTO<>(instanceDTOs, pageable, instances.getTotalElements()); } @GetMapping("/by-namespace/count") public long getInstancesCountByNamespace(@RequestParam("appId") String appId, @RequestParam("clusterName") String clusterName, @RequestParam("namespaceName") String namespaceName) { Page<Instance> instances = instanceService.findInstancesByNamespace(appId, clusterName, namespaceName, PageRequest.of(0, 1)); return instances.getTotalElements(); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/ldap/LdapUserService.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.ldap; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toCollection; import static org.springframework.ldap.query.LdapQueryBuilder.query; import com.ctrip.framework.apollo.portal.entity.bo.UserInfo; import com.ctrip.framework.apollo.portal.spi.UserService; import com.ctrip.framework.apollo.portal.spi.configuration.LdapExtendProperties; import com.ctrip.framework.apollo.portal.spi.configuration.LdapProperties; import com.google.common.base.Strings; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.naming.directory.Attribute; import javax.naming.ldap.LdapName; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.ldap.core.AttributesMapper; import org.springframework.ldap.core.ContextMapper; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.query.ContainerCriteria; import org.springframework.ldap.query.SearchScope; import org.springframework.ldap.support.LdapUtils; import org.springframework.util.CollectionUtils; /** * Ldap user spi service * * Support OpenLdap,ApacheDS,ActiveDirectory use {@link LdapTemplate} as underlying implementation * * @author xm.lin xm.lin@anxincloud.com * @author idefav * @Description ldap user service * @date 18-8-9 下午4:42 */ public class LdapUserService implements UserService { @Autowired private LdapProperties ldapProperties; @Autowired private LdapExtendProperties ldapExtendProperties; /** * ldap search base */ @Value("${spring.ldap.base}") private String base; /** * user objectClass */ @Value("${ldap.mapping.objectClass}") private String objectClassAttrName; /** * user LoginId */ @Value("${ldap.mapping.loginId}") private String loginIdAttrName; /** * user displayName */ @Value("${ldap.mapping.userDisplayName}") private String userDisplayNameAttrName; /** * email */ @Value("${ldap.mapping.email}") private String emailAttrName; /** * rdn */ @Value("${ldap.mapping.rdnKey:}") private String rdnKey; /** * memberOf */ @Value("#{'${ldap.filter.memberOf:}'.split('\\|')}") private String[] memberOf; /** * group search base */ @Value("${ldap.group.groupBase:}") private String groupBase; /** * group filter eg. (&(cn=apollo-admins)(&(member=*))) */ @Value("${ldap.group.groupSearch:}") private String groupSearch; /** * group memberShip eg. member */ @Value("${ldap.group.groupMembership:}") private String groupMembershipAttrName; @Autowired private LdapTemplate ldapTemplate; private static final String MEMBER_OF_ATTR_NAME = "memberOf"; private static final String MEMBER_UID_ATTR_NAME = "memberUid"; /** * 用户信息Mapper */ private ContextMapper<UserInfo> ldapUserInfoMapper = (ctx) -> { DirContextAdapter contextAdapter = (DirContextAdapter) ctx; UserInfo userInfo = new UserInfo(); userInfo.setUserId(contextAdapter.getStringAttribute(loginIdAttrName)); userInfo.setName(contextAdapter.getStringAttribute(userDisplayNameAttrName)); userInfo.setEmail(contextAdapter.getStringAttribute(emailAttrName)); return userInfo; }; /** * 查询条件 */ private ContainerCriteria ldapQueryCriteria() { ContainerCriteria criteria = query() .searchScope(SearchScope.SUBTREE) .where("objectClass").is(objectClassAttrName); if (memberOf.length > 0 && !StringUtils.isEmpty(memberOf[0])) { ContainerCriteria memberOfFilters = query().where(MEMBER_OF_ATTR_NAME).is(memberOf[0]); Arrays.stream(memberOf).skip(1) .forEach(filter -> memberOfFilters.or(MEMBER_OF_ATTR_NAME).is(filter)); criteria.and(memberOfFilters); } return criteria; } /** * 根据entryDN查找用户信息 * * @param member ldap EntryDN * @param userIds 用户ID列表 */ private UserInfo lookupUser(String member, List<String> userIds) { return ldapTemplate.lookup(member, (AttributesMapper<UserInfo>) attributes -> { UserInfo tmp = new UserInfo(); Attribute emailAttribute = attributes.get(emailAttrName); if (emailAttribute != null && emailAttribute.get() != null) { tmp.setEmail(emailAttribute.get().toString()); } Attribute loginIdAttribute = attributes.get(loginIdAttrName); if (loginIdAttribute != null && loginIdAttribute.get() != null) { tmp.setUserId(loginIdAttribute.get().toString()); } Attribute userDisplayNameAttribute = attributes.get(userDisplayNameAttrName); if (userDisplayNameAttribute != null && userDisplayNameAttribute.get() != null) { tmp.setName(userDisplayNameAttribute.get().toString()); } if (userIds != null) { if (userIds.stream().anyMatch(c -> c.equals(tmp.getUserId()))) { return tmp; } return null; } return tmp; }); } private UserInfo searchUserById(String userId) { try { return ldapTemplate.searchForObject(query().where(loginIdAttrName).is(userId), ctx -> { UserInfo userInfo = new UserInfo(); DirContextAdapter contextAdapter = (DirContextAdapter) ctx; userInfo.setEmail(contextAdapter.getStringAttribute(emailAttrName)); userInfo.setName(contextAdapter.getStringAttribute(userDisplayNameAttrName)); userInfo.setUserId(contextAdapter.getStringAttribute(loginIdAttrName)); return userInfo; }); } catch (EmptyResultDataAccessException ex) { // EmptyResultDataAccessException means no record found return null; } } /** * 按照group搜索用户 * * @param groupBase group search base * @param groupSearch group filter * @param keyword user search keywords * @param userIds user id list */ private List<UserInfo> searchUserInfoByGroup(String groupBase, String groupSearch, String keyword, List<String> userIds) { return ldapTemplate .searchForObject(groupBase, groupSearch, ctx -> { List<UserInfo> userInfos = new ArrayList<>(); if (!MEMBER_UID_ATTR_NAME.equals(groupMembershipAttrName)) { String[] members = ((DirContextAdapter) ctx).getStringAttributes(groupMembershipAttrName); for (String item : members) { LdapName ldapName = LdapUtils.newLdapName(item); LdapName memberRdn = LdapUtils.removeFirst(ldapName, LdapUtils.newLdapName(base)); if (keyword != null) { String rdnValue = LdapUtils.getValue(memberRdn, rdnKey).toString(); if (rdnValue.toLowerCase().contains(keyword.toLowerCase())) { UserInfo userInfo = lookupUser(memberRdn.toString(), userIds); userInfos.add(userInfo); } } else { UserInfo userInfo = lookupUser(memberRdn.toString(), userIds); if (userInfo != null) { userInfos.add(userInfo); } } } return userInfos; } Set<String> memberUids = Sets.newHashSet(((DirContextAdapter) ctx) .getStringAttributes(groupMembershipAttrName)); if (!CollectionUtils.isEmpty(userIds)) { memberUids = Sets.intersection(memberUids, Sets.newHashSet(userIds)); } for (String memberUid : memberUids) { UserInfo userInfo = searchUserById(memberUid); if (userInfo != null) { if (keyword != null) { if (userInfo.getUserId().toLowerCase().contains(keyword.toLowerCase())) { userInfos.add(userInfo); } } else { userInfos.add(userInfo); } } } return userInfos; }); } @Override public List<UserInfo> searchUsers(String keyword, int offset, int limit) { List<UserInfo> users = new ArrayList<>(); if (StringUtils.isNotBlank(groupSearch)) { List<UserInfo> userListByGroup = searchUserInfoByGroup(groupBase, groupSearch, keyword, null); users.addAll(userListByGroup); return users.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>((o1, o2) -> { if (o1.getUserId().equals(o2.getUserId())) { return 0; } return -1; })), ArrayList::new)); } ContainerCriteria criteria = ldapQueryCriteria(); if (!Strings.isNullOrEmpty(keyword)) { criteria.and(query().where(loginIdAttrName).like(keyword + "*").or(userDisplayNameAttrName) .like(keyword + "*")); } users = ldapTemplate.search(criteria, ldapUserInfoMapper); return users; } @Override public UserInfo findByUserId(String userId) { if (StringUtils.isNotBlank(groupSearch)) { List<UserInfo> lists = searchUserInfoByGroup(groupBase, groupSearch, null, Collections.singletonList(userId)); if (lists != null && !lists.isEmpty() && lists.get(0) != null) { return lists.get(0); } return null; } try { return ldapTemplate .searchForObject(ldapQueryCriteria().and(loginIdAttrName).is(userId), ldapUserInfoMapper); } catch (EmptyResultDataAccessException ex) { // EmptyResultDataAccessException means no record found return null; } } @Override public List<UserInfo> findByUserIds(List<String> userIds) { if (CollectionUtils.isEmpty(userIds)) { return Collections.emptyList(); } if (StringUtils.isNotBlank(groupSearch)) { List<UserInfo> userListByGroup = searchUserInfoByGroup(groupBase, groupSearch, null, userIds); return userListByGroup; } ContainerCriteria criteria = query().where(loginIdAttrName).is(userIds.get(0)); userIds.stream().skip(1).forEach(userId -> criteria.or(loginIdAttrName).is(userId)); return ldapTemplate.search(ldapQueryCriteria().and(criteria), ldapUserInfoMapper); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.ldap; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toCollection; import static org.springframework.ldap.query.LdapQueryBuilder.query; import com.ctrip.framework.apollo.portal.entity.bo.UserInfo; import com.ctrip.framework.apollo.portal.spi.UserService; import com.ctrip.framework.apollo.portal.spi.configuration.LdapExtendProperties; import com.ctrip.framework.apollo.portal.spi.configuration.LdapProperties; import com.google.common.base.Strings; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.naming.directory.Attribute; import javax.naming.ldap.LdapName; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.ldap.core.AttributesMapper; import org.springframework.ldap.core.ContextMapper; import org.springframework.ldap.core.DirContextAdapter; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.query.ContainerCriteria; import org.springframework.ldap.query.SearchScope; import org.springframework.ldap.support.LdapUtils; import org.springframework.util.CollectionUtils; /** * Ldap user spi service * * Support OpenLdap,ApacheDS,ActiveDirectory use {@link LdapTemplate} as underlying implementation * * @author xm.lin xm.lin@anxincloud.com * @author idefav * @Description ldap user service * @date 18-8-9 下午4:42 */ public class LdapUserService implements UserService { @Autowired private LdapProperties ldapProperties; @Autowired private LdapExtendProperties ldapExtendProperties; /** * ldap search base */ @Value("${spring.ldap.base}") private String base; /** * user objectClass */ @Value("${ldap.mapping.objectClass}") private String objectClassAttrName; /** * user LoginId */ @Value("${ldap.mapping.loginId}") private String loginIdAttrName; /** * user displayName */ @Value("${ldap.mapping.userDisplayName}") private String userDisplayNameAttrName; /** * email */ @Value("${ldap.mapping.email}") private String emailAttrName; /** * rdn */ @Value("${ldap.mapping.rdnKey:}") private String rdnKey; /** * memberOf */ @Value("#{'${ldap.filter.memberOf:}'.split('\\|')}") private String[] memberOf; /** * group search base */ @Value("${ldap.group.groupBase:}") private String groupBase; /** * group filter eg. (&(cn=apollo-admins)(&(member=*))) */ @Value("${ldap.group.groupSearch:}") private String groupSearch; /** * group memberShip eg. member */ @Value("${ldap.group.groupMembership:}") private String groupMembershipAttrName; @Autowired private LdapTemplate ldapTemplate; private static final String MEMBER_OF_ATTR_NAME = "memberOf"; private static final String MEMBER_UID_ATTR_NAME = "memberUid"; /** * 用户信息Mapper */ private ContextMapper<UserInfo> ldapUserInfoMapper = (ctx) -> { DirContextAdapter contextAdapter = (DirContextAdapter) ctx; UserInfo userInfo = new UserInfo(); userInfo.setUserId(contextAdapter.getStringAttribute(loginIdAttrName)); userInfo.setName(contextAdapter.getStringAttribute(userDisplayNameAttrName)); userInfo.setEmail(contextAdapter.getStringAttribute(emailAttrName)); return userInfo; }; /** * 查询条件 */ private ContainerCriteria ldapQueryCriteria() { ContainerCriteria criteria = query() .searchScope(SearchScope.SUBTREE) .where("objectClass").is(objectClassAttrName); if (memberOf.length > 0 && !StringUtils.isEmpty(memberOf[0])) { ContainerCriteria memberOfFilters = query().where(MEMBER_OF_ATTR_NAME).is(memberOf[0]); Arrays.stream(memberOf).skip(1) .forEach(filter -> memberOfFilters.or(MEMBER_OF_ATTR_NAME).is(filter)); criteria.and(memberOfFilters); } return criteria; } /** * 根据entryDN查找用户信息 * * @param member ldap EntryDN * @param userIds 用户ID列表 */ private UserInfo lookupUser(String member, List<String> userIds) { return ldapTemplate.lookup(member, (AttributesMapper<UserInfo>) attributes -> { UserInfo tmp = new UserInfo(); Attribute emailAttribute = attributes.get(emailAttrName); if (emailAttribute != null && emailAttribute.get() != null) { tmp.setEmail(emailAttribute.get().toString()); } Attribute loginIdAttribute = attributes.get(loginIdAttrName); if (loginIdAttribute != null && loginIdAttribute.get() != null) { tmp.setUserId(loginIdAttribute.get().toString()); } Attribute userDisplayNameAttribute = attributes.get(userDisplayNameAttrName); if (userDisplayNameAttribute != null && userDisplayNameAttribute.get() != null) { tmp.setName(userDisplayNameAttribute.get().toString()); } if (userIds != null) { if (userIds.stream().anyMatch(c -> c.equals(tmp.getUserId()))) { return tmp; } return null; } return tmp; }); } private UserInfo searchUserById(String userId) { try { return ldapTemplate.searchForObject(query().where(loginIdAttrName).is(userId), ctx -> { UserInfo userInfo = new UserInfo(); DirContextAdapter contextAdapter = (DirContextAdapter) ctx; userInfo.setEmail(contextAdapter.getStringAttribute(emailAttrName)); userInfo.setName(contextAdapter.getStringAttribute(userDisplayNameAttrName)); userInfo.setUserId(contextAdapter.getStringAttribute(loginIdAttrName)); return userInfo; }); } catch (EmptyResultDataAccessException ex) { // EmptyResultDataAccessException means no record found return null; } } /** * 按照group搜索用户 * * @param groupBase group search base * @param groupSearch group filter * @param keyword user search keywords * @param userIds user id list */ private List<UserInfo> searchUserInfoByGroup(String groupBase, String groupSearch, String keyword, List<String> userIds) { return ldapTemplate .searchForObject(groupBase, groupSearch, ctx -> { List<UserInfo> userInfos = new ArrayList<>(); if (!MEMBER_UID_ATTR_NAME.equals(groupMembershipAttrName)) { String[] members = ((DirContextAdapter) ctx).getStringAttributes(groupMembershipAttrName); for (String item : members) { LdapName ldapName = LdapUtils.newLdapName(item); LdapName memberRdn = LdapUtils.removeFirst(ldapName, LdapUtils.newLdapName(base)); if (keyword != null) { String rdnValue = LdapUtils.getValue(memberRdn, rdnKey).toString(); if (rdnValue.toLowerCase().contains(keyword.toLowerCase())) { UserInfo userInfo = lookupUser(memberRdn.toString(), userIds); userInfos.add(userInfo); } } else { UserInfo userInfo = lookupUser(memberRdn.toString(), userIds); if (userInfo != null) { userInfos.add(userInfo); } } } return userInfos; } Set<String> memberUids = Sets.newHashSet(((DirContextAdapter) ctx) .getStringAttributes(groupMembershipAttrName)); if (!CollectionUtils.isEmpty(userIds)) { memberUids = Sets.intersection(memberUids, Sets.newHashSet(userIds)); } for (String memberUid : memberUids) { UserInfo userInfo = searchUserById(memberUid); if (userInfo != null) { if (keyword != null) { if (userInfo.getUserId().toLowerCase().contains(keyword.toLowerCase())) { userInfos.add(userInfo); } } else { userInfos.add(userInfo); } } } return userInfos; }); } @Override public List<UserInfo> searchUsers(String keyword, int offset, int limit) { List<UserInfo> users = new ArrayList<>(); if (StringUtils.isNotBlank(groupSearch)) { List<UserInfo> userListByGroup = searchUserInfoByGroup(groupBase, groupSearch, keyword, null); users.addAll(userListByGroup); return users.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>((o1, o2) -> { if (o1.getUserId().equals(o2.getUserId())) { return 0; } return -1; })), ArrayList::new)); } ContainerCriteria criteria = ldapQueryCriteria(); if (!Strings.isNullOrEmpty(keyword)) { criteria.and(query().where(loginIdAttrName).like(keyword + "*").or(userDisplayNameAttrName) .like(keyword + "*")); } users = ldapTemplate.search(criteria, ldapUserInfoMapper); return users; } @Override public UserInfo findByUserId(String userId) { if (StringUtils.isNotBlank(groupSearch)) { List<UserInfo> lists = searchUserInfoByGroup(groupBase, groupSearch, null, Collections.singletonList(userId)); if (lists != null && !lists.isEmpty() && lists.get(0) != null) { return lists.get(0); } return null; } try { return ldapTemplate .searchForObject(ldapQueryCriteria().and(loginIdAttrName).is(userId), ldapUserInfoMapper); } catch (EmptyResultDataAccessException ex) { // EmptyResultDataAccessException means no record found return null; } } @Override public List<UserInfo> findByUserIds(List<String> userIds) { if (CollectionUtils.isEmpty(userIds)) { return Collections.emptyList(); } if (StringUtils.isNotBlank(groupSearch)) { List<UserInfo> userListByGroup = searchUserInfoByGroup(groupBase, groupSearch, null, userIds); return userListByGroup; } ContainerCriteria criteria = query().where(loginIdAttrName).is(userIds.get(0)); userIds.stream().skip(1).forEach(userId -> criteria.or(loginIdAttrName).is(userId)); return ldapTemplate.search(ldapQueryCriteria().and(criteria), ldapUserInfoMapper); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Release.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.entity; import com.ctrip.framework.apollo.common.entity.BaseEntity; import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.Where; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Lob; import javax.persistence.Table; /** * @author Jason Song(song_s@ctrip.com) */ @Entity @Table(name = "Release") @SQLDelete(sql = "Update Release set isDeleted = 1 where id = ?") @Where(clause = "isDeleted = 0") public class Release extends BaseEntity { @Column(name = "ReleaseKey", nullable = false) private String releaseKey; @Column(name = "Name", nullable = false) private String name; @Column(name = "AppId", nullable = false) private String appId; @Column(name = "ClusterName", nullable = false) private String clusterName; @Column(name = "NamespaceName", nullable = false) private String namespaceName; @Column(name = "Configurations", nullable = false) @Lob private String configurations; @Column(name = "Comment", nullable = false) private String comment; @Column(name = "IsAbandoned", columnDefinition = "Bit default '0'") private boolean isAbandoned; public String getReleaseKey() { return releaseKey; } public String getAppId() { return appId; } public String getClusterName() { return clusterName; } public String getComment() { return comment; } public String getConfigurations() { return configurations; } public String getNamespaceName() { return namespaceName; } public String getName() { return name; } public void setReleaseKey(String releaseKey) { this.releaseKey = releaseKey; } public void setAppId(String appId) { this.appId = appId; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public void setComment(String comment) { this.comment = comment; } public void setConfigurations(String configurations) { this.configurations = configurations; } public void setNamespaceName(String namespaceName) { this.namespaceName = namespaceName; } public void setName(String name) { this.name = name; } public boolean isAbandoned() { return isAbandoned; } public void setAbandoned(boolean abandoned) { isAbandoned = abandoned; } public String toString() { return toStringHelper().add("name", name).add("appId", appId).add("clusterName", clusterName) .add("namespaceName", namespaceName).add("configurations", configurations) .add("comment", comment).add("isAbandoned", isAbandoned).toString(); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.entity; import com.ctrip.framework.apollo.common.entity.BaseEntity; import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.Where; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Lob; import javax.persistence.Table; /** * @author Jason Song(song_s@ctrip.com) */ @Entity @Table(name = "Release") @SQLDelete(sql = "Update Release set isDeleted = 1 where id = ?") @Where(clause = "isDeleted = 0") public class Release extends BaseEntity { @Column(name = "ReleaseKey", nullable = false) private String releaseKey; @Column(name = "Name", nullable = false) private String name; @Column(name = "AppId", nullable = false) private String appId; @Column(name = "ClusterName", nullable = false) private String clusterName; @Column(name = "NamespaceName", nullable = false) private String namespaceName; @Column(name = "Configurations", nullable = false) @Lob private String configurations; @Column(name = "Comment", nullable = false) private String comment; @Column(name = "IsAbandoned", columnDefinition = "Bit default '0'") private boolean isAbandoned; public String getReleaseKey() { return releaseKey; } public String getAppId() { return appId; } public String getClusterName() { return clusterName; } public String getComment() { return comment; } public String getConfigurations() { return configurations; } public String getNamespaceName() { return namespaceName; } public String getName() { return name; } public void setReleaseKey(String releaseKey) { this.releaseKey = releaseKey; } public void setAppId(String appId) { this.appId = appId; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public void setComment(String comment) { this.comment = comment; } public void setConfigurations(String configurations) { this.configurations = configurations; } public void setNamespaceName(String namespaceName) { this.namespaceName = namespaceName; } public void setName(String name) { this.name = name; } public boolean isAbandoned() { return isAbandoned; } public void setAbandoned(boolean abandoned) { isAbandoned = abandoned; } public String toString() { return toStringHelper().add("name", name).add("appId", appId).add("clusterName", clusterName) .add("namespaceName", namespaceName).add("configurations", configurations) .add("comment", comment).add("isAbandoned", isAbandoned).toString(); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-client/src/test/java/com/ctrip/framework/apollo/util/yaml/YamlParserTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.util.yaml; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.ctrip.framework.apollo.build.MockInjector; import com.ctrip.framework.apollo.util.OrderedProperties; import com.ctrip.framework.apollo.util.factory.PropertiesFactory; import com.google.common.base.Charsets; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.util.Properties; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.core.io.ByteArrayResource; import org.yaml.snakeyaml.constructor.ConstructorException; import org.yaml.snakeyaml.parser.ParserException; public class YamlParserTest { private YamlParser parser; @Before public void setUp() throws Exception { parser = new YamlParser(); } @After public void tearDown() throws Exception { MockInjector.reset(); } @Test public void testValidCases() throws Exception { test("case1.yaml"); test("case3.yaml"); test("case4.yaml"); test("case5.yaml"); test("case6.yaml"); test("case7.yaml"); } @Test(expected = ParserException.class) public void testcase2() throws Exception { testInvalid("case2.yaml"); } @Test(expected = ParserException.class) public void testcase8() throws Exception { testInvalid("case8.yaml"); } @Test(expected = ConstructorException.class) public void testcase9() throws Exception { testInvalid("case9.yaml"); } @Test public void testOrderProperties() throws IOException { String yamlContent = loadYaml("orderedcase.yaml"); Properties nonOrderedProperties = parser.yamlToProperties(yamlContent); PropertiesFactory propertiesFactory = mock(PropertiesFactory.class); when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() { @Override public Properties answer(InvocationOnMock invocation) { return new OrderedProperties(); } }); MockInjector.setInstance(PropertiesFactory.class, propertiesFactory); parser = new YamlParser(); Properties orderedProperties = parser.yamlToProperties(yamlContent); assertTrue(orderedProperties instanceof OrderedProperties); checkPropertiesEquals(nonOrderedProperties, orderedProperties); String[] propertyNames = orderedProperties.stringPropertyNames().toArray(new String[0]); assertEquals("k2", propertyNames[0]); assertEquals("k4", propertyNames[1]); assertEquals("k1", propertyNames[2]); } private void test(String caseName) throws Exception { String yamlContent = loadYaml(caseName); check(yamlContent); } private String loadYaml(String caseName) throws IOException { File file = new File("src/test/resources/yaml/" + caseName); return Files.toString(file, Charsets.UTF_8); } private void testInvalid(String caseName) throws Exception { File file = new File("src/test/resources/yaml/" + caseName); String yamlContent = Files.toString(file, Charsets.UTF_8); parser.yamlToProperties(yamlContent); } private void check(String yamlContent) { YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean(); yamlPropertiesFactoryBean.setResources(new ByteArrayResource(yamlContent.getBytes())); Properties expected = yamlPropertiesFactoryBean.getObject(); Properties actual = parser.yamlToProperties(yamlContent); assertTrue("expected: " + expected + " actual: " + actual, checkPropertiesEquals(expected, actual)); } private boolean checkPropertiesEquals(Properties expected, Properties actual) { if (expected == actual) return true; if (expected.size() != actual.size()) return false; for (Object key : expected.keySet()) { if (!expected.getProperty((String) key).equals(actual.getProperty((String) key))) { return false; } } return true; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.util.yaml; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.ctrip.framework.apollo.build.MockInjector; import com.ctrip.framework.apollo.util.OrderedProperties; import com.ctrip.framework.apollo.util.factory.PropertiesFactory; import com.google.common.base.Charsets; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.util.Properties; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.core.io.ByteArrayResource; import org.yaml.snakeyaml.constructor.ConstructorException; import org.yaml.snakeyaml.parser.ParserException; public class YamlParserTest { private YamlParser parser; @Before public void setUp() throws Exception { parser = new YamlParser(); } @After public void tearDown() throws Exception { MockInjector.reset(); } @Test public void testValidCases() throws Exception { test("case1.yaml"); test("case3.yaml"); test("case4.yaml"); test("case5.yaml"); test("case6.yaml"); test("case7.yaml"); } @Test(expected = ParserException.class) public void testcase2() throws Exception { testInvalid("case2.yaml"); } @Test(expected = ParserException.class) public void testcase8() throws Exception { testInvalid("case8.yaml"); } @Test(expected = ConstructorException.class) public void testcase9() throws Exception { testInvalid("case9.yaml"); } @Test public void testOrderProperties() throws IOException { String yamlContent = loadYaml("orderedcase.yaml"); Properties nonOrderedProperties = parser.yamlToProperties(yamlContent); PropertiesFactory propertiesFactory = mock(PropertiesFactory.class); when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() { @Override public Properties answer(InvocationOnMock invocation) { return new OrderedProperties(); } }); MockInjector.setInstance(PropertiesFactory.class, propertiesFactory); parser = new YamlParser(); Properties orderedProperties = parser.yamlToProperties(yamlContent); assertTrue(orderedProperties instanceof OrderedProperties); checkPropertiesEquals(nonOrderedProperties, orderedProperties); String[] propertyNames = orderedProperties.stringPropertyNames().toArray(new String[0]); assertEquals("k2", propertyNames[0]); assertEquals("k4", propertyNames[1]); assertEquals("k1", propertyNames[2]); } private void test(String caseName) throws Exception { String yamlContent = loadYaml(caseName); check(yamlContent); } private String loadYaml(String caseName) throws IOException { File file = new File("src/test/resources/yaml/" + caseName); return Files.toString(file, Charsets.UTF_8); } private void testInvalid(String caseName) throws Exception { File file = new File("src/test/resources/yaml/" + caseName); String yamlContent = Files.toString(file, Charsets.UTF_8); parser.yamlToProperties(yamlContent); } private void check(String yamlContent) { YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean(); yamlPropertiesFactoryBean.setResources(new ByteArrayResource(yamlContent.getBytes())); Properties expected = yamlPropertiesFactoryBean.getObject(); Properties actual = parser.yamlToProperties(yamlContent); assertTrue("expected: " + expected + " actual: " + actual, checkPropertiesEquals(expected, actual)); } private boolean checkPropertiesEquals(Properties expected, Properties actual) { if (expected == actual) return true; if (expected.size() != actual.size()) return false; for (Object key : expected.keySet()) { if (!expected.getProperty((String) key).equals(actual.getProperty((String) key))) { return false; } } return true; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/repository/PermissionRepository.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.repository; import com.ctrip.framework.apollo.portal.entity.po.Permission; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import java.util.Collection; import java.util.List; /** * @author Jason Song(song_s@ctrip.com) */ public interface PermissionRepository extends PagingAndSortingRepository<Permission, Long> { /** * find permission by permission type and targetId */ Permission findTopByPermissionTypeAndTargetId(String permissionType, String targetId); /** * find permissions by permission types and targetId */ List<Permission> findByPermissionTypeInAndTargetId(Collection<String> permissionTypes, String targetId); @Query("SELECT p.id from Permission p where p.targetId = ?1 or p.targetId like CONCAT(?1, '+%')") List<Long> findPermissionIdsByAppId(String appId); @Query("SELECT p.id from Permission p where p.targetId = CONCAT(?1, '+', ?2)") List<Long> findPermissionIdsByAppIdAndNamespace(String appId, String namespaceName); @Modifying @Query("UPDATE Permission SET IsDeleted=1, DataChange_LastModifiedBy = ?2 WHERE Id in ?1") Integer batchDelete(List<Long> permissionIds, String operator); }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.repository; import com.ctrip.framework.apollo.portal.entity.po.Permission; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import java.util.Collection; import java.util.List; /** * @author Jason Song(song_s@ctrip.com) */ public interface PermissionRepository extends PagingAndSortingRepository<Permission, Long> { /** * find permission by permission type and targetId */ Permission findTopByPermissionTypeAndTargetId(String permissionType, String targetId); /** * find permissions by permission types and targetId */ List<Permission> findByPermissionTypeInAndTargetId(Collection<String> permissionTypes, String targetId); @Query("SELECT p.id from Permission p where p.targetId = ?1 or p.targetId like CONCAT(?1, '+%')") List<Long> findPermissionIdsByAppId(String appId); @Query("SELECT p.id from Permission p where p.targetId = CONCAT(?1, '+', ?2)") List<Long> findPermissionIdsByAppIdAndNamespace(String appId, String namespaceName); @Modifying @Query("UPDATE Permission SET IsDeleted=1, DataChange_LastModifiedBy = ?2 WHERE Id in ?1") Integer batchDelete(List<Long> permissionIds, String operator); }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/ByteUtilTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.core.utils; import com.ctrip.framework.apollo.core.utils.ByteUtil; import org.junit.Assert; import org.junit.Test; public class ByteUtilTest { @Test public void testInt3() { Assert.assertEquals((byte)0, ByteUtil.int3(0)); Assert.assertEquals((byte)0, ByteUtil.int3(1)); } @Test public void testInt2() { Assert.assertEquals((byte)0, ByteUtil.int2(0)); Assert.assertEquals((byte)0, ByteUtil.int2(1)); } @Test public void testInt1() { Assert.assertEquals((byte)0, ByteUtil.int1(0)); Assert.assertEquals((byte)0, ByteUtil.int1(1)); } @Test public void testInt0() { Assert.assertEquals((byte)0, ByteUtil.int0(0)); Assert.assertEquals((byte)1, ByteUtil.int0(1)); } @Test public void testToHexString() { Assert.assertEquals("", ByteUtil.toHexString(new byte[] {})); Assert.assertEquals("98", ByteUtil.toHexString(new byte[] {(byte)-104})); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.core.utils; import com.ctrip.framework.apollo.core.utils.ByteUtil; import org.junit.Assert; import org.junit.Test; public class ByteUtilTest { @Test public void testInt3() { Assert.assertEquals((byte)0, ByteUtil.int3(0)); Assert.assertEquals((byte)0, ByteUtil.int3(1)); } @Test public void testInt2() { Assert.assertEquals((byte)0, ByteUtil.int2(0)); Assert.assertEquals((byte)0, ByteUtil.int2(1)); } @Test public void testInt1() { Assert.assertEquals((byte)0, ByteUtil.int1(0)); Assert.assertEquals((byte)0, ByteUtil.int1(1)); } @Test public void testInt0() { Assert.assertEquals((byte)0, ByteUtil.int0(0)); Assert.assertEquals((byte)1, ByteUtil.int0(1)); } @Test public void testToHexString() { Assert.assertEquals("", ByteUtil.toHexString(new byte[] {})); Assert.assertEquals("98", ByteUtil.toHexString(new byte[] {(byte)-104})); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/listener/ApolloDeferredLoggerApplicationListener.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.config.data.listener; import com.ctrip.framework.apollo.core.utils.DeferredLogger; import org.springframework.boot.context.event.ApplicationContextInitializedEvent; import org.springframework.boot.context.event.ApplicationFailedEvent; import org.springframework.boot.context.event.SpringApplicationEvent; import org.springframework.context.ApplicationListener; /** * @author vdisk <vdisk@foxmail.com> */ public class ApolloDeferredLoggerApplicationListener implements ApplicationListener<SpringApplicationEvent> { @Override public void onApplicationEvent(SpringApplicationEvent event) { if (event instanceof ApplicationContextInitializedEvent) { DeferredLogger.replayTo(); } if (event instanceof ApplicationFailedEvent) { DeferredLogger.replayTo(); } } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.config.data.listener; import com.ctrip.framework.apollo.core.utils.DeferredLogger; import org.springframework.boot.context.event.ApplicationContextInitializedEvent; import org.springframework.boot.context.event.ApplicationFailedEvent; import org.springframework.boot.context.event.SpringApplicationEvent; import org.springframework.context.ApplicationListener; /** * @author vdisk <vdisk@foxmail.com> */ public class ApolloDeferredLoggerApplicationListener implements ApplicationListener<SpringApplicationEvent> { @Override public void onApplicationEvent(SpringApplicationEvent event) { if (event instanceof ApplicationContextInitializedEvent) { DeferredLogger.replayTo(); } if (event instanceof ApplicationFailedEvent) { DeferredLogger.replayTo(); } } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/defaultimpl/DefaultMQService.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.defaultimpl; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO; import com.ctrip.framework.apollo.portal.spi.MQService; public class DefaultMQService implements MQService{ @Override public void sendPublishMsg(Env env, ReleaseHistoryBO releaseHistory) { //do nothing } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.defaultimpl; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO; import com.ctrip.framework.apollo.portal.spi.MQService; public class DefaultMQService implements MQService{ @Override public void sendPublishMsg(Env env, ReleaseHistoryBO releaseHistory) { //do nothing } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-demo/src/main/java/com/ctrip/framework/apollo/demo/api/ApolloConfigDemo.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.demo.api; import com.ctrip.framework.apollo.internals.YamlConfigFile; import com.google.common.base.Charsets; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigChangeListener; import com.ctrip.framework.apollo.ConfigFile; import com.ctrip.framework.apollo.ConfigFileChangeListener; import com.ctrip.framework.apollo.ConfigService; import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; import com.ctrip.framework.apollo.model.ConfigChange; import com.ctrip.framework.apollo.model.ConfigChangeEvent; import com.ctrip.framework.apollo.model.ConfigFileChangeEvent; import com.ctrip.framework.foundation.Foundation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author Jason Song(song_s@ctrip.com) */ public class ApolloConfigDemo { private static final Logger logger = LoggerFactory.getLogger(ApolloConfigDemo.class); private String DEFAULT_VALUE = "undefined"; private Config config; private Config yamlConfig; private Config publicConfig; private ConfigFile applicationConfigFile; private ConfigFile xmlConfigFile; private YamlConfigFile yamlConfigFile; public ApolloConfigDemo() { ConfigChangeListener changeListener = new ConfigChangeListener() { @Override public void onChange(ConfigChangeEvent changeEvent) { logger.info("Changes for namespace {}", changeEvent.getNamespace()); for (String key : changeEvent.changedKeys()) { ConfigChange change = changeEvent.getChange(key); logger.info("Change - key: {}, oldValue: {}, newValue: {}, changeType: {}", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()); } } }; config = ConfigService.getAppConfig(); config.addChangeListener(changeListener); yamlConfig = ConfigService.getConfig("application.yaml"); yamlConfig.addChangeListener(changeListener); publicConfig = ConfigService.getConfig("TEST1.apollo"); publicConfig.addChangeListener(changeListener); applicationConfigFile = ConfigService.getConfigFile("application", ConfigFileFormat.Properties); // datasources.xml xmlConfigFile = ConfigService.getConfigFile("datasources", ConfigFileFormat.XML); xmlConfigFile.addChangeListener(new ConfigFileChangeListener() { @Override public void onChange(ConfigFileChangeEvent changeEvent) { logger.info(changeEvent.toString()); } }); // application.yaml yamlConfigFile = (YamlConfigFile) ConfigService.getConfigFile("application", ConfigFileFormat.YAML); } private String getConfig(String key) { String result = config.getProperty(key, DEFAULT_VALUE); if (DEFAULT_VALUE.equals(result)) { result = publicConfig.getProperty(key, DEFAULT_VALUE); } if (DEFAULT_VALUE.equals(result)) { result = yamlConfig.getProperty(key, DEFAULT_VALUE); } logger.info(String.format("Loading key : %s with value: %s", key, result)); return result; } private void print(String namespace) { switch (namespace) { case "application": print(applicationConfigFile); return; case "xml": print(xmlConfigFile); return; case "yaml": printYaml(yamlConfigFile); return; } } private void print(ConfigFile configFile) { if (!configFile.hasContent()) { System.out.println("No config file content found for " + configFile.getNamespace()); return; } System.out.println("=== Config File Content for " + configFile.getNamespace() + " is as follows: "); System.out.println(configFile.getContent()); } private void printYaml(YamlConfigFile configFile) { System.out.println("=== Properties for " + configFile.getNamespace() + " is as follows: "); System.out.println(configFile.asProperties()); } private void printEnvInfo() { String message = String.format("AppId: %s, Env: %s, DC: %s, IP: %s", Foundation.app() .getAppId(), Foundation.server().getEnvType(), Foundation.server().getDataCenter(), Foundation.net().getHostAddress()); System.out.println(message); } public static void main(String[] args) throws IOException { ApolloConfigDemo apolloConfigDemo = new ApolloConfigDemo(); apolloConfigDemo.printEnvInfo(); System.out.println( "Apollo Config Demo. Please input key to get the value."); while (true) { System.out.print("> "); String input = new BufferedReader(new InputStreamReader(System.in, Charsets.UTF_8)).readLine(); if (input == null || input.length() == 0) { continue; } input = input.trim(); try { if (input.equalsIgnoreCase("application")) { apolloConfigDemo.print("application"); continue; } if (input.equalsIgnoreCase("xml")) { apolloConfigDemo.print("xml"); continue; } if (input.equalsIgnoreCase("yaml") || input.equalsIgnoreCase("yml")) { apolloConfigDemo.print("yaml"); continue; } if (input.equalsIgnoreCase("quit")) { System.exit(0); } apolloConfigDemo.getConfig(input); } catch (Throwable ex) { logger.error("some error occurred", ex); } } } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.demo.api; import com.ctrip.framework.apollo.internals.YamlConfigFile; import com.google.common.base.Charsets; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.ConfigChangeListener; import com.ctrip.framework.apollo.ConfigFile; import com.ctrip.framework.apollo.ConfigFileChangeListener; import com.ctrip.framework.apollo.ConfigService; import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; import com.ctrip.framework.apollo.model.ConfigChange; import com.ctrip.framework.apollo.model.ConfigChangeEvent; import com.ctrip.framework.apollo.model.ConfigFileChangeEvent; import com.ctrip.framework.foundation.Foundation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author Jason Song(song_s@ctrip.com) */ public class ApolloConfigDemo { private static final Logger logger = LoggerFactory.getLogger(ApolloConfigDemo.class); private String DEFAULT_VALUE = "undefined"; private Config config; private Config yamlConfig; private Config publicConfig; private ConfigFile applicationConfigFile; private ConfigFile xmlConfigFile; private YamlConfigFile yamlConfigFile; public ApolloConfigDemo() { ConfigChangeListener changeListener = new ConfigChangeListener() { @Override public void onChange(ConfigChangeEvent changeEvent) { logger.info("Changes for namespace {}", changeEvent.getNamespace()); for (String key : changeEvent.changedKeys()) { ConfigChange change = changeEvent.getChange(key); logger.info("Change - key: {}, oldValue: {}, newValue: {}, changeType: {}", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()); } } }; config = ConfigService.getAppConfig(); config.addChangeListener(changeListener); yamlConfig = ConfigService.getConfig("application.yaml"); yamlConfig.addChangeListener(changeListener); publicConfig = ConfigService.getConfig("TEST1.apollo"); publicConfig.addChangeListener(changeListener); applicationConfigFile = ConfigService.getConfigFile("application", ConfigFileFormat.Properties); // datasources.xml xmlConfigFile = ConfigService.getConfigFile("datasources", ConfigFileFormat.XML); xmlConfigFile.addChangeListener(new ConfigFileChangeListener() { @Override public void onChange(ConfigFileChangeEvent changeEvent) { logger.info(changeEvent.toString()); } }); // application.yaml yamlConfigFile = (YamlConfigFile) ConfigService.getConfigFile("application", ConfigFileFormat.YAML); } private String getConfig(String key) { String result = config.getProperty(key, DEFAULT_VALUE); if (DEFAULT_VALUE.equals(result)) { result = publicConfig.getProperty(key, DEFAULT_VALUE); } if (DEFAULT_VALUE.equals(result)) { result = yamlConfig.getProperty(key, DEFAULT_VALUE); } logger.info(String.format("Loading key : %s with value: %s", key, result)); return result; } private void print(String namespace) { switch (namespace) { case "application": print(applicationConfigFile); return; case "xml": print(xmlConfigFile); return; case "yaml": printYaml(yamlConfigFile); return; } } private void print(ConfigFile configFile) { if (!configFile.hasContent()) { System.out.println("No config file content found for " + configFile.getNamespace()); return; } System.out.println("=== Config File Content for " + configFile.getNamespace() + " is as follows: "); System.out.println(configFile.getContent()); } private void printYaml(YamlConfigFile configFile) { System.out.println("=== Properties for " + configFile.getNamespace() + " is as follows: "); System.out.println(configFile.asProperties()); } private void printEnvInfo() { String message = String.format("AppId: %s, Env: %s, DC: %s, IP: %s", Foundation.app() .getAppId(), Foundation.server().getEnvType(), Foundation.server().getDataCenter(), Foundation.net().getHostAddress()); System.out.println(message); } public static void main(String[] args) throws IOException { ApolloConfigDemo apolloConfigDemo = new ApolloConfigDemo(); apolloConfigDemo.printEnvInfo(); System.out.println( "Apollo Config Demo. Please input key to get the value."); while (true) { System.out.print("> "); String input = new BufferedReader(new InputStreamReader(System.in, Charsets.UTF_8)).readLine(); if (input == null || input.length() == 0) { continue; } input = input.trim(); try { if (input.equalsIgnoreCase("application")) { apolloConfigDemo.print("application"); continue; } if (input.equalsIgnoreCase("xml")) { apolloConfigDemo.print("xml"); continue; } if (input.equalsIgnoreCase("yaml") || input.equalsIgnoreCase("yml")) { apolloConfigDemo.print("yaml"); continue; } if (input.equalsIgnoreCase("quit")) { System.exit(0); } apolloConfigDemo.getConfig(input); } catch (Throwable ex) { logger.error("some error occurred", ex); } } } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/ctrip/CtripEmailRequestBuilder.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.ctrip; import com.ctrip.framework.apollo.portal.component.config.PortalConfig; import com.ctrip.framework.apollo.portal.entity.bo.Email; import com.ctrip.framework.apollo.tracer.Tracer; import org.apache.commons.lang.time.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.lang.reflect.Method; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; public class CtripEmailRequestBuilder { private static final Logger logger = LoggerFactory.getLogger(CtripEmailRequestBuilder.class); private static Class sendEmailRequestClazz; private static Method setBodyContent; private static Method setRecipient; private static Method setSendCode; private static Method setBodyTemplateID; private static Method setSender; private static Method setSubject; private static Method setIsBodyHtml; private static Method setCharset; private static Method setExpiredTime; private static Method setAppID; @Autowired private PortalConfig portalConfig; @PostConstruct public void init() { try { sendEmailRequestClazz = Class.forName("com.ctrip.framework.apolloctripservice.emailservice.SendEmailRequest"); setSendCode = sendEmailRequestClazz.getMethod("setSendCode", String.class); setBodyTemplateID = sendEmailRequestClazz.getMethod("setBodyTemplateID", Integer.class); setSender = sendEmailRequestClazz.getMethod("setSender", String.class); setBodyContent = sendEmailRequestClazz.getMethod("setBodyContent", String.class); setRecipient = sendEmailRequestClazz.getMethod("setRecipient", List.class); setSubject = sendEmailRequestClazz.getMethod("setSubject", String.class); setIsBodyHtml = sendEmailRequestClazz.getMethod("setIsBodyHtml", Boolean.class); setCharset = sendEmailRequestClazz.getMethod("setCharset", String.class); setExpiredTime = sendEmailRequestClazz.getMethod("setExpiredTime", Calendar.class); setAppID = sendEmailRequestClazz.getMethod("setAppID", Integer.class); } catch (Throwable e) { logger.error("init email request build failed", e); Tracer.logError("init email request build failed", e); } } public Object buildEmailRequest(Email email) throws Exception { Object emailRequest = createBasicEmailRequest(); setSender.invoke(emailRequest, email.getSenderEmailAddress()); setSubject.invoke(emailRequest, email.getSubject()); String emailBodyBuilder = "<entry><content><![CDATA[<!DOCTYPE html>" + email.getBody() + "]]></content></entry>"; setBodyContent.invoke(emailRequest, emailBodyBuilder); setRecipient.invoke(emailRequest, email.getRecipients()); return emailRequest; } private Object createBasicEmailRequest() throws Exception { Object request = sendEmailRequestClazz.newInstance(); setSendCode.invoke(request, portalConfig.sendCode()); setBodyTemplateID.invoke(request, portalConfig.templateId()); setIsBodyHtml.invoke(request, true); setCharset.invoke(request, "UTF-8"); setExpiredTime.invoke(request, calExpiredTime()); setAppID.invoke(request, portalConfig.appId()); return request; } private Calendar calExpiredTime() { Calendar calendar = Calendar.getInstance(); calendar.setTime(DateUtils.addHours(new Date(), portalConfig.survivalDuration())); return calendar; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.ctrip; import com.ctrip.framework.apollo.portal.component.config.PortalConfig; import com.ctrip.framework.apollo.portal.entity.bo.Email; import com.ctrip.framework.apollo.tracer.Tracer; import org.apache.commons.lang.time.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.lang.reflect.Method; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; public class CtripEmailRequestBuilder { private static final Logger logger = LoggerFactory.getLogger(CtripEmailRequestBuilder.class); private static Class sendEmailRequestClazz; private static Method setBodyContent; private static Method setRecipient; private static Method setSendCode; private static Method setBodyTemplateID; private static Method setSender; private static Method setSubject; private static Method setIsBodyHtml; private static Method setCharset; private static Method setExpiredTime; private static Method setAppID; @Autowired private PortalConfig portalConfig; @PostConstruct public void init() { try { sendEmailRequestClazz = Class.forName("com.ctrip.framework.apolloctripservice.emailservice.SendEmailRequest"); setSendCode = sendEmailRequestClazz.getMethod("setSendCode", String.class); setBodyTemplateID = sendEmailRequestClazz.getMethod("setBodyTemplateID", Integer.class); setSender = sendEmailRequestClazz.getMethod("setSender", String.class); setBodyContent = sendEmailRequestClazz.getMethod("setBodyContent", String.class); setRecipient = sendEmailRequestClazz.getMethod("setRecipient", List.class); setSubject = sendEmailRequestClazz.getMethod("setSubject", String.class); setIsBodyHtml = sendEmailRequestClazz.getMethod("setIsBodyHtml", Boolean.class); setCharset = sendEmailRequestClazz.getMethod("setCharset", String.class); setExpiredTime = sendEmailRequestClazz.getMethod("setExpiredTime", Calendar.class); setAppID = sendEmailRequestClazz.getMethod("setAppID", Integer.class); } catch (Throwable e) { logger.error("init email request build failed", e); Tracer.logError("init email request build failed", e); } } public Object buildEmailRequest(Email email) throws Exception { Object emailRequest = createBasicEmailRequest(); setSender.invoke(emailRequest, email.getSenderEmailAddress()); setSubject.invoke(emailRequest, email.getSubject()); String emailBodyBuilder = "<entry><content><![CDATA[<!DOCTYPE html>" + email.getBody() + "]]></content></entry>"; setBodyContent.invoke(emailRequest, emailBodyBuilder); setRecipient.invoke(emailRequest, email.getRecipients()); return emailRequest; } private Object createBasicEmailRequest() throws Exception { Object request = sendEmailRequestClazz.newInstance(); setSendCode.invoke(request, portalConfig.sendCode()); setBodyTemplateID.invoke(request, portalConfig.templateId()); setIsBodyHtml.invoke(request, true); setCharset.invoke(request, "UTF-8"); setExpiredTime.invoke(request, calExpiredTime()); setAppID.invoke(request, portalConfig.appId()); return request; } private Calendar calExpiredTime() { Calendar calendar = Calendar.getInstance(); calendar.setTime(DateUtils.addHours(new Date(), portalConfig.survivalDuration())); return calendar; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/configuration/MQConfiguration.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.configuration; import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripMQService; import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultMQService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration public class MQConfiguration { @Configuration @Profile("ctrip") public static class CtripMQConfiguration { @Bean public CtripMQService mqService() { return new CtripMQService(); } } /** * spring.profiles.active != ctrip */ @Configuration @ConditionalOnMissingProfile({"ctrip"}) public static class DefaultMQConfiguration { @Bean public DefaultMQService mqService() { return new DefaultMQService(); } } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.spi.configuration; import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile; import com.ctrip.framework.apollo.portal.spi.ctrip.CtripMQService; import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultMQService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration public class MQConfiguration { @Configuration @Profile("ctrip") public static class CtripMQConfiguration { @Bean public CtripMQService mqService() { return new CtripMQService(); } } /** * spring.profiles.active != ctrip */ @Configuration @ConditionalOnMissingProfile({"ctrip"}) public static class DefaultMQConfiguration { @Bean public DefaultMQService mqService() { return new DefaultMQService(); } } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/DefaultApplicationProvider.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.foundation.internals.provider; import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; import com.ctrip.framework.apollo.core.utils.DeprecatedPropertyNotifyUtil; import com.ctrip.framework.foundation.internals.Utils; import com.ctrip.framework.foundation.internals.io.BOMInputStream; import com.ctrip.framework.foundation.spi.provider.ApplicationProvider; import com.ctrip.framework.foundation.spi.provider.Provider; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Properties; import org.slf4j.Logger; public class DefaultApplicationProvider implements ApplicationProvider { private static final Logger logger = DeferredLoggerFactory .getLogger(DefaultApplicationProvider.class); public static final String APP_PROPERTIES_CLASSPATH = "/META-INF/app.properties"; private Properties m_appProperties = new Properties(); private String m_appId; private String accessKeySecret; @Override public void initialize() { try { InputStream in = Thread.currentThread().getContextClassLoader() .getResourceAsStream(APP_PROPERTIES_CLASSPATH.substring(1)); if (in == null) { in = DefaultApplicationProvider.class.getResourceAsStream(APP_PROPERTIES_CLASSPATH); } initialize(in); } catch (Throwable ex) { logger.error("Initialize DefaultApplicationProvider failed.", ex); } } @Override public void initialize(InputStream in) { try { if (in != null) { try { m_appProperties .load(new InputStreamReader(new BOMInputStream(in), StandardCharsets.UTF_8)); } finally { in.close(); } } initAppId(); initAccessKey(); } catch (Throwable ex) { logger.error("Initialize DefaultApplicationProvider failed.", ex); } } @Override public String getAppId() { return m_appId; } @Override public String getAccessKeySecret() { return accessKeySecret; } @Override public boolean isAppIdSet() { return !Utils.isBlank(m_appId); } @Override public String getProperty(String name, String defaultValue) { if (ApolloClientSystemConsts.APP_ID.equals(name)) { String val = getAppId(); return val == null ? defaultValue : val; } if (ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET.equals(name)) { String val = getAccessKeySecret(); return val == null ? defaultValue : val; } String val = m_appProperties.getProperty(name, defaultValue); return val == null ? defaultValue : val; } @Override public Class<? extends Provider> getType() { return ApplicationProvider.class; } private void initAppId() { // 1. Get app.id from System Property m_appId = System.getProperty(ApolloClientSystemConsts.APP_ID); if (!Utils.isBlank(m_appId)) { m_appId = m_appId.trim(); logger.info("App ID is set to {} by app.id property from System Property", m_appId); return; } //2. Try to get app id from OS environment variable m_appId = System.getenv(ApolloClientSystemConsts.APP_ID_ENVIRONMENT_VARIABLES); if (!Utils.isBlank(m_appId)) { m_appId = m_appId.trim(); logger.info("App ID is set to {} by APP_ID property from OS environment variable", m_appId); return; } // 3. Try to get app id from app.properties. m_appId = m_appProperties.getProperty(ApolloClientSystemConsts.APP_ID); if (!Utils.isBlank(m_appId)) { m_appId = m_appId.trim(); logger.info("App ID is set to {} by app.id property from {}", m_appId, APP_PROPERTIES_CLASSPATH); return; } m_appId = null; logger.warn("app.id is not available from System Property and {}. It is set to null", APP_PROPERTIES_CLASSPATH); } private void initAccessKey() { // 1. Get ACCESS KEY SECRET from System Property accessKeySecret = System.getProperty(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET); if (!Utils.isBlank(accessKeySecret)) { accessKeySecret = accessKeySecret.trim(); logger .info("ACCESS KEY SECRET is set by apollo.access-key.secret property from System Property"); return; } //2. Try to get ACCESS KEY SECRET from OS environment variable accessKeySecret = System.getenv(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES); if (!Utils.isBlank(accessKeySecret)) { accessKeySecret = accessKeySecret.trim(); logger.info( "ACCESS KEY SECRET is set by APOLLO_ACCESS_KEY_SECRET property from OS environment variable"); return; } // 3. Try to get ACCESS KEY SECRET from app.properties. accessKeySecret = m_appProperties.getProperty(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET); if (!Utils.isBlank(accessKeySecret)) { accessKeySecret = accessKeySecret.trim(); logger.info("ACCESS KEY SECRET is set by apollo.access-key.secret property from {}", APP_PROPERTIES_CLASSPATH); return; } // 4. Try to get ACCESS KEY SECRET from deprecated config. accessKeySecret = initDeprecatedAccessKey(); if (!Utils.isBlank(accessKeySecret)) { return; } accessKeySecret = null; } @SuppressWarnings("deprecation") private String initDeprecatedAccessKey() { // 1. Get ACCESS KEY SECRET from System Property String accessKeySecret = System .getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET); if (!Utils.isBlank(accessKeySecret)) { accessKeySecret = accessKeySecret.trim(); logger.info( "ACCESS KEY SECRET is set by apollo.accesskey.secret property from System Property"); DeprecatedPropertyNotifyUtil .warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET, ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET); return accessKeySecret; } //2. Try to get ACCESS KEY SECRET from OS environment variable accessKeySecret = System .getenv(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES); if (!Utils.isBlank(accessKeySecret)) { accessKeySecret = accessKeySecret.trim(); logger.info( "ACCESS KEY SECRET is set by APOLLO_ACCESSKEY_SECRET property from OS environment variable"); DeprecatedPropertyNotifyUtil .warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES, ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES); return accessKeySecret; } // 3. Try to get ACCESS KEY SECRET from app.properties. accessKeySecret = m_appProperties .getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET); if (!Utils.isBlank(accessKeySecret)) { accessKeySecret = accessKeySecret.trim(); logger.info("ACCESS KEY SECRET is set by apollo.accesskey.secret property from {}", APP_PROPERTIES_CLASSPATH); DeprecatedPropertyNotifyUtil .warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET, ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET); return accessKeySecret; } return null; } @Override public String toString() { return "appId [" + getAppId() + "] properties: " + m_appProperties + " (DefaultApplicationProvider)"; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.foundation.internals.provider; import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; import com.ctrip.framework.apollo.core.utils.DeprecatedPropertyNotifyUtil; import com.ctrip.framework.foundation.internals.Utils; import com.ctrip.framework.foundation.internals.io.BOMInputStream; import com.ctrip.framework.foundation.spi.provider.ApplicationProvider; import com.ctrip.framework.foundation.spi.provider.Provider; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Properties; import org.slf4j.Logger; public class DefaultApplicationProvider implements ApplicationProvider { private static final Logger logger = DeferredLoggerFactory .getLogger(DefaultApplicationProvider.class); public static final String APP_PROPERTIES_CLASSPATH = "/META-INF/app.properties"; private Properties m_appProperties = new Properties(); private String m_appId; private String accessKeySecret; @Override public void initialize() { try { InputStream in = Thread.currentThread().getContextClassLoader() .getResourceAsStream(APP_PROPERTIES_CLASSPATH.substring(1)); if (in == null) { in = DefaultApplicationProvider.class.getResourceAsStream(APP_PROPERTIES_CLASSPATH); } initialize(in); } catch (Throwable ex) { logger.error("Initialize DefaultApplicationProvider failed.", ex); } } @Override public void initialize(InputStream in) { try { if (in != null) { try { m_appProperties .load(new InputStreamReader(new BOMInputStream(in), StandardCharsets.UTF_8)); } finally { in.close(); } } initAppId(); initAccessKey(); } catch (Throwable ex) { logger.error("Initialize DefaultApplicationProvider failed.", ex); } } @Override public String getAppId() { return m_appId; } @Override public String getAccessKeySecret() { return accessKeySecret; } @Override public boolean isAppIdSet() { return !Utils.isBlank(m_appId); } @Override public String getProperty(String name, String defaultValue) { if (ApolloClientSystemConsts.APP_ID.equals(name)) { String val = getAppId(); return val == null ? defaultValue : val; } if (ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET.equals(name)) { String val = getAccessKeySecret(); return val == null ? defaultValue : val; } String val = m_appProperties.getProperty(name, defaultValue); return val == null ? defaultValue : val; } @Override public Class<? extends Provider> getType() { return ApplicationProvider.class; } private void initAppId() { // 1. Get app.id from System Property m_appId = System.getProperty(ApolloClientSystemConsts.APP_ID); if (!Utils.isBlank(m_appId)) { m_appId = m_appId.trim(); logger.info("App ID is set to {} by app.id property from System Property", m_appId); return; } //2. Try to get app id from OS environment variable m_appId = System.getenv(ApolloClientSystemConsts.APP_ID_ENVIRONMENT_VARIABLES); if (!Utils.isBlank(m_appId)) { m_appId = m_appId.trim(); logger.info("App ID is set to {} by APP_ID property from OS environment variable", m_appId); return; } // 3. Try to get app id from app.properties. m_appId = m_appProperties.getProperty(ApolloClientSystemConsts.APP_ID); if (!Utils.isBlank(m_appId)) { m_appId = m_appId.trim(); logger.info("App ID is set to {} by app.id property from {}", m_appId, APP_PROPERTIES_CLASSPATH); return; } m_appId = null; logger.warn("app.id is not available from System Property and {}. It is set to null", APP_PROPERTIES_CLASSPATH); } private void initAccessKey() { // 1. Get ACCESS KEY SECRET from System Property accessKeySecret = System.getProperty(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET); if (!Utils.isBlank(accessKeySecret)) { accessKeySecret = accessKeySecret.trim(); logger .info("ACCESS KEY SECRET is set by apollo.access-key.secret property from System Property"); return; } //2. Try to get ACCESS KEY SECRET from OS environment variable accessKeySecret = System.getenv(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES); if (!Utils.isBlank(accessKeySecret)) { accessKeySecret = accessKeySecret.trim(); logger.info( "ACCESS KEY SECRET is set by APOLLO_ACCESS_KEY_SECRET property from OS environment variable"); return; } // 3. Try to get ACCESS KEY SECRET from app.properties. accessKeySecret = m_appProperties.getProperty(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET); if (!Utils.isBlank(accessKeySecret)) { accessKeySecret = accessKeySecret.trim(); logger.info("ACCESS KEY SECRET is set by apollo.access-key.secret property from {}", APP_PROPERTIES_CLASSPATH); return; } // 4. Try to get ACCESS KEY SECRET from deprecated config. accessKeySecret = initDeprecatedAccessKey(); if (!Utils.isBlank(accessKeySecret)) { return; } accessKeySecret = null; } @SuppressWarnings("deprecation") private String initDeprecatedAccessKey() { // 1. Get ACCESS KEY SECRET from System Property String accessKeySecret = System .getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET); if (!Utils.isBlank(accessKeySecret)) { accessKeySecret = accessKeySecret.trim(); logger.info( "ACCESS KEY SECRET is set by apollo.accesskey.secret property from System Property"); DeprecatedPropertyNotifyUtil .warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET, ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET); return accessKeySecret; } //2. Try to get ACCESS KEY SECRET from OS environment variable accessKeySecret = System .getenv(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES); if (!Utils.isBlank(accessKeySecret)) { accessKeySecret = accessKeySecret.trim(); logger.info( "ACCESS KEY SECRET is set by APOLLO_ACCESSKEY_SECRET property from OS environment variable"); DeprecatedPropertyNotifyUtil .warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES, ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES); return accessKeySecret; } // 3. Try to get ACCESS KEY SECRET from app.properties. accessKeySecret = m_appProperties .getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET); if (!Utils.isBlank(accessKeySecret)) { accessKeySecret = accessKeySecret.trim(); logger.info("ACCESS KEY SECRET is set by apollo.accesskey.secret property from {}", APP_PROPERTIES_CLASSPATH); DeprecatedPropertyNotifyUtil .warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET, ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET); return accessKeySecret; } return null; } @Override public String toString() { return "appId [" + getAppId() + "] properties: " + m_appProperties + " (DefaultApplicationProvider)"; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-adminservice/src/test/java/com/ctrip/framework/apollo/adminservice/controller/InstanceConfigControllerTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.adminservice.controller; import com.ctrip.framework.apollo.biz.entity.Instance; import com.ctrip.framework.apollo.biz.entity.InstanceConfig; import com.ctrip.framework.apollo.biz.entity.Release; import com.ctrip.framework.apollo.biz.service.InstanceService; import com.ctrip.framework.apollo.biz.service.ReleaseService; import com.ctrip.framework.apollo.common.dto.InstanceDTO; import com.ctrip.framework.apollo.common.dto.PageDTO; import com.ctrip.framework.apollo.common.exception.NotFoundException; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author Jason Song(song_s@ctrip.com) */ @RunWith(MockitoJUnitRunner.class) public class InstanceConfigControllerTest { private InstanceConfigController instanceConfigController; @Mock private ReleaseService releaseService; @Mock private InstanceService instanceService; private Pageable pageable; @Before public void setUp() throws Exception { instanceConfigController = new InstanceConfigController(releaseService, instanceService); pageable = PageRequest.of(0, 2); } @Test public void getByRelease() throws Exception { long someReleaseId = 1; long someInstanceId = 1; long anotherInstanceId = 2; String someReleaseKey = "someKey"; Release someRelease = new Release(); someRelease.setReleaseKey(someReleaseKey); String someAppId = "someAppId"; String anotherAppId = "anotherAppId"; String someCluster = "someCluster"; String someDataCenter = "someDC"; String someConfigAppId = "someConfigAppId"; String someConfigNamespace = "someNamespace"; String someIp = "someIp"; Date someReleaseDeliveryTime = new Date(); Date anotherReleaseDeliveryTime = new Date(); when(releaseService.findOne(someReleaseId)).thenReturn(someRelease); InstanceConfig someInstanceConfig = assembleInstanceConfig(someInstanceId, someConfigAppId, someConfigNamespace, someReleaseKey, someReleaseDeliveryTime); InstanceConfig anotherInstanceConfig = assembleInstanceConfig(anotherInstanceId, someConfigAppId, someConfigNamespace, someReleaseKey, anotherReleaseDeliveryTime); List<InstanceConfig> instanceConfigs = Lists.newArrayList(someInstanceConfig, anotherInstanceConfig); Page<InstanceConfig> instanceConfigPage = new PageImpl<>(instanceConfigs, pageable, instanceConfigs.size()); when(instanceService.findActiveInstanceConfigsByReleaseKey(someReleaseKey, pageable)) .thenReturn(instanceConfigPage); Instance someInstance = assembleInstance(someInstanceId, someAppId, someCluster, someDataCenter, someIp); Instance anotherInstance = assembleInstance(anotherInstanceId, anotherAppId, someCluster, someDataCenter, someIp); List<Instance> instances = Lists.newArrayList(someInstance, anotherInstance); Set<Long> instanceIds = Sets.newHashSet(someInstanceId, anotherInstanceId); when(instanceService.findInstancesByIds(instanceIds)) .thenReturn(instances); PageDTO<InstanceDTO> result = instanceConfigController.getByRelease(someReleaseId, pageable); assertEquals(2, result.getContent().size()); InstanceDTO someInstanceDto = null; InstanceDTO anotherInstanceDto = null; for (InstanceDTO instanceDTO : result.getContent()) { if (instanceDTO.getId() == someInstanceId) { someInstanceDto = instanceDTO; } else if (instanceDTO.getId() == anotherInstanceId) { anotherInstanceDto = instanceDTO; } } verifyInstance(someInstance, someInstanceDto); verifyInstance(anotherInstance, anotherInstanceDto); assertEquals(1, someInstanceDto.getConfigs().size()); assertEquals(someReleaseDeliveryTime, someInstanceDto.getConfigs().get(0).getReleaseDeliveryTime()); assertEquals(1, anotherInstanceDto.getConfigs().size()); assertEquals(anotherReleaseDeliveryTime, anotherInstanceDto.getConfigs().get(0).getReleaseDeliveryTime()); } @Test(expected = NotFoundException.class) public void testGetByReleaseWhenReleaseIsNotFound() throws Exception { long someReleaseIdNotExists = 1; when(releaseService.findOne(someReleaseIdNotExists)).thenReturn(null); instanceConfigController.getByRelease(someReleaseIdNotExists, pageable); } @Test public void testGetByReleasesNotIn() throws Exception { String someConfigAppId = "someConfigAppId"; String someConfigClusterName = "someConfigClusterName"; String someConfigNamespaceName = "someConfigNamespaceName"; long someReleaseId = 1; long anotherReleaseId = 2; String releaseIds = Joiner.on(",").join(someReleaseId, anotherReleaseId); Date someReleaseDeliveryTime = new Date(); Date anotherReleaseDeliveryTime = new Date(); Release someRelease = mock(Release.class); Release anotherRelease = mock(Release.class); String someReleaseKey = "someReleaseKey"; String anotherReleaseKey = "anotherReleaseKey"; when(someRelease.getReleaseKey()).thenReturn(someReleaseKey); when(anotherRelease.getReleaseKey()).thenReturn(anotherReleaseKey); when(releaseService.findByReleaseIds(Sets.newHashSet(someReleaseId, anotherReleaseId))) .thenReturn(Lists.newArrayList(someRelease, anotherRelease)); long someInstanceId = 1; long anotherInstanceId = 2; String someInstanceConfigReleaseKey = "someInstanceConfigReleaseKey"; String anotherInstanceConfigReleaseKey = "anotherInstanceConfigReleaseKey"; InstanceConfig someInstanceConfig = mock(InstanceConfig.class); InstanceConfig anotherInstanceConfig = mock(InstanceConfig.class); when(someInstanceConfig.getInstanceId()).thenReturn(someInstanceId); when(anotherInstanceConfig.getInstanceId()).thenReturn(anotherInstanceId); when(someInstanceConfig.getReleaseKey()).thenReturn(someInstanceConfigReleaseKey); when(anotherInstanceConfig.getReleaseKey()).thenReturn(anotherInstanceConfigReleaseKey); when(someInstanceConfig.getReleaseDeliveryTime()).thenReturn(someReleaseDeliveryTime); when(anotherInstanceConfig.getReleaseDeliveryTime()).thenReturn(anotherReleaseDeliveryTime); when(instanceService.findInstanceConfigsByNamespaceWithReleaseKeysNotIn(someConfigAppId, someConfigClusterName, someConfigNamespaceName, Sets.newHashSet(someReleaseKey, anotherReleaseKey))).thenReturn(Lists.newArrayList(someInstanceConfig, anotherInstanceConfig)); String someInstanceAppId = "someInstanceAppId"; String someInstanceClusterName = "someInstanceClusterName"; String someInstanceNamespaceName = "someInstanceNamespaceName"; String someIp = "someIp"; String anotherIp = "anotherIp"; Instance someInstance = assembleInstance(someInstanceId, someInstanceAppId, someInstanceClusterName, someInstanceNamespaceName, someIp); Instance anotherInstance = assembleInstance(anotherInstanceId, someInstanceAppId, someInstanceClusterName, someInstanceNamespaceName, anotherIp); when(instanceService.findInstancesByIds(Sets.newHashSet(someInstanceId, anotherInstanceId))) .thenReturn(Lists.newArrayList(someInstance, anotherInstance)); Release someInstanceConfigRelease = new Release(); someInstanceConfigRelease.setReleaseKey(someInstanceConfigReleaseKey); Release anotherInstanceConfigRelease = new Release(); anotherInstanceConfigRelease.setReleaseKey(anotherInstanceConfigReleaseKey); when(releaseService.findByReleaseKeys(Sets.newHashSet(someInstanceConfigReleaseKey, anotherInstanceConfigReleaseKey))).thenReturn(Lists.newArrayList(someInstanceConfigRelease, anotherInstanceConfigRelease)); List<InstanceDTO> result = instanceConfigController.getByReleasesNotIn(someConfigAppId, someConfigClusterName, someConfigNamespaceName, releaseIds); assertEquals(2, result.size()); InstanceDTO someInstanceDto = null; InstanceDTO anotherInstanceDto = null; for (InstanceDTO instanceDTO : result) { if (instanceDTO.getId() == someInstanceId) { someInstanceDto = instanceDTO; } else if (instanceDTO.getId() == anotherInstanceId) { anotherInstanceDto = instanceDTO; } } verifyInstance(someInstance, someInstanceDto); verifyInstance(anotherInstance, anotherInstanceDto); assertEquals(someInstanceConfigReleaseKey, someInstanceDto.getConfigs().get(0).getRelease() .getReleaseKey()); assertEquals(anotherInstanceConfigReleaseKey, anotherInstanceDto.getConfigs().get(0) .getRelease() .getReleaseKey()); assertEquals(someReleaseDeliveryTime, someInstanceDto.getConfigs().get(0).getReleaseDeliveryTime()); assertEquals(anotherReleaseDeliveryTime, anotherInstanceDto.getConfigs().get(0) .getReleaseDeliveryTime()); } @Test public void testGetInstancesByNamespace() throws Exception { String someAppId = "someAppId"; String someClusterName = "someClusterName"; String someNamespaceName = "someNamespaceName"; String someIp = "someIp"; long someInstanceId = 1; long anotherInstanceId = 2; Instance someInstance = assembleInstance(someInstanceId, someAppId, someClusterName, someNamespaceName, someIp); Instance anotherInstance = assembleInstance(anotherInstanceId, someAppId, someClusterName, someNamespaceName, someIp); Page<Instance> instances = new PageImpl<>(Lists.newArrayList(someInstance, anotherInstance), pageable, 2); when(instanceService.findInstancesByNamespace(someAppId, someClusterName, someNamespaceName, pageable)).thenReturn(instances); PageDTO<InstanceDTO> result = instanceConfigController.getInstancesByNamespace(someAppId, someClusterName, someNamespaceName, null, pageable); assertEquals(2, result.getContent().size()); InstanceDTO someInstanceDto = null; InstanceDTO anotherInstanceDto = null; for (InstanceDTO instanceDTO : result.getContent()) { if (instanceDTO.getId() == someInstanceId) { someInstanceDto = instanceDTO; } else if (instanceDTO.getId() == anotherInstanceId) { anotherInstanceDto = instanceDTO; } } verifyInstance(someInstance, someInstanceDto); verifyInstance(anotherInstance, anotherInstanceDto); } @Test public void testGetInstancesByNamespaceAndInstanceAppId() throws Exception { String someInstanceAppId = "someInstanceAppId"; String someAppId = "someAppId"; String someClusterName = "someClusterName"; String someNamespaceName = "someNamespaceName"; String someIp = "someIp"; long someInstanceId = 1; long anotherInstanceId = 2; Instance someInstance = assembleInstance(someInstanceId, someAppId, someClusterName, someNamespaceName, someIp); Instance anotherInstance = assembleInstance(anotherInstanceId, someAppId, someClusterName, someNamespaceName, someIp); Page<Instance> instances = new PageImpl<>(Lists.newArrayList(someInstance, anotherInstance), pageable, 2); when(instanceService.findInstancesByNamespaceAndInstanceAppId(someInstanceAppId, someAppId, someClusterName, someNamespaceName, pageable)).thenReturn(instances); PageDTO<InstanceDTO> result = instanceConfigController.getInstancesByNamespace(someAppId, someClusterName, someNamespaceName, someInstanceAppId, pageable); assertEquals(2, result.getContent().size()); InstanceDTO someInstanceDto = null; InstanceDTO anotherInstanceDto = null; for (InstanceDTO instanceDTO : result.getContent()) { if (instanceDTO.getId() == someInstanceId) { someInstanceDto = instanceDTO; } else if (instanceDTO.getId() == anotherInstanceId) { anotherInstanceDto = instanceDTO; } } verifyInstance(someInstance, someInstanceDto); verifyInstance(anotherInstance, anotherInstanceDto); } @Test public void testGetInstancesCountByNamespace() throws Exception { String someAppId = "someAppId"; String someClusterName = "someClusterName"; String someNamespaceName = "someNamespaceName"; Page<Instance> instances = new PageImpl<>(Collections.emptyList(), pageable, 2); when(instanceService.findInstancesByNamespace(eq(someAppId), eq(someClusterName), eq(someNamespaceName), any(Pageable.class))).thenReturn(instances); long result = instanceConfigController.getInstancesCountByNamespace(someAppId, someClusterName, someNamespaceName); assertEquals(2, result); } private void verifyInstance(Instance instance, InstanceDTO instanceDTO) { assertEquals(instance.getId(), instanceDTO.getId()); assertEquals(instance.getAppId(), instanceDTO.getAppId()); assertEquals(instance.getClusterName(), instanceDTO.getClusterName()); assertEquals(instance.getDataCenter(), instanceDTO.getDataCenter()); assertEquals(instance.getIp(), instanceDTO.getIp()); assertEquals(instance.getDataChangeCreatedTime(), instanceDTO.getDataChangeCreatedTime()); } private Instance assembleInstance(long instanceId, String appId, String clusterName, String dataCenter, String ip) { Instance instance = new Instance(); instance.setId(instanceId); instance.setAppId(appId); instance.setIp(ip); instance.setClusterName(clusterName); instance.setDataCenter(dataCenter); instance.setDataChangeCreatedTime(new Date()); return instance; } private InstanceConfig assembleInstanceConfig(long instanceId, String configAppId, String configNamespaceName, String releaseKey, Date releaseDeliveryTime) { InstanceConfig instanceConfig = new InstanceConfig(); instanceConfig.setInstanceId(instanceId); instanceConfig.setConfigAppId(configAppId); instanceConfig.setConfigNamespaceName(configNamespaceName); instanceConfig.setReleaseKey(releaseKey); instanceConfig.setDataChangeLastModifiedTime(new Date()); instanceConfig.setReleaseDeliveryTime(releaseDeliveryTime); return instanceConfig; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.adminservice.controller; import com.ctrip.framework.apollo.biz.entity.Instance; import com.ctrip.framework.apollo.biz.entity.InstanceConfig; import com.ctrip.framework.apollo.biz.entity.Release; import com.ctrip.framework.apollo.biz.service.InstanceService; import com.ctrip.framework.apollo.biz.service.ReleaseService; import com.ctrip.framework.apollo.common.dto.InstanceDTO; import com.ctrip.framework.apollo.common.dto.PageDTO; import com.ctrip.framework.apollo.common.exception.NotFoundException; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author Jason Song(song_s@ctrip.com) */ @RunWith(MockitoJUnitRunner.class) public class InstanceConfigControllerTest { private InstanceConfigController instanceConfigController; @Mock private ReleaseService releaseService; @Mock private InstanceService instanceService; private Pageable pageable; @Before public void setUp() throws Exception { instanceConfigController = new InstanceConfigController(releaseService, instanceService); pageable = PageRequest.of(0, 2); } @Test public void getByRelease() throws Exception { long someReleaseId = 1; long someInstanceId = 1; long anotherInstanceId = 2; String someReleaseKey = "someKey"; Release someRelease = new Release(); someRelease.setReleaseKey(someReleaseKey); String someAppId = "someAppId"; String anotherAppId = "anotherAppId"; String someCluster = "someCluster"; String someDataCenter = "someDC"; String someConfigAppId = "someConfigAppId"; String someConfigNamespace = "someNamespace"; String someIp = "someIp"; Date someReleaseDeliveryTime = new Date(); Date anotherReleaseDeliveryTime = new Date(); when(releaseService.findOne(someReleaseId)).thenReturn(someRelease); InstanceConfig someInstanceConfig = assembleInstanceConfig(someInstanceId, someConfigAppId, someConfigNamespace, someReleaseKey, someReleaseDeliveryTime); InstanceConfig anotherInstanceConfig = assembleInstanceConfig(anotherInstanceId, someConfigAppId, someConfigNamespace, someReleaseKey, anotherReleaseDeliveryTime); List<InstanceConfig> instanceConfigs = Lists.newArrayList(someInstanceConfig, anotherInstanceConfig); Page<InstanceConfig> instanceConfigPage = new PageImpl<>(instanceConfigs, pageable, instanceConfigs.size()); when(instanceService.findActiveInstanceConfigsByReleaseKey(someReleaseKey, pageable)) .thenReturn(instanceConfigPage); Instance someInstance = assembleInstance(someInstanceId, someAppId, someCluster, someDataCenter, someIp); Instance anotherInstance = assembleInstance(anotherInstanceId, anotherAppId, someCluster, someDataCenter, someIp); List<Instance> instances = Lists.newArrayList(someInstance, anotherInstance); Set<Long> instanceIds = Sets.newHashSet(someInstanceId, anotherInstanceId); when(instanceService.findInstancesByIds(instanceIds)) .thenReturn(instances); PageDTO<InstanceDTO> result = instanceConfigController.getByRelease(someReleaseId, pageable); assertEquals(2, result.getContent().size()); InstanceDTO someInstanceDto = null; InstanceDTO anotherInstanceDto = null; for (InstanceDTO instanceDTO : result.getContent()) { if (instanceDTO.getId() == someInstanceId) { someInstanceDto = instanceDTO; } else if (instanceDTO.getId() == anotherInstanceId) { anotherInstanceDto = instanceDTO; } } verifyInstance(someInstance, someInstanceDto); verifyInstance(anotherInstance, anotherInstanceDto); assertEquals(1, someInstanceDto.getConfigs().size()); assertEquals(someReleaseDeliveryTime, someInstanceDto.getConfigs().get(0).getReleaseDeliveryTime()); assertEquals(1, anotherInstanceDto.getConfigs().size()); assertEquals(anotherReleaseDeliveryTime, anotherInstanceDto.getConfigs().get(0).getReleaseDeliveryTime()); } @Test(expected = NotFoundException.class) public void testGetByReleaseWhenReleaseIsNotFound() throws Exception { long someReleaseIdNotExists = 1; when(releaseService.findOne(someReleaseIdNotExists)).thenReturn(null); instanceConfigController.getByRelease(someReleaseIdNotExists, pageable); } @Test public void testGetByReleasesNotIn() throws Exception { String someConfigAppId = "someConfigAppId"; String someConfigClusterName = "someConfigClusterName"; String someConfigNamespaceName = "someConfigNamespaceName"; long someReleaseId = 1; long anotherReleaseId = 2; String releaseIds = Joiner.on(",").join(someReleaseId, anotherReleaseId); Date someReleaseDeliveryTime = new Date(); Date anotherReleaseDeliveryTime = new Date(); Release someRelease = mock(Release.class); Release anotherRelease = mock(Release.class); String someReleaseKey = "someReleaseKey"; String anotherReleaseKey = "anotherReleaseKey"; when(someRelease.getReleaseKey()).thenReturn(someReleaseKey); when(anotherRelease.getReleaseKey()).thenReturn(anotherReleaseKey); when(releaseService.findByReleaseIds(Sets.newHashSet(someReleaseId, anotherReleaseId))) .thenReturn(Lists.newArrayList(someRelease, anotherRelease)); long someInstanceId = 1; long anotherInstanceId = 2; String someInstanceConfigReleaseKey = "someInstanceConfigReleaseKey"; String anotherInstanceConfigReleaseKey = "anotherInstanceConfigReleaseKey"; InstanceConfig someInstanceConfig = mock(InstanceConfig.class); InstanceConfig anotherInstanceConfig = mock(InstanceConfig.class); when(someInstanceConfig.getInstanceId()).thenReturn(someInstanceId); when(anotherInstanceConfig.getInstanceId()).thenReturn(anotherInstanceId); when(someInstanceConfig.getReleaseKey()).thenReturn(someInstanceConfigReleaseKey); when(anotherInstanceConfig.getReleaseKey()).thenReturn(anotherInstanceConfigReleaseKey); when(someInstanceConfig.getReleaseDeliveryTime()).thenReturn(someReleaseDeliveryTime); when(anotherInstanceConfig.getReleaseDeliveryTime()).thenReturn(anotherReleaseDeliveryTime); when(instanceService.findInstanceConfigsByNamespaceWithReleaseKeysNotIn(someConfigAppId, someConfigClusterName, someConfigNamespaceName, Sets.newHashSet(someReleaseKey, anotherReleaseKey))).thenReturn(Lists.newArrayList(someInstanceConfig, anotherInstanceConfig)); String someInstanceAppId = "someInstanceAppId"; String someInstanceClusterName = "someInstanceClusterName"; String someInstanceNamespaceName = "someInstanceNamespaceName"; String someIp = "someIp"; String anotherIp = "anotherIp"; Instance someInstance = assembleInstance(someInstanceId, someInstanceAppId, someInstanceClusterName, someInstanceNamespaceName, someIp); Instance anotherInstance = assembleInstance(anotherInstanceId, someInstanceAppId, someInstanceClusterName, someInstanceNamespaceName, anotherIp); when(instanceService.findInstancesByIds(Sets.newHashSet(someInstanceId, anotherInstanceId))) .thenReturn(Lists.newArrayList(someInstance, anotherInstance)); Release someInstanceConfigRelease = new Release(); someInstanceConfigRelease.setReleaseKey(someInstanceConfigReleaseKey); Release anotherInstanceConfigRelease = new Release(); anotherInstanceConfigRelease.setReleaseKey(anotherInstanceConfigReleaseKey); when(releaseService.findByReleaseKeys(Sets.newHashSet(someInstanceConfigReleaseKey, anotherInstanceConfigReleaseKey))).thenReturn(Lists.newArrayList(someInstanceConfigRelease, anotherInstanceConfigRelease)); List<InstanceDTO> result = instanceConfigController.getByReleasesNotIn(someConfigAppId, someConfigClusterName, someConfigNamespaceName, releaseIds); assertEquals(2, result.size()); InstanceDTO someInstanceDto = null; InstanceDTO anotherInstanceDto = null; for (InstanceDTO instanceDTO : result) { if (instanceDTO.getId() == someInstanceId) { someInstanceDto = instanceDTO; } else if (instanceDTO.getId() == anotherInstanceId) { anotherInstanceDto = instanceDTO; } } verifyInstance(someInstance, someInstanceDto); verifyInstance(anotherInstance, anotherInstanceDto); assertEquals(someInstanceConfigReleaseKey, someInstanceDto.getConfigs().get(0).getRelease() .getReleaseKey()); assertEquals(anotherInstanceConfigReleaseKey, anotherInstanceDto.getConfigs().get(0) .getRelease() .getReleaseKey()); assertEquals(someReleaseDeliveryTime, someInstanceDto.getConfigs().get(0).getReleaseDeliveryTime()); assertEquals(anotherReleaseDeliveryTime, anotherInstanceDto.getConfigs().get(0) .getReleaseDeliveryTime()); } @Test public void testGetInstancesByNamespace() throws Exception { String someAppId = "someAppId"; String someClusterName = "someClusterName"; String someNamespaceName = "someNamespaceName"; String someIp = "someIp"; long someInstanceId = 1; long anotherInstanceId = 2; Instance someInstance = assembleInstance(someInstanceId, someAppId, someClusterName, someNamespaceName, someIp); Instance anotherInstance = assembleInstance(anotherInstanceId, someAppId, someClusterName, someNamespaceName, someIp); Page<Instance> instances = new PageImpl<>(Lists.newArrayList(someInstance, anotherInstance), pageable, 2); when(instanceService.findInstancesByNamespace(someAppId, someClusterName, someNamespaceName, pageable)).thenReturn(instances); PageDTO<InstanceDTO> result = instanceConfigController.getInstancesByNamespace(someAppId, someClusterName, someNamespaceName, null, pageable); assertEquals(2, result.getContent().size()); InstanceDTO someInstanceDto = null; InstanceDTO anotherInstanceDto = null; for (InstanceDTO instanceDTO : result.getContent()) { if (instanceDTO.getId() == someInstanceId) { someInstanceDto = instanceDTO; } else if (instanceDTO.getId() == anotherInstanceId) { anotherInstanceDto = instanceDTO; } } verifyInstance(someInstance, someInstanceDto); verifyInstance(anotherInstance, anotherInstanceDto); } @Test public void testGetInstancesByNamespaceAndInstanceAppId() throws Exception { String someInstanceAppId = "someInstanceAppId"; String someAppId = "someAppId"; String someClusterName = "someClusterName"; String someNamespaceName = "someNamespaceName"; String someIp = "someIp"; long someInstanceId = 1; long anotherInstanceId = 2; Instance someInstance = assembleInstance(someInstanceId, someAppId, someClusterName, someNamespaceName, someIp); Instance anotherInstance = assembleInstance(anotherInstanceId, someAppId, someClusterName, someNamespaceName, someIp); Page<Instance> instances = new PageImpl<>(Lists.newArrayList(someInstance, anotherInstance), pageable, 2); when(instanceService.findInstancesByNamespaceAndInstanceAppId(someInstanceAppId, someAppId, someClusterName, someNamespaceName, pageable)).thenReturn(instances); PageDTO<InstanceDTO> result = instanceConfigController.getInstancesByNamespace(someAppId, someClusterName, someNamespaceName, someInstanceAppId, pageable); assertEquals(2, result.getContent().size()); InstanceDTO someInstanceDto = null; InstanceDTO anotherInstanceDto = null; for (InstanceDTO instanceDTO : result.getContent()) { if (instanceDTO.getId() == someInstanceId) { someInstanceDto = instanceDTO; } else if (instanceDTO.getId() == anotherInstanceId) { anotherInstanceDto = instanceDTO; } } verifyInstance(someInstance, someInstanceDto); verifyInstance(anotherInstance, anotherInstanceDto); } @Test public void testGetInstancesCountByNamespace() throws Exception { String someAppId = "someAppId"; String someClusterName = "someClusterName"; String someNamespaceName = "someNamespaceName"; Page<Instance> instances = new PageImpl<>(Collections.emptyList(), pageable, 2); when(instanceService.findInstancesByNamespace(eq(someAppId), eq(someClusterName), eq(someNamespaceName), any(Pageable.class))).thenReturn(instances); long result = instanceConfigController.getInstancesCountByNamespace(someAppId, someClusterName, someNamespaceName); assertEquals(2, result); } private void verifyInstance(Instance instance, InstanceDTO instanceDTO) { assertEquals(instance.getId(), instanceDTO.getId()); assertEquals(instance.getAppId(), instanceDTO.getAppId()); assertEquals(instance.getClusterName(), instanceDTO.getClusterName()); assertEquals(instance.getDataCenter(), instanceDTO.getDataCenter()); assertEquals(instance.getIp(), instanceDTO.getIp()); assertEquals(instance.getDataChangeCreatedTime(), instanceDTO.getDataChangeCreatedTime()); } private Instance assembleInstance(long instanceId, String appId, String clusterName, String dataCenter, String ip) { Instance instance = new Instance(); instance.setId(instanceId); instance.setAppId(appId); instance.setIp(ip); instance.setClusterName(clusterName); instance.setDataCenter(dataCenter); instance.setDataChangeCreatedTime(new Date()); return instance; } private InstanceConfig assembleInstanceConfig(long instanceId, String configAppId, String configNamespaceName, String releaseKey, Date releaseDeliveryTime) { InstanceConfig instanceConfig = new InstanceConfig(); instanceConfig.setInstanceId(instanceId); instanceConfig.setConfigAppId(configAppId); instanceConfig.setConfigNamespaceName(configNamespaceName); instanceConfig.setReleaseKey(releaseKey); instanceConfig.setDataChangeLastModifiedTime(new Date()); instanceConfig.setReleaseDeliveryTime(releaseDeliveryTime); return instanceConfig; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/service/AccessKeyService.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.service; import com.ctrip.framework.apollo.biz.entity.AccessKey; import com.ctrip.framework.apollo.biz.entity.Audit; import com.ctrip.framework.apollo.biz.repository.AccessKeyRepository; import com.ctrip.framework.apollo.common.exception.BadRequestException; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @author nisiyong */ @Service public class AccessKeyService { private static final int ACCESSKEY_COUNT_LIMIT = 5; private final AccessKeyRepository accessKeyRepository; private final AuditService auditService; public AccessKeyService( AccessKeyRepository accessKeyRepository, AuditService auditService) { this.accessKeyRepository = accessKeyRepository; this.auditService = auditService; } public List<AccessKey> findByAppId(String appId) { return accessKeyRepository.findByAppId(appId); } @Transactional public AccessKey create(String appId, AccessKey entity) { long count = accessKeyRepository.countByAppId(appId); if (count >= ACCESSKEY_COUNT_LIMIT) { throw new BadRequestException("AccessKeys count limit exceeded"); } entity.setId(0L); entity.setAppId(appId); entity.setDataChangeLastModifiedBy(entity.getDataChangeCreatedBy()); AccessKey accessKey = accessKeyRepository.save(entity); auditService.audit(AccessKey.class.getSimpleName(), accessKey.getId(), Audit.OP.INSERT, accessKey.getDataChangeCreatedBy()); return accessKey; } @Transactional public AccessKey update(String appId, AccessKey entity) { long id = entity.getId(); String operator = entity.getDataChangeLastModifiedBy(); AccessKey accessKey = accessKeyRepository.findOneByAppIdAndId(appId, id); if (accessKey == null) { throw new BadRequestException("AccessKey not exist"); } accessKey.setEnabled(entity.isEnabled()); accessKey.setDataChangeLastModifiedBy(operator); accessKeyRepository.save(accessKey); auditService.audit(AccessKey.class.getSimpleName(), id, Audit.OP.UPDATE, operator); return accessKey; } @Transactional public void delete(String appId, long id, String operator) { AccessKey accessKey = accessKeyRepository.findOneByAppIdAndId(appId, id); if (accessKey == null) { throw new BadRequestException("AccessKey not exist"); } if (accessKey.isEnabled()) { throw new BadRequestException("AccessKey should disable first"); } accessKey.setDeleted(Boolean.TRUE); accessKey.setDataChangeLastModifiedBy(operator); accessKeyRepository.save(accessKey); auditService.audit(AccessKey.class.getSimpleName(), id, Audit.OP.DELETE, operator); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.service; import com.ctrip.framework.apollo.biz.entity.AccessKey; import com.ctrip.framework.apollo.biz.entity.Audit; import com.ctrip.framework.apollo.biz.repository.AccessKeyRepository; import com.ctrip.framework.apollo.common.exception.BadRequestException; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @author nisiyong */ @Service public class AccessKeyService { private static final int ACCESSKEY_COUNT_LIMIT = 5; private final AccessKeyRepository accessKeyRepository; private final AuditService auditService; public AccessKeyService( AccessKeyRepository accessKeyRepository, AuditService auditService) { this.accessKeyRepository = accessKeyRepository; this.auditService = auditService; } public List<AccessKey> findByAppId(String appId) { return accessKeyRepository.findByAppId(appId); } @Transactional public AccessKey create(String appId, AccessKey entity) { long count = accessKeyRepository.countByAppId(appId); if (count >= ACCESSKEY_COUNT_LIMIT) { throw new BadRequestException("AccessKeys count limit exceeded"); } entity.setId(0L); entity.setAppId(appId); entity.setDataChangeLastModifiedBy(entity.getDataChangeCreatedBy()); AccessKey accessKey = accessKeyRepository.save(entity); auditService.audit(AccessKey.class.getSimpleName(), accessKey.getId(), Audit.OP.INSERT, accessKey.getDataChangeCreatedBy()); return accessKey; } @Transactional public AccessKey update(String appId, AccessKey entity) { long id = entity.getId(); String operator = entity.getDataChangeLastModifiedBy(); AccessKey accessKey = accessKeyRepository.findOneByAppIdAndId(appId, id); if (accessKey == null) { throw new BadRequestException("AccessKey not exist"); } accessKey.setEnabled(entity.isEnabled()); accessKey.setDataChangeLastModifiedBy(operator); accessKeyRepository.save(accessKey); auditService.audit(AccessKey.class.getSimpleName(), id, Audit.OP.UPDATE, operator); return accessKey; } @Transactional public void delete(String appId, long id, String operator) { AccessKey accessKey = accessKeyRepository.findOneByAppIdAndId(appId, id); if (accessKey == null) { throw new BadRequestException("AccessKey not exist"); } if (accessKey.isEnabled()) { throw new BadRequestException("AccessKey should disable first"); } accessKey.setDeleted(Boolean.TRUE); accessKey.setDataChangeLastModifiedBy(operator); accessKeyRepository.save(accessKey); auditService.audit(AccessKey.class.getSimpleName(), id, Audit.OP.DELETE, operator); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/emailbuilder/RollbackEmailBuilder.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.component.emailbuilder; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO; import org.springframework.stereotype.Component; @Component public class RollbackEmailBuilder extends ConfigPublishEmailBuilder { private static final String EMAIL_SUBJECT = "[Apollo] 配置回滚"; @Override protected String subject() { return EMAIL_SUBJECT; } @Override protected String emailContent(Env env, ReleaseHistoryBO releaseHistory) { return renderEmailCommonContent(env, releaseHistory); } @Override protected String getTemplateFramework() { return portalConfig.emailTemplateFramework(); } @Override protected String getDiffModuleTemplate() { return portalConfig.emailRollbackDiffModuleTemplate(); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.component.emailbuilder; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO; import org.springframework.stereotype.Component; @Component public class RollbackEmailBuilder extends ConfigPublishEmailBuilder { private static final String EMAIL_SUBJECT = "[Apollo] 配置回滚"; @Override protected String subject() { return EMAIL_SUBJECT; } @Override protected String emailContent(Env env, ReleaseHistoryBO releaseHistory) { return renderEmailCommonContent(env, releaseHistory); } @Override protected String getTemplateFramework() { return portalConfig.emailTemplateFramework(); } @Override protected String getDiffModuleTemplate() { return portalConfig.emailRollbackDiffModuleTemplate(); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-common/src/test/java/com/ctrip/framework/apollo/common/utils/InputValidatorTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.common.utils; import static org.junit.Assert.*; import org.junit.Test; public class InputValidatorTest { @Test public void testValidClusterName() throws Exception { checkClusterName("some.cluster-_name.123", true); checkClusterName("some.cluster-_name.123.yml", true); checkClusterName("some.&.name", false); checkClusterName("", false); checkClusterName(null, false); } @Test public void testValidAppNamespaceName() throws Exception { checkAppNamespaceName("some.cluster-_name.123", true); checkAppNamespaceName("some.&.name", false); checkAppNamespaceName("", false); checkAppNamespaceName(null, false); checkAppNamespaceName("some.name.json", false); checkAppNamespaceName("some.name.yml", false); checkAppNamespaceName("some.name.yaml", false); checkAppNamespaceName("some.name.xml", false); checkAppNamespaceName("some.name.properties", false); } private void checkClusterName(String name, boolean valid) { assertEquals(valid, InputValidator.isValidClusterNamespace(name)); } private void checkAppNamespaceName(String name, boolean valid) { assertEquals(valid, InputValidator.isValidAppNamespace(name)); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.common.utils; import static org.junit.Assert.*; import org.junit.Test; public class InputValidatorTest { @Test public void testValidClusterName() throws Exception { checkClusterName("some.cluster-_name.123", true); checkClusterName("some.cluster-_name.123.yml", true); checkClusterName("some.&.name", false); checkClusterName("", false); checkClusterName(null, false); } @Test public void testValidAppNamespaceName() throws Exception { checkAppNamespaceName("some.cluster-_name.123", true); checkAppNamespaceName("some.&.name", false); checkAppNamespaceName("", false); checkAppNamespaceName(null, false); checkAppNamespaceName("some.name.json", false); checkAppNamespaceName("some.name.yml", false); checkAppNamespaceName("some.name.yaml", false); checkAppNamespaceName("some.name.xml", false); checkAppNamespaceName("some.name.properties", false); } private void checkClusterName(String name, boolean valid) { assertEquals(valid, InputValidator.isValidClusterNamespace(name)); } private void checkAppNamespaceName(String name, boolean valid) { assertEquals(valid, InputValidator.isValidAppNamespace(name)); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-adminservice/src/test/resources/controller/cleanup.sql
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- DELETE FROM Item; DELETE FROM Namespace; DELETE FROM AppNamespace; DELETE FROM Cluster; DELETE FROM App; DELETE FROM NamespaceLock; DELETE FROM ServerConfig;
-- -- Copyright 2021 Apollo Authors -- -- Licensed 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. -- DELETE FROM Item; DELETE FROM Namespace; DELETE FROM AppNamespace; DELETE FROM Cluster; DELETE FROM App; DELETE FROM NamespaceLock; DELETE FROM ServerConfig;
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-common/src/main/java/com/ctrip/framework/apollo/common/dto/ReleaseDTO.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.common.dto; public class ReleaseDTO extends BaseDTO{ private long id; private String releaseKey; private String name; private String appId; private String clusterName; private String namespaceName; private String configurations; private String comment; private boolean isAbandoned; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getReleaseKey() { return releaseKey; } public void setReleaseKey(String releaseKey) { this.releaseKey = releaseKey; } public String getAppId() { return appId; } public String getClusterName() { return clusterName; } public String getComment() { return comment; } public String getConfigurations() { return configurations; } public String getName() { return name; } public String getNamespaceName() { return namespaceName; } public void setAppId(String appId) { this.appId = appId; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public void setComment(String comment) { this.comment = comment; } public void setConfigurations(String configurations) { this.configurations = configurations; } public void setName(String name) { this.name = name; } public void setNamespaceName(String namespaceName) { this.namespaceName = namespaceName; } public boolean isAbandoned() { return isAbandoned; } public void setAbandoned(boolean abandoned) { isAbandoned = abandoned; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.common.dto; public class ReleaseDTO extends BaseDTO{ private long id; private String releaseKey; private String name; private String appId; private String clusterName; private String namespaceName; private String configurations; private String comment; private boolean isAbandoned; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getReleaseKey() { return releaseKey; } public void setReleaseKey(String releaseKey) { this.releaseKey = releaseKey; } public String getAppId() { return appId; } public String getClusterName() { return clusterName; } public String getComment() { return comment; } public String getConfigurations() { return configurations; } public String getName() { return name; } public String getNamespaceName() { return namespaceName; } public void setAppId(String appId) { this.appId = appId; } public void setClusterName(String clusterName) { this.clusterName = clusterName; } public void setComment(String comment) { this.comment = comment; } public void setConfigurations(String configurations) { this.configurations = configurations; } public void setName(String name) { this.name = name; } public void setNamespaceName(String namespaceName) { this.namespaceName = namespaceName; } public boolean isAbandoned() { return isAbandoned; } public void setAbandoned(boolean abandoned) { isAbandoned = abandoned; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/enricher/adapter/AppDtoUserInfoEnrichedAdapter.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.enricher.adapter; import com.ctrip.framework.apollo.common.dto.AppDTO; /** * @author vdisk <vdisk@foxmail.com> */ public class AppDtoUserInfoEnrichedAdapter implements UserInfoEnrichedAdapter { private final AppDTO dto; public AppDtoUserInfoEnrichedAdapter(AppDTO dto) { this.dto = dto; } @Override public final String getFirstUserId() { return this.dto.getDataChangeCreatedBy(); } @Override public final void setFirstUserDisplayName(String userDisplayName) { this.dto.setDataChangeCreatedByDisplayName(userDisplayName); } @Override public final String getSecondUserId() { return this.dto.getDataChangeLastModifiedBy(); } @Override public final void setSecondUserDisplayName(String userDisplayName) { this.dto.setDataChangeLastModifiedByDisplayName(userDisplayName); } @Override public final String getThirdUserId() { return this.dto.getOwnerName(); } @Override public final void setThirdUserDisplayName(String userDisplayName) { this.dto.setOwnerDisplayName(userDisplayName); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.enricher.adapter; import com.ctrip.framework.apollo.common.dto.AppDTO; /** * @author vdisk <vdisk@foxmail.com> */ public class AppDtoUserInfoEnrichedAdapter implements UserInfoEnrichedAdapter { private final AppDTO dto; public AppDtoUserInfoEnrichedAdapter(AppDTO dto) { this.dto = dto; } @Override public final String getFirstUserId() { return this.dto.getDataChangeCreatedBy(); } @Override public final void setFirstUserDisplayName(String userDisplayName) { this.dto.setDataChangeCreatedByDisplayName(userDisplayName); } @Override public final String getSecondUserId() { return this.dto.getDataChangeLastModifiedBy(); } @Override public final void setSecondUserDisplayName(String userDisplayName) { this.dto.setDataChangeLastModifiedByDisplayName(userDisplayName); } @Override public final String getThirdUserId() { return this.dto.getOwnerName(); } @Override public final void setThirdUserDisplayName(String userDisplayName) { this.dto.setOwnerDisplayName(userDisplayName); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-common/src/main/java/com/ctrip/framework/apollo/common/dto/ItemDTO.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.common.dto; public class ItemDTO extends BaseDTO{ private long id; private long namespaceId; private String key; private String value; private String comment; private int lineNum; public ItemDTO() { } public ItemDTO(String key, String value, String comment, int lineNum) { this.key = key; this.value = value; this.comment = comment; this.lineNum = lineNum; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getComment() { return comment; } public String getKey() { return key; } public long getNamespaceId() { return namespaceId; } public String getValue() { return value; } public void setComment(String comment) { this.comment = comment; } public void setKey(String key) { this.key = key; } public void setNamespaceId(long namespaceId) { this.namespaceId = namespaceId; } public void setValue(String value) { this.value = value; } public int getLineNum() { return lineNum; } public void setLineNum(int lineNum) { this.lineNum = lineNum; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.common.dto; public class ItemDTO extends BaseDTO{ private long id; private long namespaceId; private String key; private String value; private String comment; private int lineNum; public ItemDTO() { } public ItemDTO(String key, String value, String comment, int lineNum) { this.key = key; this.value = value; this.comment = comment; this.lineNum = lineNum; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getComment() { return comment; } public String getKey() { return key; } public long getNamespaceId() { return namespaceId; } public String getValue() { return value; } public void setComment(String comment) { this.comment = comment; } public void setKey(String key) { this.key = key; } public void setNamespaceId(long namespaceId) { this.namespaceId = namespaceId; } public void setValue(String value) { this.value = value; } public int getLineNum() { return lineNum; } public void setLineNum(int lineNum) { this.lineNum = lineNum; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/ConsumerController.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.controller; import com.ctrip.framework.apollo.common.dto.NamespaceDTO; import com.ctrip.framework.apollo.common.exception.BadRequestException; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.openapi.entity.Consumer; import com.ctrip.framework.apollo.openapi.entity.ConsumerRole; import com.ctrip.framework.apollo.openapi.entity.ConsumerToken; import com.ctrip.framework.apollo.openapi.service.ConsumerService; import com.ctrip.framework.apollo.portal.environment.Env; import com.google.common.base.Strings; import com.google.common.collect.Lists; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.util.*; /** * @author Jason Song(song_s@ctrip.com) */ @RestController public class ConsumerController { private static final Date DEFAULT_EXPIRES = new GregorianCalendar(2099, Calendar.JANUARY, 1).getTime(); private final ConsumerService consumerService; public ConsumerController(final ConsumerService consumerService) { this.consumerService = consumerService; } @Transactional @PreAuthorize(value = "@permissionValidator.isSuperAdmin()") @PostMapping(value = "/consumers") public ConsumerToken createConsumer(@RequestBody Consumer consumer, @RequestParam(value = "expires", required = false) @DateTimeFormat(pattern = "yyyyMMddHHmmss") Date expires) { if (StringUtils.isContainEmpty(consumer.getAppId(), consumer.getName(), consumer.getOwnerName(), consumer.getOrgId())) { throw new BadRequestException("Params(appId、name、ownerName、orgId) can not be empty."); } Consumer createdConsumer = consumerService.createConsumer(consumer); if (Objects.isNull(expires)) { expires = DEFAULT_EXPIRES; } return consumerService.generateAndSaveConsumerToken(createdConsumer, expires); } @GetMapping(value = "/consumers/by-appId") public ConsumerToken getConsumerTokenByAppId(@RequestParam String appId) { return consumerService.getConsumerTokenByAppId(appId); } @PreAuthorize(value = "@permissionValidator.isSuperAdmin()") @PostMapping(value = "/consumers/{token}/assign-role") public List<ConsumerRole> assignNamespaceRoleToConsumer(@PathVariable String token, @RequestParam String type, @RequestParam(required = false) String envs, @RequestBody NamespaceDTO namespace) { String appId = namespace.getAppId(); String namespaceName = namespace.getNamespaceName(); if (StringUtils.isEmpty(appId)) { throw new BadRequestException("Params(AppId) can not be empty."); } if (Objects.equals("AppRole", type)) { return Collections.singletonList(consumerService.assignAppRoleToConsumer(token, appId)); } if (StringUtils.isEmpty(namespaceName)) { throw new BadRequestException("Params(NamespaceName) can not be empty."); } if (null != envs){ String[] envArray = envs.split(","); List<String> envList = Lists.newArrayList(); // validate env parameter for (String env : envArray) { if (Strings.isNullOrEmpty(env)) { continue; } if (Env.UNKNOWN.equals(Env.transformEnv(env))) { throw new BadRequestException(String.format("env: %s is illegal", env)); } envList.add(env); } List<ConsumerRole> consumeRoles = new ArrayList<>(); for (String env : envList) { consumeRoles.addAll(consumerService.assignNamespaceRoleToConsumer(token, appId, namespaceName, env)); } return consumeRoles; } return consumerService.assignNamespaceRoleToConsumer(token, appId, namespaceName); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.controller; import com.ctrip.framework.apollo.common.dto.NamespaceDTO; import com.ctrip.framework.apollo.common.exception.BadRequestException; import com.ctrip.framework.apollo.core.utils.StringUtils; import com.ctrip.framework.apollo.openapi.entity.Consumer; import com.ctrip.framework.apollo.openapi.entity.ConsumerRole; import com.ctrip.framework.apollo.openapi.entity.ConsumerToken; import com.ctrip.framework.apollo.openapi.service.ConsumerService; import com.ctrip.framework.apollo.portal.environment.Env; import com.google.common.base.Strings; import com.google.common.collect.Lists; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.util.*; /** * @author Jason Song(song_s@ctrip.com) */ @RestController public class ConsumerController { private static final Date DEFAULT_EXPIRES = new GregorianCalendar(2099, Calendar.JANUARY, 1).getTime(); private final ConsumerService consumerService; public ConsumerController(final ConsumerService consumerService) { this.consumerService = consumerService; } @Transactional @PreAuthorize(value = "@permissionValidator.isSuperAdmin()") @PostMapping(value = "/consumers") public ConsumerToken createConsumer(@RequestBody Consumer consumer, @RequestParam(value = "expires", required = false) @DateTimeFormat(pattern = "yyyyMMddHHmmss") Date expires) { if (StringUtils.isContainEmpty(consumer.getAppId(), consumer.getName(), consumer.getOwnerName(), consumer.getOrgId())) { throw new BadRequestException("Params(appId、name、ownerName、orgId) can not be empty."); } Consumer createdConsumer = consumerService.createConsumer(consumer); if (Objects.isNull(expires)) { expires = DEFAULT_EXPIRES; } return consumerService.generateAndSaveConsumerToken(createdConsumer, expires); } @GetMapping(value = "/consumers/by-appId") public ConsumerToken getConsumerTokenByAppId(@RequestParam String appId) { return consumerService.getConsumerTokenByAppId(appId); } @PreAuthorize(value = "@permissionValidator.isSuperAdmin()") @PostMapping(value = "/consumers/{token}/assign-role") public List<ConsumerRole> assignNamespaceRoleToConsumer(@PathVariable String token, @RequestParam String type, @RequestParam(required = false) String envs, @RequestBody NamespaceDTO namespace) { String appId = namespace.getAppId(); String namespaceName = namespace.getNamespaceName(); if (StringUtils.isEmpty(appId)) { throw new BadRequestException("Params(AppId) can not be empty."); } if (Objects.equals("AppRole", type)) { return Collections.singletonList(consumerService.assignAppRoleToConsumer(token, appId)); } if (StringUtils.isEmpty(namespaceName)) { throw new BadRequestException("Params(NamespaceName) can not be empty."); } if (null != envs){ String[] envArray = envs.split(","); List<String> envList = Lists.newArrayList(); // validate env parameter for (String env : envArray) { if (Strings.isNullOrEmpty(env)) { continue; } if (Env.UNKNOWN.equals(Env.transformEnv(env))) { throw new BadRequestException(String.format("env: %s is illegal", env)); } envList.add(env); } List<ConsumerRole> consumeRoles = new ArrayList<>(); for (String env : envList) { consumeRoles.addAll(consumerService.assignNamespaceRoleToConsumer(token, appId, namespaceName, env)); } return consumeRoles; } return consumerService.assignNamespaceRoleToConsumer(token, appId, namespaceName); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-configservice/src/test/java/com/ctrip/framework/apollo/metaservice/service/DefaultDiscoveryServiceTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.metaservice.service; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.ctrip.framework.apollo.core.dto.ServiceDTO; import com.google.common.collect.Lists; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.shared.Application; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class DefaultDiscoveryServiceTest { @Mock private EurekaClient eurekaClient; @Mock private Application someApplication; private DefaultDiscoveryService defaultDiscoveryService; private String someServiceId; @Before public void setUp() throws Exception { defaultDiscoveryService = new DefaultDiscoveryService(eurekaClient); someServiceId = "someServiceId"; } @Test public void testGetServiceInstancesWithNullInstances() { when(eurekaClient.getApplication(someServiceId)).thenReturn(null); assertTrue(defaultDiscoveryService.getServiceInstances(someServiceId).isEmpty()); } @Test public void testGetServiceInstancesWithEmptyInstances() { when(eurekaClient.getApplication(someServiceId)).thenReturn(someApplication); when(someApplication.getInstances()).thenReturn(new ArrayList<>()); assertTrue(defaultDiscoveryService.getServiceInstances(someServiceId).isEmpty()); } @Test public void testGetServiceInstances() throws URISyntaxException { String someUri = "http://1.2.3.4:8080/some-path/"; String someInstanceId = "someInstanceId"; InstanceInfo someServiceInstance = mockServiceInstance(someServiceId, someInstanceId, someUri); String anotherUri = "http://2.3.4.5:9090/anotherPath"; String anotherInstanceId = "anotherInstanceId"; InstanceInfo anotherServiceInstance = mockServiceInstance(someServiceId, anotherInstanceId, anotherUri); when(eurekaClient.getApplication(someServiceId)).thenReturn(someApplication); when(someApplication.getInstances()) .thenReturn(Lists.newArrayList(someServiceInstance, anotherServiceInstance)); List<ServiceDTO> serviceDTOList = defaultDiscoveryService.getServiceInstances(someServiceId); assertEquals(2, serviceDTOList.size()); check(someServiceInstance, serviceDTOList.get(0)); check(anotherServiceInstance, serviceDTOList.get(1)); } private void check(InstanceInfo serviceInstance, ServiceDTO serviceDTO) { assertEquals(serviceInstance.getAppName(), serviceDTO.getAppName()); assertEquals(serviceInstance.getInstanceId(), serviceDTO.getInstanceId()); assertEquals(serviceInstance.getHomePageUrl(), serviceDTO.getHomepageUrl()); } private InstanceInfo mockServiceInstance(String serviceId, String instanceId, String homePageUrl) { InstanceInfo serviceInstance = mock(InstanceInfo.class); when(serviceInstance.getAppName()).thenReturn(serviceId); when(serviceInstance.getInstanceId()).thenReturn(instanceId); when(serviceInstance.getHomePageUrl()).thenReturn(homePageUrl); return serviceInstance; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.metaservice.service; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.ctrip.framework.apollo.core.dto.ServiceDTO; import com.google.common.collect.Lists; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.shared.Application; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class DefaultDiscoveryServiceTest { @Mock private EurekaClient eurekaClient; @Mock private Application someApplication; private DefaultDiscoveryService defaultDiscoveryService; private String someServiceId; @Before public void setUp() throws Exception { defaultDiscoveryService = new DefaultDiscoveryService(eurekaClient); someServiceId = "someServiceId"; } @Test public void testGetServiceInstancesWithNullInstances() { when(eurekaClient.getApplication(someServiceId)).thenReturn(null); assertTrue(defaultDiscoveryService.getServiceInstances(someServiceId).isEmpty()); } @Test public void testGetServiceInstancesWithEmptyInstances() { when(eurekaClient.getApplication(someServiceId)).thenReturn(someApplication); when(someApplication.getInstances()).thenReturn(new ArrayList<>()); assertTrue(defaultDiscoveryService.getServiceInstances(someServiceId).isEmpty()); } @Test public void testGetServiceInstances() throws URISyntaxException { String someUri = "http://1.2.3.4:8080/some-path/"; String someInstanceId = "someInstanceId"; InstanceInfo someServiceInstance = mockServiceInstance(someServiceId, someInstanceId, someUri); String anotherUri = "http://2.3.4.5:9090/anotherPath"; String anotherInstanceId = "anotherInstanceId"; InstanceInfo anotherServiceInstance = mockServiceInstance(someServiceId, anotherInstanceId, anotherUri); when(eurekaClient.getApplication(someServiceId)).thenReturn(someApplication); when(someApplication.getInstances()) .thenReturn(Lists.newArrayList(someServiceInstance, anotherServiceInstance)); List<ServiceDTO> serviceDTOList = defaultDiscoveryService.getServiceInstances(someServiceId); assertEquals(2, serviceDTOList.size()); check(someServiceInstance, serviceDTOList.get(0)); check(anotherServiceInstance, serviceDTOList.get(1)); } private void check(InstanceInfo serviceInstance, ServiceDTO serviceDTO) { assertEquals(serviceInstance.getAppName(), serviceDTO.getAppName()); assertEquals(serviceInstance.getInstanceId(), serviceDTO.getInstanceId()); assertEquals(serviceInstance.getHomePageUrl(), serviceDTO.getHomepageUrl()); } private InstanceInfo mockServiceInstance(String serviceId, String instanceId, String homePageUrl) { InstanceInfo serviceInstance = mock(InstanceInfo.class); when(serviceInstance.getAppName()).thenReturn(serviceId); when(serviceInstance.getInstanceId()).thenReturn(instanceId); when(serviceInstance.getHomePageUrl()).thenReturn(homePageUrl); return serviceInstance; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/SystemRoleManagerService.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.service; import com.ctrip.framework.apollo.portal.component.config.PortalConfig; import com.ctrip.framework.apollo.portal.constant.PermissionType; import com.ctrip.framework.apollo.portal.util.RoleUtils; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SystemRoleManagerService { public static final Logger logger = LoggerFactory.getLogger(SystemRoleManagerService.class); public static final String SYSTEM_PERMISSION_TARGET_ID = "SystemRole"; public static final String CREATE_APPLICATION_ROLE_NAME = RoleUtils.buildCreateApplicationRoleName(PermissionType.CREATE_APPLICATION, SYSTEM_PERMISSION_TARGET_ID); public static final String CREATE_APPLICATION_LIMIT_SWITCH_KEY = "role.create-application.enabled"; public static final String MANAGE_APP_MASTER_LIMIT_SWITCH_KEY = "role.manage-app-master.enabled"; private final RolePermissionService rolePermissionService; private final PortalConfig portalConfig; private final RoleInitializationService roleInitializationService; @Autowired public SystemRoleManagerService(final RolePermissionService rolePermissionService, final PortalConfig portalConfig, final RoleInitializationService roleInitializationService) { this.rolePermissionService = rolePermissionService; this.portalConfig = portalConfig; this.roleInitializationService = roleInitializationService; } @PostConstruct private void init() { roleInitializationService.initCreateAppRole(); } private boolean isCreateApplicationPermissionEnabled() { return portalConfig.isCreateApplicationPermissionEnabled(); } public boolean isManageAppMasterPermissionEnabled() { return portalConfig.isManageAppMasterPermissionEnabled(); } public boolean hasCreateApplicationPermission(String userId) { if (!isCreateApplicationPermissionEnabled()) { return true; } return rolePermissionService.userHasPermission(userId, PermissionType.CREATE_APPLICATION, SYSTEM_PERMISSION_TARGET_ID); } public boolean hasManageAppMasterPermission(String userId, String appId) { if (!isManageAppMasterPermissionEnabled()) { return true; } return rolePermissionService.userHasPermission(userId, PermissionType.MANAGE_APP_MASTER, appId); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.service; import com.ctrip.framework.apollo.portal.component.config.PortalConfig; import com.ctrip.framework.apollo.portal.constant.PermissionType; import com.ctrip.framework.apollo.portal.util.RoleUtils; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SystemRoleManagerService { public static final Logger logger = LoggerFactory.getLogger(SystemRoleManagerService.class); public static final String SYSTEM_PERMISSION_TARGET_ID = "SystemRole"; public static final String CREATE_APPLICATION_ROLE_NAME = RoleUtils.buildCreateApplicationRoleName(PermissionType.CREATE_APPLICATION, SYSTEM_PERMISSION_TARGET_ID); public static final String CREATE_APPLICATION_LIMIT_SWITCH_KEY = "role.create-application.enabled"; public static final String MANAGE_APP_MASTER_LIMIT_SWITCH_KEY = "role.manage-app-master.enabled"; private final RolePermissionService rolePermissionService; private final PortalConfig portalConfig; private final RoleInitializationService roleInitializationService; @Autowired public SystemRoleManagerService(final RolePermissionService rolePermissionService, final PortalConfig portalConfig, final RoleInitializationService roleInitializationService) { this.rolePermissionService = rolePermissionService; this.portalConfig = portalConfig; this.roleInitializationService = roleInitializationService; } @PostConstruct private void init() { roleInitializationService.initCreateAppRole(); } private boolean isCreateApplicationPermissionEnabled() { return portalConfig.isCreateApplicationPermissionEnabled(); } public boolean isManageAppMasterPermissionEnabled() { return portalConfig.isManageAppMasterPermissionEnabled(); } public boolean hasCreateApplicationPermission(String userId) { if (!isCreateApplicationPermissionEnabled()) { return true; } return rolePermissionService.userHasPermission(userId, PermissionType.CREATE_APPLICATION, SYSTEM_PERMISSION_TARGET_ID); } public boolean hasManageAppMasterPermission(String userId, String appId) { if (!isManageAppMasterPermissionEnabled()) { return true; } return rolePermissionService.userHasPermission(userId, PermissionType.MANAGE_APP_MASTER, appId); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/test/java/com/ctrip/framework/apollo/portal/service/ConfigServiceTest.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.service; import com.ctrip.framework.apollo.common.dto.ItemChangeSets; import com.ctrip.framework.apollo.common.dto.ItemDTO; import com.ctrip.framework.apollo.common.dto.NamespaceDTO; import com.ctrip.framework.apollo.core.ConfigConsts; import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.portal.AbstractUnitTest; import com.ctrip.framework.apollo.portal.api.AdminServiceAPI; import com.ctrip.framework.apollo.portal.spi.UserInfoHolder; import com.ctrip.framework.apollo.portal.entity.bo.UserInfo; import com.ctrip.framework.apollo.portal.component.txtresolver.PropertyResolver; import com.ctrip.framework.apollo.portal.entity.model.NamespaceTextModel; import com.ctrip.framework.apollo.portal.entity.vo.ItemDiffs; import com.ctrip.framework.apollo.portal.entity.vo.NamespaceIdentifier; import java.util.Collections; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.test.util.ReflectionTestUtils; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ConfigServiceTest extends AbstractUnitTest { @Mock private AdminServiceAPI.NamespaceAPI namespaceAPI; @Mock private AdminServiceAPI.ReleaseAPI releaseAPI; @Mock private AdminServiceAPI.ItemAPI itemAPI; @Mock private PropertyResolver resolver; @Mock private UserInfoHolder userInfoHolder; @InjectMocks private ItemService configService; @Before public void setup() { ReflectionTestUtils.setField(configService, "propertyResolver", resolver); } @Test public void testUpdateConfigByText() { String appId = "6666"; String clusterName = "default"; String namespaceName = "application"; long someNamespaceId = 123L; NamespaceTextModel model = new NamespaceTextModel(); model.setEnv("DEV"); model.setNamespaceName(namespaceName); model.setClusterName(clusterName); model.setAppId(appId); model.setConfigText("a=b\nb=c\nc=d\nd=e"); model.setFormat(ConfigFileFormat.Properties.getValue()); List<ItemDTO> itemDTOs = mockBaseItemHas3Key(); ItemChangeSets changeSets = new ItemChangeSets(); changeSets.addCreateItem(new ItemDTO("d", "c", "", 4)); NamespaceDTO someNamespaceDto = mock(NamespaceDTO.class); when(someNamespaceDto.getId()).thenReturn(someNamespaceId); when(namespaceAPI.loadNamespace(appId, model.getEnv(), clusterName, namespaceName)) .thenReturn(someNamespaceDto); when(itemAPI.findItems(appId, Env.DEV, clusterName, namespaceName)).thenReturn(itemDTOs); when(resolver.resolve(someNamespaceId, model.getConfigText(), itemDTOs)).thenReturn(changeSets); UserInfo userInfo = new UserInfo(); userInfo.setUserId("test"); when(userInfoHolder.getUser()).thenReturn(userInfo); try { configService.updateConfigItemByText(model); } catch (Exception e) { Assert.fail(); } } /** * a=b b=c c=d */ private List<ItemDTO> mockBaseItemHas3Key() { ItemDTO item1 = new ItemDTO("a", "b", "", 1); ItemDTO item2 = new ItemDTO("b", "c", "", 2); ItemDTO item3 = new ItemDTO("c", "d", "", 3); return Arrays.asList(item1, item2, item3); } @Test public void testCompareTargetNamespaceHasNoItems() { ItemDTO sourceItem1 = new ItemDTO("a", "b", "comment", 1); List<ItemDTO> sourceItems = Collections.singletonList(sourceItem1); String appId = "6666", env = "LOCAL", clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT, namespaceName = ConfigConsts.NAMESPACE_APPLICATION; List<NamespaceIdentifier> namespaceIdentifiers = generateNamespaceIdentifier(appId, env, clusterName, namespaceName); NamespaceDTO namespaceDTO = generateNamespaceDTO(appId, clusterName, namespaceName); when(namespaceAPI.loadNamespace(appId, Env.valueOf(env), clusterName, namespaceName)).thenReturn(namespaceDTO); when(itemAPI.findItems(appId, Env.valueOf(env), clusterName, namespaceName)).thenReturn(null); UserInfo userInfo = new UserInfo(); userInfo.setUserId("test"); when(userInfoHolder.getUser()).thenReturn(userInfo); List<ItemDiffs> itemDiffses = configService.compare(namespaceIdentifiers, sourceItems); assertEquals(1, itemDiffses.size()); ItemDiffs itemDiffs = itemDiffses.get(0); ItemChangeSets changeSets = itemDiffs.getDiffs(); assertEquals(0, changeSets.getUpdateItems().size()); assertEquals(0, changeSets.getDeleteItems().size()); List<ItemDTO> createItems = changeSets.getCreateItems(); ItemDTO createItem = createItems.get(0); assertEquals(1, createItem.getLineNum()); assertEquals("a", createItem.getKey()); assertEquals("b", createItem.getValue()); assertEquals("comment", createItem.getComment()); } @Test public void testCompare() { ItemDTO sourceItem1 = new ItemDTO("a", "b", "comment", 1);//not modified ItemDTO sourceItem2 = new ItemDTO("newKey", "c", "comment", 2);//new item ItemDTO sourceItem3 = new ItemDTO("c", "newValue", "comment", 3);// update value ItemDTO sourceItem4 = new ItemDTO("d", "b", "newComment", 4);// update comment List<ItemDTO> sourceItems = Arrays.asList(sourceItem1, sourceItem2, sourceItem3, sourceItem4); ItemDTO targetItem1 = new ItemDTO("a", "b", "comment", 1); ItemDTO targetItem2 = new ItemDTO("c", "oldValue", "comment", 2); ItemDTO targetItem3 = new ItemDTO("d", "b", "oldComment", 3); List<ItemDTO> targetItems = Arrays.asList(targetItem1, targetItem2, targetItem3); String appId = "6666", env = "LOCAL", clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT, namespaceName = ConfigConsts.NAMESPACE_APPLICATION; List<NamespaceIdentifier> namespaceIdentifiers = generateNamespaceIdentifier(appId, env, clusterName, namespaceName); NamespaceDTO namespaceDTO = generateNamespaceDTO(appId, clusterName, namespaceName); when(namespaceAPI.loadNamespace(appId, Env.valueOf(env), clusterName, namespaceName)).thenReturn(namespaceDTO); when(itemAPI.findItems(appId, Env.valueOf(env), clusterName, namespaceName)).thenReturn(targetItems); UserInfo userInfo = new UserInfo(); userInfo.setUserId("test"); when(userInfoHolder.getUser()).thenReturn(userInfo); List<ItemDiffs> itemDiffses = configService.compare(namespaceIdentifiers, sourceItems); assertEquals(1, itemDiffses.size()); ItemDiffs itemDiffs = itemDiffses.get(0); ItemChangeSets changeSets = itemDiffs.getDiffs(); assertEquals(0, changeSets.getDeleteItems().size()); assertEquals(2, changeSets.getUpdateItems().size()); assertEquals(1, changeSets.getCreateItems().size()); NamespaceIdentifier namespaceIdentifier = itemDiffs.getNamespace(); assertEquals(appId, namespaceIdentifier.getAppId()); assertEquals(Env.valueOf("LOCAL"), namespaceIdentifier.getEnv()); assertEquals(clusterName, namespaceIdentifier.getClusterName()); assertEquals(namespaceName, namespaceIdentifier.getNamespaceName()); ItemDTO createdItem = changeSets.getCreateItems().get(0); assertEquals("newKey", createdItem.getKey()); assertEquals("c", createdItem.getValue()); assertEquals("comment", createdItem.getComment()); assertEquals(4, createdItem.getLineNum()); List<ItemDTO> updateItems = changeSets.getUpdateItems(); ItemDTO updateItem1 = updateItems.get(0); ItemDTO updateItem2 = updateItems.get(1); assertEquals("c", updateItem1.getKey()); assertEquals("newValue", updateItem1.getValue()); assertEquals("comment", updateItem1.getComment()); assertEquals(2, updateItem1.getLineNum()); assertEquals("d", updateItem2.getKey()); assertEquals("b", updateItem2.getValue()); assertEquals("newComment", updateItem2.getComment()); assertEquals(3, updateItem2.getLineNum()); } private NamespaceDTO generateNamespaceDTO(String appId, String clusterName, String namespaceName) { NamespaceDTO namespaceDTO = new NamespaceDTO(); namespaceDTO.setAppId(appId); namespaceDTO.setId(1); namespaceDTO.setClusterName(clusterName); namespaceDTO.setNamespaceName(namespaceName); return namespaceDTO; } private List<NamespaceIdentifier> generateNamespaceIdentifier(String appId, String env, String clusterName, String namespaceName) { NamespaceIdentifier targetNamespace = new NamespaceIdentifier(); targetNamespace.setAppId(appId); targetNamespace.setEnv(env); targetNamespace.setClusterName(clusterName); targetNamespace.setNamespaceName(namespaceName); return Collections.singletonList(targetNamespace); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.service; import com.ctrip.framework.apollo.common.dto.ItemChangeSets; import com.ctrip.framework.apollo.common.dto.ItemDTO; import com.ctrip.framework.apollo.common.dto.NamespaceDTO; import com.ctrip.framework.apollo.core.ConfigConsts; import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.portal.AbstractUnitTest; import com.ctrip.framework.apollo.portal.api.AdminServiceAPI; import com.ctrip.framework.apollo.portal.spi.UserInfoHolder; import com.ctrip.framework.apollo.portal.entity.bo.UserInfo; import com.ctrip.framework.apollo.portal.component.txtresolver.PropertyResolver; import com.ctrip.framework.apollo.portal.entity.model.NamespaceTextModel; import com.ctrip.framework.apollo.portal.entity.vo.ItemDiffs; import com.ctrip.framework.apollo.portal.entity.vo.NamespaceIdentifier; import java.util.Collections; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.test.util.ReflectionTestUtils; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ConfigServiceTest extends AbstractUnitTest { @Mock private AdminServiceAPI.NamespaceAPI namespaceAPI; @Mock private AdminServiceAPI.ReleaseAPI releaseAPI; @Mock private AdminServiceAPI.ItemAPI itemAPI; @Mock private PropertyResolver resolver; @Mock private UserInfoHolder userInfoHolder; @InjectMocks private ItemService configService; @Before public void setup() { ReflectionTestUtils.setField(configService, "propertyResolver", resolver); } @Test public void testUpdateConfigByText() { String appId = "6666"; String clusterName = "default"; String namespaceName = "application"; long someNamespaceId = 123L; NamespaceTextModel model = new NamespaceTextModel(); model.setEnv("DEV"); model.setNamespaceName(namespaceName); model.setClusterName(clusterName); model.setAppId(appId); model.setConfigText("a=b\nb=c\nc=d\nd=e"); model.setFormat(ConfigFileFormat.Properties.getValue()); List<ItemDTO> itemDTOs = mockBaseItemHas3Key(); ItemChangeSets changeSets = new ItemChangeSets(); changeSets.addCreateItem(new ItemDTO("d", "c", "", 4)); NamespaceDTO someNamespaceDto = mock(NamespaceDTO.class); when(someNamespaceDto.getId()).thenReturn(someNamespaceId); when(namespaceAPI.loadNamespace(appId, model.getEnv(), clusterName, namespaceName)) .thenReturn(someNamespaceDto); when(itemAPI.findItems(appId, Env.DEV, clusterName, namespaceName)).thenReturn(itemDTOs); when(resolver.resolve(someNamespaceId, model.getConfigText(), itemDTOs)).thenReturn(changeSets); UserInfo userInfo = new UserInfo(); userInfo.setUserId("test"); when(userInfoHolder.getUser()).thenReturn(userInfo); try { configService.updateConfigItemByText(model); } catch (Exception e) { Assert.fail(); } } /** * a=b b=c c=d */ private List<ItemDTO> mockBaseItemHas3Key() { ItemDTO item1 = new ItemDTO("a", "b", "", 1); ItemDTO item2 = new ItemDTO("b", "c", "", 2); ItemDTO item3 = new ItemDTO("c", "d", "", 3); return Arrays.asList(item1, item2, item3); } @Test public void testCompareTargetNamespaceHasNoItems() { ItemDTO sourceItem1 = new ItemDTO("a", "b", "comment", 1); List<ItemDTO> sourceItems = Collections.singletonList(sourceItem1); String appId = "6666", env = "LOCAL", clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT, namespaceName = ConfigConsts.NAMESPACE_APPLICATION; List<NamespaceIdentifier> namespaceIdentifiers = generateNamespaceIdentifier(appId, env, clusterName, namespaceName); NamespaceDTO namespaceDTO = generateNamespaceDTO(appId, clusterName, namespaceName); when(namespaceAPI.loadNamespace(appId, Env.valueOf(env), clusterName, namespaceName)).thenReturn(namespaceDTO); when(itemAPI.findItems(appId, Env.valueOf(env), clusterName, namespaceName)).thenReturn(null); UserInfo userInfo = new UserInfo(); userInfo.setUserId("test"); when(userInfoHolder.getUser()).thenReturn(userInfo); List<ItemDiffs> itemDiffses = configService.compare(namespaceIdentifiers, sourceItems); assertEquals(1, itemDiffses.size()); ItemDiffs itemDiffs = itemDiffses.get(0); ItemChangeSets changeSets = itemDiffs.getDiffs(); assertEquals(0, changeSets.getUpdateItems().size()); assertEquals(0, changeSets.getDeleteItems().size()); List<ItemDTO> createItems = changeSets.getCreateItems(); ItemDTO createItem = createItems.get(0); assertEquals(1, createItem.getLineNum()); assertEquals("a", createItem.getKey()); assertEquals("b", createItem.getValue()); assertEquals("comment", createItem.getComment()); } @Test public void testCompare() { ItemDTO sourceItem1 = new ItemDTO("a", "b", "comment", 1);//not modified ItemDTO sourceItem2 = new ItemDTO("newKey", "c", "comment", 2);//new item ItemDTO sourceItem3 = new ItemDTO("c", "newValue", "comment", 3);// update value ItemDTO sourceItem4 = new ItemDTO("d", "b", "newComment", 4);// update comment List<ItemDTO> sourceItems = Arrays.asList(sourceItem1, sourceItem2, sourceItem3, sourceItem4); ItemDTO targetItem1 = new ItemDTO("a", "b", "comment", 1); ItemDTO targetItem2 = new ItemDTO("c", "oldValue", "comment", 2); ItemDTO targetItem3 = new ItemDTO("d", "b", "oldComment", 3); List<ItemDTO> targetItems = Arrays.asList(targetItem1, targetItem2, targetItem3); String appId = "6666", env = "LOCAL", clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT, namespaceName = ConfigConsts.NAMESPACE_APPLICATION; List<NamespaceIdentifier> namespaceIdentifiers = generateNamespaceIdentifier(appId, env, clusterName, namespaceName); NamespaceDTO namespaceDTO = generateNamespaceDTO(appId, clusterName, namespaceName); when(namespaceAPI.loadNamespace(appId, Env.valueOf(env), clusterName, namespaceName)).thenReturn(namespaceDTO); when(itemAPI.findItems(appId, Env.valueOf(env), clusterName, namespaceName)).thenReturn(targetItems); UserInfo userInfo = new UserInfo(); userInfo.setUserId("test"); when(userInfoHolder.getUser()).thenReturn(userInfo); List<ItemDiffs> itemDiffses = configService.compare(namespaceIdentifiers, sourceItems); assertEquals(1, itemDiffses.size()); ItemDiffs itemDiffs = itemDiffses.get(0); ItemChangeSets changeSets = itemDiffs.getDiffs(); assertEquals(0, changeSets.getDeleteItems().size()); assertEquals(2, changeSets.getUpdateItems().size()); assertEquals(1, changeSets.getCreateItems().size()); NamespaceIdentifier namespaceIdentifier = itemDiffs.getNamespace(); assertEquals(appId, namespaceIdentifier.getAppId()); assertEquals(Env.valueOf("LOCAL"), namespaceIdentifier.getEnv()); assertEquals(clusterName, namespaceIdentifier.getClusterName()); assertEquals(namespaceName, namespaceIdentifier.getNamespaceName()); ItemDTO createdItem = changeSets.getCreateItems().get(0); assertEquals("newKey", createdItem.getKey()); assertEquals("c", createdItem.getValue()); assertEquals("comment", createdItem.getComment()); assertEquals(4, createdItem.getLineNum()); List<ItemDTO> updateItems = changeSets.getUpdateItems(); ItemDTO updateItem1 = updateItems.get(0); ItemDTO updateItem2 = updateItems.get(1); assertEquals("c", updateItem1.getKey()); assertEquals("newValue", updateItem1.getValue()); assertEquals("comment", updateItem1.getComment()); assertEquals(2, updateItem1.getLineNum()); assertEquals("d", updateItem2.getKey()); assertEquals("b", updateItem2.getValue()); assertEquals("newComment", updateItem2.getComment()); assertEquals(3, updateItem2.getLineNum()); } private NamespaceDTO generateNamespaceDTO(String appId, String clusterName, String namespaceName) { NamespaceDTO namespaceDTO = new NamespaceDTO(); namespaceDTO.setAppId(appId); namespaceDTO.setId(1); namespaceDTO.setClusterName(clusterName); namespaceDTO.setNamespaceName(namespaceName); return namespaceDTO; } private List<NamespaceIdentifier> generateNamespaceIdentifier(String appId, String env, String clusterName, String namespaceName) { NamespaceIdentifier targetNamespace = new NamespaceIdentifier(); targetNamespace.setAppId(appId); targetNamespace.setEnv(env); targetNamespace.setClusterName(clusterName); targetNamespace.setNamespaceName(namespaceName); return Collections.singletonList(targetNamespace); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/repository/AppNamespaceRepository.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.repository; import com.ctrip.framework.apollo.common.entity.AppNamespace; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import java.util.List; import java.util.Set; public interface AppNamespaceRepository extends PagingAndSortingRepository<AppNamespace, Long>{ AppNamespace findByAppIdAndName(String appId, String namespaceName); List<AppNamespace> findByAppIdAndNameIn(String appId, Set<String> namespaceNames); AppNamespace findByNameAndIsPublicTrue(String namespaceName); List<AppNamespace> findByNameInAndIsPublicTrue(Set<String> namespaceNames); List<AppNamespace> findByAppIdAndIsPublic(String appId, boolean isPublic); List<AppNamespace> findByAppId(String appId); List<AppNamespace> findFirst500ByIdGreaterThanOrderByIdAsc(long id); @Modifying @Query("UPDATE AppNamespace SET IsDeleted=1,DataChange_LastModifiedBy = ?2 WHERE AppId=?1") int batchDeleteByAppId(String appId, String operator); @Modifying @Query("UPDATE AppNamespace SET IsDeleted=1,DataChange_LastModifiedBy = ?3 WHERE AppId=?1 and Name = ?2") int delete(String appId, String namespaceName, String operator); }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.biz.repository; import com.ctrip.framework.apollo.common.entity.AppNamespace; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import java.util.List; import java.util.Set; public interface AppNamespaceRepository extends PagingAndSortingRepository<AppNamespace, Long>{ AppNamespace findByAppIdAndName(String appId, String namespaceName); List<AppNamespace> findByAppIdAndNameIn(String appId, Set<String> namespaceNames); AppNamespace findByNameAndIsPublicTrue(String namespaceName); List<AppNamespace> findByNameInAndIsPublicTrue(Set<String> namespaceNames); List<AppNamespace> findByAppIdAndIsPublic(String appId, boolean isPublic); List<AppNamespace> findByAppId(String appId); List<AppNamespace> findFirst500ByIdGreaterThanOrderByIdAsc(long id); @Modifying @Query("UPDATE AppNamespace SET IsDeleted=1,DataChange_LastModifiedBy = ?2 WHERE AppId=?1") int batchDeleteByAppId(String appId, String operator); @Modifying @Query("UPDATE AppNamespace SET IsDeleted=1,DataChange_LastModifiedBy = ?3 WHERE AppId=?1 and Name = ?2") int delete(String appId, String namespaceName, String operator); }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/TestProcessorHelper.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.spring.spi; import org.springframework.beans.BeansException; import org.springframework.beans.factory.support.BeanDefinitionRegistry; public class TestProcessorHelper extends DefaultConfigPropertySourcesProcessorHelper { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { super.postProcessBeanDefinitionRegistry(registry); } @Override public int getOrder() { return 0; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.spring.spi; import org.springframework.beans.BeansException; import org.springframework.beans.factory.support.BeanDefinitionRegistry; public class TestProcessorHelper extends DefaultConfigPropertySourcesProcessorHelper { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { super.postProcessBeanDefinitionRegistry(registry); } @Override public int getOrder() { return 0; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/po/Favorite.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.entity.po; import com.ctrip.framework.apollo.common.entity.BaseEntity; import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.Where; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "Favorite") @SQLDelete(sql = "Update Favorite set isDeleted = 1 where id = ?") @Where(clause = "isDeleted = 0") public class Favorite extends BaseEntity { @Column(name = "AppId", nullable = false) private String appId; @Column(name = "UserId", nullable = false) private String userId; @Column(name = "Position") private long position; public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public long getPosition() { return position; } public void setPosition(long position) { this.position = position; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.entity.po; import com.ctrip.framework.apollo.common.entity.BaseEntity; import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.Where; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "Favorite") @SQLDelete(sql = "Update Favorite set isDeleted = 1 where id = ?") @Where(clause = "isDeleted = 0") public class Favorite extends BaseEntity { @Column(name = "AppId", nullable = false) private String appId; @Column(name = "UserId", nullable = false) private String userId; @Column(name = "Position") private long position; public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public long getPosition() { return position; } public void setPosition(long position) { this.position = position; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/bo/ItemBO.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.entity.bo; import com.ctrip.framework.apollo.common.dto.ItemDTO; public class ItemBO { private ItemDTO item; private boolean isModified; private boolean isDeleted; private String oldValue; private String newValue; public ItemDTO getItem() { return item; } public void setItem(ItemDTO item) { this.item = item; } public boolean isDeleted() { return isDeleted; } public void setDeleted(boolean deleted) { isDeleted = deleted; } public boolean isModified() { return isModified; } public void setModified(boolean isModified) { this.isModified = isModified; } public String getOldValue() { return oldValue; } public void setOldValue(String oldValue) { this.oldValue = oldValue; } public String getNewValue() { return newValue; } public void setNewValue(String newValue) { this.newValue = newValue; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.entity.bo; import com.ctrip.framework.apollo.common.dto.ItemDTO; public class ItemBO { private ItemDTO item; private boolean isModified; private boolean isDeleted; private String oldValue; private String newValue; public ItemDTO getItem() { return item; } public void setItem(ItemDTO item) { this.item = item; } public boolean isDeleted() { return isDeleted; } public void setDeleted(boolean deleted) { isDeleted = deleted; } public boolean isModified() { return isModified; } public void setModified(boolean isModified) { this.isModified = isModified; } public String getOldValue() { return oldValue; } public void setOldValue(String oldValue) { this.oldValue = oldValue; } public String getNewValue() { return newValue; } public void setNewValue(String newValue) { this.newValue = newValue; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/resources/static/namespace/role.html
<!-- ~ Copyright 2021 Apollo Authors ~ ~ Licensed 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. ~ --> <!doctype html> <html ng-app="role"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="icon" href="../img/config.png"> <!-- styles --> <link rel="stylesheet" type="text/css" href="../vendor/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="../vendor/angular/angular-toastr-1.4.1.min.css"> <link rel="stylesheet" type="text/css" media='all' href="../vendor/angular/loading-bar.min.css"> <link rel="stylesheet" type="text/css" href="../styles/common-style.css"> <link rel="stylesheet" type="text/css" href="../vendor/select2/select2.min.css"> <title>{{'Namespace.Role.Title' | translate }}</title> </head> <body> <apollonav></apollonav> <div class="container-fluid apollo-container"> <section class="panel col-md-offset-1 col-md-10" ng-controller="NamespaceRoleController"> <header class="panel-heading"> <div class="row"> <div class="col-md-9"> <h4 class="modal-title"> {{'Namespace.Role.Title' | translate }}<small>({{'Common.AppId' | translate }}:<label ng-bind="pageContext.appId"></label> {{'Common.Namespace' | translate }}:<label ng-bind="pageContext.namespaceName"></label>)</small> </h4> </div> <div class="col-md-3 text-right"> <a type="button" class="btn btn-info" data-dismiss="modal" href="{{ '/config.html' | prefixPath }}?#appid={{pageContext.appId}}">{{'Common.ReturnToIndex' | translate }} </a> </div> </div> </header> <div class="panel-body" ng-show="hasAssignUserPermission"> <div class="row"> <div class="form-horizontal"> <div class="form-group"> <label class="col-sm-2 control-label">{{'Namespace.Role.GrantModifyTo' | translate }}<br><small>{{'Namespace.Role.GrantModifyTo2' | translate }}</small></label> <div class="col-sm-8"> <form class="form-inline" ng-submit="assignRoleToUser('ModifyNamespace')"> <div class="form-group"> <apollouserselector apollo-id="modifyRoleWidgetId"></apollouserselector> <select class="form-control input-sm" ng-model="modifyRoleSelectedEnv"> <option value="">{{'Namespace.Role.AllEnv' | translate }}</option> <option ng-repeat="env in envs" ng-value="env">{{env}}</option> </select> </div> <button type="submit" class="btn btn-default" style="margin-left: 20px;" ng-disabled="modifyRoleSubmitBtnDisabled">{{'Namespace.Role.Add' | translate }}</button> </form> <!-- Split button --> <div class="item-container"> <h5>{{'Namespace.Role.AllEnv' | translate }}</h5> <div class="btn-group item-info" ng-repeat="user in rolesAssignedUsers.modifyRoleUsers"> <button type="button" class="btn btn-default" ng-bind="user.userId"></button> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" ng-click="removeUserRole('ModifyNamespace', user.userId, null)"> <span class="glyphicon glyphicon-remove"></span> </button> </div> </div> <div class="item-container" ng-repeat="env in envs"> <h5>{{env}}</h5> <div class="btn-group item-info" ng-repeat="user in envRolesAssignedUsers[env].modifyRoleUsers"> <button type="button" class="btn btn-default" ng-bind="user.userId"></button> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" ng-click="removeUserRole('ModifyNamespace', user.userId, env)"> <span class="glyphicon glyphicon-remove"></span> </button> </div> </div> </div> </div> </div> <hr> <div class="row" style="margin-top: 10px;"> <div class="form-horizontal"> <div class="col-sm-2 text-right"> <label class="control-label">{{'Namespace.Role.GrantPublishTo' | translate }}<br><small>{{'Namespace.Role.GrantPublishTo2' | translate }}</small></label> </div> <div class="col-sm-8"> <form class="form-inline" ng-submit="assignRoleToUser('ReleaseNamespace')"> <div class="form-group"> <apollouserselector apollo-id="releaseRoleWidgetId"></apollouserselector> <select class="form-control input-sm" ng-model="releaseRoleSelectedEnv"> <option value="">{{'Namespace.Role.AllEnv' | translate }}</option> <option ng-repeat="env in envs" ng-value="env">{{env}}</option> </select> </div> <button type="submit" class="btn btn-default" style="margin-left: 20px;" ng-disabled="ReleaseRoleSubmitBtnDisabled">{{'Namespace.Role.Add' | translate }}</button> </form> <!-- Split button --> <div class="item-container"> <h5>{{'Namespace.Role.AllEnv' | translate }}</h5> <div class="btn-group item-info" ng-repeat="user in rolesAssignedUsers.releaseRoleUsers"> <button type="button" class="btn btn-default" ng-bind="user.userId"></button> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" ng-click="removeUserRole('ReleaseNamespace', user.userId, null)"> <span class="glyphicon glyphicon-remove"></span> </button> </div> </div> <div class="item-container" ng-repeat="env in envs"> <h5>{{env}}</h5> <div class="btn-group item-info" ng-repeat="user in envRolesAssignedUsers[env].releaseRoleUsers"> <button type="button" class="btn btn-default" ng-bind="user.userId"></button> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" ng-click="removeUserRole('ReleaseNamespace', user.userId, env)"> <span class="glyphicon glyphicon-remove"></span> </button> </div> </div> </div> </div> </div> </div> </div> <div class="panel-body text-center" ng-show="!hasAssignUserPermission"> <h2>{{'Namespace.Role.NoPermission' | translate }}</h2> </div> </section> </div> <div ng-include="'../views/common/footer.html'"></div> <!-- jquery.js --> <script src="../vendor/jquery.min.js" type="text/javascript"></script> <!--angular--> <script src="../vendor/angular/angular.min.js"></script> <script src="../vendor/angular/angular-resource.min.js"></script> <script src="../vendor/angular/angular-toastr-1.4.1.tpls.min.js"></script> <script src="../vendor/angular/loading-bar.min.js"></script> <script src="../vendor/angular/angular-cookies.min.js"></script> <script src="../vendor/angular/angular-translate.2.18.1/angular-translate.min.js"></script> <script src="../vendor/angular/angular-translate.2.18.1/angular-translate-loader-static-files.min.js"></script> <script src="../vendor/angular/angular-translate.2.18.1/angular-translate-storage-cookie.min.js"></script> <!-- bootstrap.js --> <script src="../vendor/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="../vendor/select2/select2.min.js" type="text/javascript"></script> <!--biz--> <!--must import--> <script type="application/javascript" src="../scripts/app.js"></script> <script type="application/javascript" src="../scripts/services/AppService.js"></script> <script type="application/javascript" src="../scripts/services/EnvService.js"></script> <script type="application/javascript" src="../scripts/services/UserService.js"></script> <script type="application/javascript" src="../scripts/services/CommonService.js"></script> <script type="application/javascript" src="../scripts/services/PermissionService.js"></script> <script type="application/javascript" src="../scripts/AppUtils.js"></script> <script type="application/javascript" src="../scripts/PageCommon.js"></script> <script type="application/javascript" src="../scripts/directive/directive.js"></script> <script type="application/javascript" src="../scripts/controller/role/NamespaceRoleController.js"></script> </body> </html>
<!-- ~ Copyright 2021 Apollo Authors ~ ~ Licensed 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. ~ --> <!doctype html> <html ng-app="role"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="icon" href="../img/config.png"> <!-- styles --> <link rel="stylesheet" type="text/css" href="../vendor/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="../vendor/angular/angular-toastr-1.4.1.min.css"> <link rel="stylesheet" type="text/css" media='all' href="../vendor/angular/loading-bar.min.css"> <link rel="stylesheet" type="text/css" href="../styles/common-style.css"> <link rel="stylesheet" type="text/css" href="../vendor/select2/select2.min.css"> <title>{{'Namespace.Role.Title' | translate }}</title> </head> <body> <apollonav></apollonav> <div class="container-fluid apollo-container"> <section class="panel col-md-offset-1 col-md-10" ng-controller="NamespaceRoleController"> <header class="panel-heading"> <div class="row"> <div class="col-md-9"> <h4 class="modal-title"> {{'Namespace.Role.Title' | translate }}<small>({{'Common.AppId' | translate }}:<label ng-bind="pageContext.appId"></label> {{'Common.Namespace' | translate }}:<label ng-bind="pageContext.namespaceName"></label>)</small> </h4> </div> <div class="col-md-3 text-right"> <a type="button" class="btn btn-info" data-dismiss="modal" href="{{ '/config.html' | prefixPath }}?#appid={{pageContext.appId}}">{{'Common.ReturnToIndex' | translate }} </a> </div> </div> </header> <div class="panel-body" ng-show="hasAssignUserPermission"> <div class="row"> <div class="form-horizontal"> <div class="form-group"> <label class="col-sm-2 control-label">{{'Namespace.Role.GrantModifyTo' | translate }}<br><small>{{'Namespace.Role.GrantModifyTo2' | translate }}</small></label> <div class="col-sm-8"> <form class="form-inline" ng-submit="assignRoleToUser('ModifyNamespace')"> <div class="form-group"> <apollouserselector apollo-id="modifyRoleWidgetId"></apollouserselector> <select class="form-control input-sm" ng-model="modifyRoleSelectedEnv"> <option value="">{{'Namespace.Role.AllEnv' | translate }}</option> <option ng-repeat="env in envs" ng-value="env">{{env}}</option> </select> </div> <button type="submit" class="btn btn-default" style="margin-left: 20px;" ng-disabled="modifyRoleSubmitBtnDisabled">{{'Namespace.Role.Add' | translate }}</button> </form> <!-- Split button --> <div class="item-container"> <h5>{{'Namespace.Role.AllEnv' | translate }}</h5> <div class="btn-group item-info" ng-repeat="user in rolesAssignedUsers.modifyRoleUsers"> <button type="button" class="btn btn-default" ng-bind="user.userId"></button> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" ng-click="removeUserRole('ModifyNamespace', user.userId, null)"> <span class="glyphicon glyphicon-remove"></span> </button> </div> </div> <div class="item-container" ng-repeat="env in envs"> <h5>{{env}}</h5> <div class="btn-group item-info" ng-repeat="user in envRolesAssignedUsers[env].modifyRoleUsers"> <button type="button" class="btn btn-default" ng-bind="user.userId"></button> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" ng-click="removeUserRole('ModifyNamespace', user.userId, env)"> <span class="glyphicon glyphicon-remove"></span> </button> </div> </div> </div> </div> </div> <hr> <div class="row" style="margin-top: 10px;"> <div class="form-horizontal"> <div class="col-sm-2 text-right"> <label class="control-label">{{'Namespace.Role.GrantPublishTo' | translate }}<br><small>{{'Namespace.Role.GrantPublishTo2' | translate }}</small></label> </div> <div class="col-sm-8"> <form class="form-inline" ng-submit="assignRoleToUser('ReleaseNamespace')"> <div class="form-group"> <apollouserselector apollo-id="releaseRoleWidgetId"></apollouserselector> <select class="form-control input-sm" ng-model="releaseRoleSelectedEnv"> <option value="">{{'Namespace.Role.AllEnv' | translate }}</option> <option ng-repeat="env in envs" ng-value="env">{{env}}</option> </select> </div> <button type="submit" class="btn btn-default" style="margin-left: 20px;" ng-disabled="ReleaseRoleSubmitBtnDisabled">{{'Namespace.Role.Add' | translate }}</button> </form> <!-- Split button --> <div class="item-container"> <h5>{{'Namespace.Role.AllEnv' | translate }}</h5> <div class="btn-group item-info" ng-repeat="user in rolesAssignedUsers.releaseRoleUsers"> <button type="button" class="btn btn-default" ng-bind="user.userId"></button> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" ng-click="removeUserRole('ReleaseNamespace', user.userId, null)"> <span class="glyphicon glyphicon-remove"></span> </button> </div> </div> <div class="item-container" ng-repeat="env in envs"> <h5>{{env}}</h5> <div class="btn-group item-info" ng-repeat="user in envRolesAssignedUsers[env].releaseRoleUsers"> <button type="button" class="btn btn-default" ng-bind="user.userId"></button> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" ng-click="removeUserRole('ReleaseNamespace', user.userId, env)"> <span class="glyphicon glyphicon-remove"></span> </button> </div> </div> </div> </div> </div> </div> </div> <div class="panel-body text-center" ng-show="!hasAssignUserPermission"> <h2>{{'Namespace.Role.NoPermission' | translate }}</h2> </div> </section> </div> <div ng-include="'../views/common/footer.html'"></div> <!-- jquery.js --> <script src="../vendor/jquery.min.js" type="text/javascript"></script> <!--angular--> <script src="../vendor/angular/angular.min.js"></script> <script src="../vendor/angular/angular-resource.min.js"></script> <script src="../vendor/angular/angular-toastr-1.4.1.tpls.min.js"></script> <script src="../vendor/angular/loading-bar.min.js"></script> <script src="../vendor/angular/angular-cookies.min.js"></script> <script src="../vendor/angular/angular-translate.2.18.1/angular-translate.min.js"></script> <script src="../vendor/angular/angular-translate.2.18.1/angular-translate-loader-static-files.min.js"></script> <script src="../vendor/angular/angular-translate.2.18.1/angular-translate-storage-cookie.min.js"></script> <!-- bootstrap.js --> <script src="../vendor/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="../vendor/select2/select2.min.js" type="text/javascript"></script> <!--biz--> <!--must import--> <script type="application/javascript" src="../scripts/app.js"></script> <script type="application/javascript" src="../scripts/services/AppService.js"></script> <script type="application/javascript" src="../scripts/services/EnvService.js"></script> <script type="application/javascript" src="../scripts/services/UserService.js"></script> <script type="application/javascript" src="../scripts/services/CommonService.js"></script> <script type="application/javascript" src="../scripts/services/PermissionService.js"></script> <script type="application/javascript" src="../scripts/AppUtils.js"></script> <script type="application/javascript" src="../scripts/PageCommon.js"></script> <script type="application/javascript" src="../scripts/directive/directive.js"></script> <script type="application/javascript" src="../scripts/controller/role/NamespaceRoleController.js"></script> </body> </html>
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/vo/ItemDiffs.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.entity.vo; import com.ctrip.framework.apollo.common.dto.ItemChangeSets; public class ItemDiffs { private NamespaceIdentifier namespace; private ItemChangeSets diffs; private String extInfo; public ItemDiffs(NamespaceIdentifier namespace) { this.namespace = namespace; } public NamespaceIdentifier getNamespace() { return namespace; } public void setNamespace(NamespaceIdentifier namespace) { this.namespace = namespace; } public ItemChangeSets getDiffs() { return diffs; } public void setDiffs(ItemChangeSets diffs) { this.diffs = diffs; } public String getExtInfo() { return extInfo; } public void setExtInfo(String extInfo) { this.extInfo = extInfo; } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.entity.vo; import com.ctrip.framework.apollo.common.dto.ItemChangeSets; public class ItemDiffs { private NamespaceIdentifier namespace; private ItemChangeSets diffs; private String extInfo; public ItemDiffs(NamespaceIdentifier namespace) { this.namespace = namespace; } public NamespaceIdentifier getNamespace() { return namespace; } public void setNamespace(NamespaceIdentifier namespace) { this.namespace = namespace; } public ItemChangeSets getDiffs() { return diffs; } public void setDiffs(ItemChangeSets diffs) { this.diffs = diffs; } public String getExtInfo() { return extInfo; } public void setExtInfo(String extInfo) { this.extInfo = extInfo; } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/ReleaseHistoryController.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.controller; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.portal.component.PermissionValidator; import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO; import com.ctrip.framework.apollo.portal.service.ReleaseHistoryService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Collections; import java.util.List; @RestController public class ReleaseHistoryController { private final ReleaseHistoryService releaseHistoryService; private final PermissionValidator permissionValidator; public ReleaseHistoryController(final ReleaseHistoryService releaseHistoryService, final PermissionValidator permissionValidator) { this.releaseHistoryService = releaseHistoryService; this.permissionValidator = permissionValidator; } @GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/releases/histories") public List<ReleaseHistoryBO> findReleaseHistoriesByNamespace(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "size", defaultValue = "10") int size) { if (permissionValidator.shouldHideConfigToCurrentUser(appId, env, namespaceName)) { return Collections.emptyList(); } return releaseHistoryService.findNamespaceReleaseHistory(appId, Env.valueOf(env), clusterName ,namespaceName, page, size); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.portal.controller; import com.ctrip.framework.apollo.portal.environment.Env; import com.ctrip.framework.apollo.portal.component.PermissionValidator; import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO; import com.ctrip.framework.apollo.portal.service.ReleaseHistoryService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.Collections; import java.util.List; @RestController public class ReleaseHistoryController { private final ReleaseHistoryService releaseHistoryService; private final PermissionValidator permissionValidator; public ReleaseHistoryController(final ReleaseHistoryService releaseHistoryService, final PermissionValidator permissionValidator) { this.releaseHistoryService = releaseHistoryService; this.permissionValidator = permissionValidator; } @GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/releases/histories") public List<ReleaseHistoryBO> findReleaseHistoriesByNamespace(@PathVariable String appId, @PathVariable String env, @PathVariable String clusterName, @PathVariable String namespaceName, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "size", defaultValue = "10") int size) { if (permissionValidator.shouldHideConfigToCurrentUser(appId, env, namespaceName)) { return Collections.emptyList(); } return releaseHistoryService.findNamespaceReleaseHistory(appId, Env.valueOf(env), clusterName ,namespaceName, page, size); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./apollo-adminservice/src/main/java/com/ctrip/framework/apollo/adminservice/controller/ItemController.java
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.adminservice.controller; import com.ctrip.framework.apollo.adminservice.aop.PreAcquireNamespaceLock; import com.ctrip.framework.apollo.biz.entity.Commit; import com.ctrip.framework.apollo.biz.entity.Item; import com.ctrip.framework.apollo.biz.entity.Namespace; import com.ctrip.framework.apollo.biz.entity.Release; import com.ctrip.framework.apollo.biz.service.CommitService; import com.ctrip.framework.apollo.biz.service.ItemService; import com.ctrip.framework.apollo.biz.service.NamespaceService; import com.ctrip.framework.apollo.biz.service.ReleaseService; import com.ctrip.framework.apollo.biz.utils.ConfigChangeContentBuilder; import com.ctrip.framework.apollo.common.dto.ItemDTO; import com.ctrip.framework.apollo.common.exception.BadRequestException; import com.ctrip.framework.apollo.common.exception.NotFoundException; import com.ctrip.framework.apollo.common.utils.BeanUtils; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class ItemController { private final ItemService itemService; private final NamespaceService namespaceService; private final CommitService commitService; private final ReleaseService releaseService; public ItemController(final ItemService itemService, final NamespaceService namespaceService, final CommitService commitService, final ReleaseService releaseService) { this.itemService = itemService; this.namespaceService = namespaceService; this.commitService = commitService; this.releaseService = releaseService; } @PreAcquireNamespaceLock @PostMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items") public ItemDTO create(@PathVariable("appId") String appId, @PathVariable("clusterName") String clusterName, @PathVariable("namespaceName") String namespaceName, @RequestBody ItemDTO dto) { Item entity = BeanUtils.transform(Item.class, dto); ConfigChangeContentBuilder builder = new ConfigChangeContentBuilder(); Item managedEntity = itemService.findOne(appId, clusterName, namespaceName, entity.getKey()); if (managedEntity != null) { throw new BadRequestException("item already exists"); } entity = itemService.save(entity); builder.createItem(entity); dto = BeanUtils.transform(ItemDTO.class, entity); Commit commit = new Commit(); commit.setAppId(appId); commit.setClusterName(clusterName); commit.setNamespaceName(namespaceName); commit.setChangeSets(builder.build()); commit.setDataChangeCreatedBy(dto.getDataChangeLastModifiedBy()); commit.setDataChangeLastModifiedBy(dto.getDataChangeLastModifiedBy()); commitService.save(commit); return dto; } @PreAcquireNamespaceLock @PutMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{itemId}") public ItemDTO update(@PathVariable("appId") String appId, @PathVariable("clusterName") String clusterName, @PathVariable("namespaceName") String namespaceName, @PathVariable("itemId") long itemId, @RequestBody ItemDTO itemDTO) { Item managedEntity = itemService.findOne(itemId); if (managedEntity == null) { throw new NotFoundException("item not found for itemId " + itemId); } Namespace namespace = namespaceService.findOne(appId, clusterName, namespaceName); // In case someone constructs an attack scenario if (namespace == null || namespace.getId() != managedEntity.getNamespaceId()) { throw new BadRequestException("Invalid request, item and namespace do not match!"); } Item entity = BeanUtils.transform(Item.class, itemDTO); ConfigChangeContentBuilder builder = new ConfigChangeContentBuilder(); Item beforeUpdateItem = BeanUtils.transform(Item.class, managedEntity); //protect. only value,comment,lastModifiedBy can be modified managedEntity.setValue(entity.getValue()); managedEntity.setComment(entity.getComment()); managedEntity.setDataChangeLastModifiedBy(entity.getDataChangeLastModifiedBy()); entity = itemService.update(managedEntity); builder.updateItem(beforeUpdateItem, entity); itemDTO = BeanUtils.transform(ItemDTO.class, entity); if (builder.hasContent()) { Commit commit = new Commit(); commit.setAppId(appId); commit.setClusterName(clusterName); commit.setNamespaceName(namespaceName); commit.setChangeSets(builder.build()); commit.setDataChangeCreatedBy(itemDTO.getDataChangeLastModifiedBy()); commit.setDataChangeLastModifiedBy(itemDTO.getDataChangeLastModifiedBy()); commitService.save(commit); } return itemDTO; } @PreAcquireNamespaceLock @DeleteMapping("/items/{itemId}") public void delete(@PathVariable("itemId") long itemId, @RequestParam String operator) { Item entity = itemService.findOne(itemId); if (entity == null) { throw new NotFoundException("item not found for itemId " + itemId); } itemService.delete(entity.getId(), operator); Namespace namespace = namespaceService.findOne(entity.getNamespaceId()); Commit commit = new Commit(); commit.setAppId(namespace.getAppId()); commit.setClusterName(namespace.getClusterName()); commit.setNamespaceName(namespace.getNamespaceName()); commit.setChangeSets(new ConfigChangeContentBuilder().deleteItem(entity).build()); commit.setDataChangeCreatedBy(operator); commit.setDataChangeLastModifiedBy(operator); commitService.save(commit); } @GetMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items") public List<ItemDTO> findItems(@PathVariable("appId") String appId, @PathVariable("clusterName") String clusterName, @PathVariable("namespaceName") String namespaceName) { return BeanUtils.batchTransform(ItemDTO.class, itemService.findItemsWithOrdered(appId, clusterName, namespaceName)); } @GetMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/deleted") public List<ItemDTO> findDeletedItems(@PathVariable("appId") String appId, @PathVariable("clusterName") String clusterName, @PathVariable("namespaceName") String namespaceName) { //get latest release time Release latestActiveRelease = releaseService.findLatestActiveRelease(appId, clusterName, namespaceName); List<Commit> commits; if (Objects.nonNull(latestActiveRelease)) { commits = commitService.find(appId, clusterName, namespaceName, latestActiveRelease.getDataChangeCreatedTime(), null); } else { commits = commitService.find(appId, clusterName, namespaceName, null); } if (Objects.nonNull(commits)) { List<Item> deletedItems = commits.stream() .map(item -> ConfigChangeContentBuilder.convertJsonString(item.getChangeSets()).getDeleteItems()) .flatMap(Collection::stream) .collect(Collectors.toList()); return BeanUtils.batchTransform(ItemDTO.class, deletedItems); } return Collections.emptyList(); } @GetMapping("/items/{itemId}") public ItemDTO get(@PathVariable("itemId") long itemId) { Item item = itemService.findOne(itemId); if (item == null) { throw new NotFoundException("item not found for itemId " + itemId); } return BeanUtils.transform(ItemDTO.class, item); } @GetMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key:.+}") public ItemDTO get(@PathVariable("appId") String appId, @PathVariable("clusterName") String clusterName, @PathVariable("namespaceName") String namespaceName, @PathVariable("key") String key) { Item item = itemService.findOne(appId, clusterName, namespaceName, key); if (item == null) { throw new NotFoundException( String.format("item not found for %s %s %s %s", appId, clusterName, namespaceName, key)); } return BeanUtils.transform(ItemDTO.class, item); } }
/* * Copyright 2021 Apollo Authors * * Licensed 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 com.ctrip.framework.apollo.adminservice.controller; import com.ctrip.framework.apollo.adminservice.aop.PreAcquireNamespaceLock; import com.ctrip.framework.apollo.biz.entity.Commit; import com.ctrip.framework.apollo.biz.entity.Item; import com.ctrip.framework.apollo.biz.entity.Namespace; import com.ctrip.framework.apollo.biz.entity.Release; import com.ctrip.framework.apollo.biz.service.CommitService; import com.ctrip.framework.apollo.biz.service.ItemService; import com.ctrip.framework.apollo.biz.service.NamespaceService; import com.ctrip.framework.apollo.biz.service.ReleaseService; import com.ctrip.framework.apollo.biz.utils.ConfigChangeContentBuilder; import com.ctrip.framework.apollo.common.dto.ItemDTO; import com.ctrip.framework.apollo.common.exception.BadRequestException; import com.ctrip.framework.apollo.common.exception.NotFoundException; import com.ctrip.framework.apollo.common.utils.BeanUtils; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class ItemController { private final ItemService itemService; private final NamespaceService namespaceService; private final CommitService commitService; private final ReleaseService releaseService; public ItemController(final ItemService itemService, final NamespaceService namespaceService, final CommitService commitService, final ReleaseService releaseService) { this.itemService = itemService; this.namespaceService = namespaceService; this.commitService = commitService; this.releaseService = releaseService; } @PreAcquireNamespaceLock @PostMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items") public ItemDTO create(@PathVariable("appId") String appId, @PathVariable("clusterName") String clusterName, @PathVariable("namespaceName") String namespaceName, @RequestBody ItemDTO dto) { Item entity = BeanUtils.transform(Item.class, dto); ConfigChangeContentBuilder builder = new ConfigChangeContentBuilder(); Item managedEntity = itemService.findOne(appId, clusterName, namespaceName, entity.getKey()); if (managedEntity != null) { throw new BadRequestException("item already exists"); } entity = itemService.save(entity); builder.createItem(entity); dto = BeanUtils.transform(ItemDTO.class, entity); Commit commit = new Commit(); commit.setAppId(appId); commit.setClusterName(clusterName); commit.setNamespaceName(namespaceName); commit.setChangeSets(builder.build()); commit.setDataChangeCreatedBy(dto.getDataChangeLastModifiedBy()); commit.setDataChangeLastModifiedBy(dto.getDataChangeLastModifiedBy()); commitService.save(commit); return dto; } @PreAcquireNamespaceLock @PutMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{itemId}") public ItemDTO update(@PathVariable("appId") String appId, @PathVariable("clusterName") String clusterName, @PathVariable("namespaceName") String namespaceName, @PathVariable("itemId") long itemId, @RequestBody ItemDTO itemDTO) { Item managedEntity = itemService.findOne(itemId); if (managedEntity == null) { throw new NotFoundException("item not found for itemId " + itemId); } Namespace namespace = namespaceService.findOne(appId, clusterName, namespaceName); // In case someone constructs an attack scenario if (namespace == null || namespace.getId() != managedEntity.getNamespaceId()) { throw new BadRequestException("Invalid request, item and namespace do not match!"); } Item entity = BeanUtils.transform(Item.class, itemDTO); ConfigChangeContentBuilder builder = new ConfigChangeContentBuilder(); Item beforeUpdateItem = BeanUtils.transform(Item.class, managedEntity); //protect. only value,comment,lastModifiedBy can be modified managedEntity.setValue(entity.getValue()); managedEntity.setComment(entity.getComment()); managedEntity.setDataChangeLastModifiedBy(entity.getDataChangeLastModifiedBy()); entity = itemService.update(managedEntity); builder.updateItem(beforeUpdateItem, entity); itemDTO = BeanUtils.transform(ItemDTO.class, entity); if (builder.hasContent()) { Commit commit = new Commit(); commit.setAppId(appId); commit.setClusterName(clusterName); commit.setNamespaceName(namespaceName); commit.setChangeSets(builder.build()); commit.setDataChangeCreatedBy(itemDTO.getDataChangeLastModifiedBy()); commit.setDataChangeLastModifiedBy(itemDTO.getDataChangeLastModifiedBy()); commitService.save(commit); } return itemDTO; } @PreAcquireNamespaceLock @DeleteMapping("/items/{itemId}") public void delete(@PathVariable("itemId") long itemId, @RequestParam String operator) { Item entity = itemService.findOne(itemId); if (entity == null) { throw new NotFoundException("item not found for itemId " + itemId); } itemService.delete(entity.getId(), operator); Namespace namespace = namespaceService.findOne(entity.getNamespaceId()); Commit commit = new Commit(); commit.setAppId(namespace.getAppId()); commit.setClusterName(namespace.getClusterName()); commit.setNamespaceName(namespace.getNamespaceName()); commit.setChangeSets(new ConfigChangeContentBuilder().deleteItem(entity).build()); commit.setDataChangeCreatedBy(operator); commit.setDataChangeLastModifiedBy(operator); commitService.save(commit); } @GetMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items") public List<ItemDTO> findItems(@PathVariable("appId") String appId, @PathVariable("clusterName") String clusterName, @PathVariable("namespaceName") String namespaceName) { return BeanUtils.batchTransform(ItemDTO.class, itemService.findItemsWithOrdered(appId, clusterName, namespaceName)); } @GetMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/deleted") public List<ItemDTO> findDeletedItems(@PathVariable("appId") String appId, @PathVariable("clusterName") String clusterName, @PathVariable("namespaceName") String namespaceName) { //get latest release time Release latestActiveRelease = releaseService.findLatestActiveRelease(appId, clusterName, namespaceName); List<Commit> commits; if (Objects.nonNull(latestActiveRelease)) { commits = commitService.find(appId, clusterName, namespaceName, latestActiveRelease.getDataChangeCreatedTime(), null); } else { commits = commitService.find(appId, clusterName, namespaceName, null); } if (Objects.nonNull(commits)) { List<Item> deletedItems = commits.stream() .map(item -> ConfigChangeContentBuilder.convertJsonString(item.getChangeSets()).getDeleteItems()) .flatMap(Collection::stream) .collect(Collectors.toList()); return BeanUtils.batchTransform(ItemDTO.class, deletedItems); } return Collections.emptyList(); } @GetMapping("/items/{itemId}") public ItemDTO get(@PathVariable("itemId") long itemId) { Item item = itemService.findOne(itemId); if (item == null) { throw new NotFoundException("item not found for itemId " + itemId); } return BeanUtils.transform(ItemDTO.class, item); } @GetMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key:.+}") public ItemDTO get(@PathVariable("appId") String appId, @PathVariable("clusterName") String clusterName, @PathVariable("namespaceName") String namespaceName, @PathVariable("key") String key) { Item item = itemService.findOne(appId, clusterName, namespaceName, key); if (item == null) { throw new NotFoundException( String.format("item not found for %s %s %s %s", appId, clusterName, namespaceName, key)); } return BeanUtils.transform(ItemDTO.class, item); } }
-1
apolloconfig/apollo
3,804
feature: add the delegating password encoder for apollo-portal simple auth
## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
vdiskg
2021-07-02T11:16:09Z
2021-07-10T08:12:21Z
907dbad14e2d76bf1ffa3645d115534632e28cc2
72a04989d049e182dd409e2a76e5c0e4448a8a2d
feature: add the delegating password encoder for apollo-portal simple auth. ## What's the purpose of this PR the best algorithm for password storage should change some day in the future. the `DelegatingPasswordEncoder` can makes the algorithm upgrade seamless. ## Brief changelog 1. extend the `ApolloPortalDB`.`Users`.`Password` to 512 2. replace the `BCryptPasswordEncoder` with the `DelegatingPasswordEncoder` backend of the `BCryptPasswordEncoder` 3. add a `PlaceholderPasswordEncoder` which return a random string as encoded password and never matches any encoded password. 4. replace the random string password for oidc with the `DelegatingPasswordEncoder` backend of the `PlaceholderPasswordEncoder` Follow this checklist to help us incorporate your contribution quickly and easily: - [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request. - [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why. - [x] Write necessary unit tests to verify the code. - [x] Run `mvn clean test` to make sure this pull request doesn't break anything. - [x] Update the [`CHANGES` log](https://github.com/ctripcorp/apollo/blob/master/CHANGES.md).
./scripts/apollo-on-kubernetes/apollo-config-server/config/app.properties
# # Copyright 2021 Apollo Authors # # Licensed 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. # appId=100003171 jdkVersion=1.8
# # Copyright 2021 Apollo Authors # # Licensed 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. # appId=100003171 jdkVersion=1.8
-1