repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/TargetObjectWithUUID.java
/* * Copyright 2002-2017 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls; import java.util.UUID; /** * Dummy domain object class with a {@link UUID} for the Id. * * @author Luke Taylor */ public final class TargetObjectWithUUID { private UUID id; public UUID getId() { return this.id; } public void setId(UUID id) { this.id = id; } }
945
23.25641
75
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/TargetObject.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls; /** * Dummy domain object class * * @author Luke Taylor */ public final class TargetObject { }
767
27.444444
75
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/AclPermissionEvaluatorTests.java
/* * Copyright 2002-2018 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls; import java.util.Locale; import org.junit.jupiter.api.Test; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy; import org.springframework.security.acls.model.SidRetrievalStrategy; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author Luke Taylor * @since 3.0 */ public class AclPermissionEvaluatorTests { @Test public void hasPermissionReturnsTrueIfAclGrantsPermission() { AclService service = mock(AclService.class); AclPermissionEvaluator pe = new AclPermissionEvaluator(service); ObjectIdentity oid = mock(ObjectIdentity.class); ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class); given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid); pe.setObjectIdentityRetrievalStrategy(oidStrategy); pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class)); Acl acl = mock(Acl.class); given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl); given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true); assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "READ")).isTrue(); } @Test public void resolvePermissionNonEnglishLocale() { Locale systemLocale = Locale.getDefault(); Locale.setDefault(new Locale("tr")); AclService service = mock(AclService.class); AclPermissionEvaluator pe = new AclPermissionEvaluator(service); ObjectIdentity oid = mock(ObjectIdentity.class); ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class); given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid); pe.setObjectIdentityRetrievalStrategy(oidStrategy); pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class)); Acl acl = mock(Acl.class); given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl); given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true); assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "write")).isTrue(); Locale.setDefault(systemLocale); } }
3,205
40.636364
92
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/AclPermissionCacheOptimizerTests.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy; import org.springframework.security.acls.model.SidRetrievalStrategy; import org.springframework.security.core.Authentication; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * @author Luke Taylor */ @SuppressWarnings({ "unchecked" }) public class AclPermissionCacheOptimizerTests { @Test public void eagerlyLoadsRequiredAcls() { AclService service = mock(AclService.class); AclPermissionCacheOptimizer pco = new AclPermissionCacheOptimizer(service); ObjectIdentityRetrievalStrategy oidStrat = mock(ObjectIdentityRetrievalStrategy.class); SidRetrievalStrategy sidStrat = mock(SidRetrievalStrategy.class); pco.setObjectIdentityRetrievalStrategy(oidStrat); pco.setSidRetrievalStrategy(sidStrat); Object[] dos = { new Object(), null, new Object() }; ObjectIdentity[] oids = { new ObjectIdentityImpl("A", "1"), new ObjectIdentityImpl("A", "2") }; given(oidStrat.getObjectIdentity(dos[0])).willReturn(oids[0]); given(oidStrat.getObjectIdentity(dos[2])).willReturn(oids[1]); pco.cachePermissionsFor(mock(Authentication.class), Arrays.asList(dos)); // AclService should be invoked with the list of required Oids verify(service).readAclsById(eq(Arrays.asList(oids)), any(List.class)); } @Test public void ignoresEmptyCollection() { AclService service = mock(AclService.class); AclPermissionCacheOptimizer pco = new AclPermissionCacheOptimizer(service); ObjectIdentityRetrievalStrategy oids = mock(ObjectIdentityRetrievalStrategy.class); SidRetrievalStrategy sids = mock(SidRetrievalStrategy.class); pco.setObjectIdentityRetrievalStrategy(oids); pco.setSidRetrievalStrategy(sids); pco.cachePermissionsFor(mock(Authentication.class), Collections.emptyList()); verifyNoMoreInteractions(service, sids, oids); } }
3,044
39.6
97
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/AclFormattingUtilsTests.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls; import org.junit.jupiter.api.Test; import org.springframework.security.acls.domain.AclFormattingUtils; import org.springframework.security.acls.model.Permission; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatNoException; /** * Tests for {@link AclFormattingUtils}. * * @author Andrei Stefan */ public class AclFormattingUtilsTests { @Test public final void testDemergePatternsParametersConstraints() { assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.demergePatterns(null, "SOME STRING")); assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", null)); assertThatIllegalArgumentException() .isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING")); assertThatNoException().isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH")); } @Test public final void testDemergePatterns() { String original = "...........................A...R"; String removeBits = "...............................R"; assertThat(AclFormattingUtils.demergePatterns(original, removeBits)) .isEqualTo("...........................A...."); assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "......")).isEqualTo("ABCDEF"); assertThat(AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL")).isEqualTo("......"); } @Test public final void testMergePatternsParametersConstraints() { assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.mergePatterns(null, "SOME STRING")); assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", null)); assertThatIllegalArgumentException() .isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING")); assertThatNoException().isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH")); } @Test public final void testMergePatterns() { String original = "...............................R"; String extraBits = "...........................A...."; assertThat(AclFormattingUtils.mergePatterns(original, extraBits)).isEqualTo("...........................A...R"); assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "......")).isEqualTo("ABCDEF"); assertThat(AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL")).isEqualTo("GHIJKL"); } @Test public final void testBinaryPrints() { assertThat(AclFormattingUtils.printBinary(15)).isEqualTo("............................****"); assertThatIllegalArgumentException() .isThrownBy(() -> AclFormattingUtils.printBinary(15, Permission.RESERVED_ON)); assertThatIllegalArgumentException() .isThrownBy(() -> AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF)); assertThat(AclFormattingUtils.printBinary(15, 'x')).isEqualTo("............................xxxx"); } @Test public void testPrintBinaryNegative() { assertThat(AclFormattingUtils.printBinary(0x80000000)).isEqualTo("*..............................."); } @Test public void testPrintBinaryMinusOne() { assertThat(AclFormattingUtils.printBinary(0xffffffff)).isEqualTo("********************************"); } }
3,978
41.784946
114
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/sid/SidTests.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.sid; import java.util.Collection; import java.util.Collections; import org.junit.jupiter.api.Test; import org.springframework.security.acls.domain.GrantedAuthoritySid; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.Sid; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatNoException; public class SidTests { @Test public void testPrincipalSidConstructorsRequiredFields() { // Check one String-argument constructor assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid((String) null)); assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid("")); assertThatNoException().isThrownBy(() -> new PrincipalSid("johndoe")); // Check one Authentication-argument constructor assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid((Authentication) null)); assertThatIllegalArgumentException() .isThrownBy(() -> new PrincipalSid(new TestingAuthenticationToken(null, "password"))); assertThatNoException() .isThrownBy(() -> new PrincipalSid(new TestingAuthenticationToken("johndoe", "password"))); } @Test public void testGrantedAuthoritySidConstructorsRequiredFields() { // Check one String-argument constructor assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid((String) null)); assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid("")); assertThatNoException().isThrownBy(() -> new GrantedAuthoritySid("ROLE_TEST")); // Check one GrantedAuthority-argument constructor assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid((GrantedAuthority) null)); assertThatIllegalArgumentException() .isThrownBy(() -> new GrantedAuthoritySid(new SimpleGrantedAuthority(null))); assertThatNoException().isThrownBy(() -> new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_TEST"))); } @Test public void testPrincipalSidEquals() { Authentication authentication = new TestingAuthenticationToken("johndoe", "password"); Sid principalSid = new PrincipalSid(authentication); assertThat(principalSid.equals(null)).isFalse(); assertThat(principalSid.equals("DIFFERENT_TYPE_OBJECT")).isFalse(); assertThat(principalSid.equals(principalSid)).isTrue(); assertThat(principalSid.equals(new PrincipalSid(authentication))).isTrue(); assertThat(principalSid.equals(new PrincipalSid(new TestingAuthenticationToken("johndoe", null)))).isTrue(); assertThat(principalSid.equals(new PrincipalSid(new TestingAuthenticationToken("scott", null)))).isFalse(); assertThat(principalSid.equals(new PrincipalSid("johndoe"))).isTrue(); assertThat(principalSid.equals(new PrincipalSid("scott"))).isFalse(); } @Test public void testGrantedAuthoritySidEquals() { GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST"); Sid gaSid = new GrantedAuthoritySid(ga); assertThat(gaSid.equals(null)).isFalse(); assertThat(gaSid.equals("DIFFERENT_TYPE_OBJECT")).isFalse(); assertThat(gaSid.equals(gaSid)).isTrue(); assertThat(gaSid.equals(new GrantedAuthoritySid(ga))).isTrue(); assertThat(gaSid.equals(new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_TEST")))).isTrue(); assertThat(gaSid.equals(new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_NOT_EQUAL")))).isFalse(); assertThat(gaSid.equals(new GrantedAuthoritySid("ROLE_TEST"))).isTrue(); assertThat(gaSid.equals(new GrantedAuthoritySid("ROLE_NOT_EQUAL"))).isFalse(); } @Test public void testPrincipalSidHashCode() { Authentication authentication = new TestingAuthenticationToken("johndoe", "password"); Sid principalSid = new PrincipalSid(authentication); assertThat(principalSid.hashCode()).isEqualTo("johndoe".hashCode()); assertThat(principalSid.hashCode()).isEqualTo(new PrincipalSid("johndoe").hashCode()); assertThat(principalSid.hashCode()).isNotEqualTo(new PrincipalSid("scott").hashCode()); assertThat(principalSid.hashCode()) .isNotEqualTo(new PrincipalSid(new TestingAuthenticationToken("scott", "password")).hashCode()); } @Test public void testGrantedAuthoritySidHashCode() { GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST"); Sid gaSid = new GrantedAuthoritySid(ga); assertThat(gaSid.hashCode()).isEqualTo("ROLE_TEST".hashCode()); assertThat(gaSid.hashCode()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST").hashCode()); assertThat(gaSid.hashCode()).isNotEqualTo(new GrantedAuthoritySid("ROLE_TEST_2").hashCode()); assertThat(gaSid.hashCode()) .isNotEqualTo(new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_TEST_2")).hashCode()); } @Test public void testGetters() { Authentication authentication = new TestingAuthenticationToken("johndoe", "password"); PrincipalSid principalSid = new PrincipalSid(authentication); GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST"); GrantedAuthoritySid gaSid = new GrantedAuthoritySid(ga); assertThat("johndoe".equals(principalSid.getPrincipal())).isTrue(); assertThat("scott".equals(principalSid.getPrincipal())).isFalse(); assertThat("ROLE_TEST".equals(gaSid.getGrantedAuthority())).isTrue(); assertThat("ROLE_TEST2".equals(gaSid.getGrantedAuthority())).isFalse(); } @Test public void getPrincipalWhenPrincipalInstanceOfUserDetailsThenReturnsUsername() { User user = new User("user", "password", Collections.singletonList(new SimpleGrantedAuthority("ROLE_TEST"))); Authentication authentication = new TestingAuthenticationToken(user, "password"); PrincipalSid principalSid = new PrincipalSid(authentication); assertThat("user").isEqualTo(principalSid.getPrincipal()); } @Test public void getPrincipalWhenPrincipalNotInstanceOfUserDetailsThenReturnsPrincipalName() { Authentication authentication = new TestingAuthenticationToken("token", "password"); PrincipalSid principalSid = new PrincipalSid(authentication); assertThat("token").isEqualTo(principalSid.getPrincipal()); } @Test public void getPrincipalWhenCustomAuthenticationPrincipalThenReturnsPrincipalName() { Authentication authentication = new CustomAuthenticationToken(new CustomToken("token"), null); PrincipalSid principalSid = new PrincipalSid(authentication); assertThat("token").isEqualTo(principalSid.getPrincipal()); } static class CustomAuthenticationToken extends AbstractAuthenticationToken { private CustomToken principal; CustomAuthenticationToken(CustomToken principal, Collection<GrantedAuthority> authorities) { super(authorities); this.principal = principal; } @Override public Object getCredentials() { return null; } @Override public CustomToken getPrincipal() { return this.principal; } @Override public String getName() { return this.principal.getName(); } } static class CustomToken { private String name; CustomToken(String name) { this.name = name; } String getName() { return this.name; } } }
8,149
41.447917
111
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/sid/CustomSid.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.sid; import org.springframework.security.acls.model.Sid; /** * This class is example of custom {@link Sid} implementation * * @author Mikhail Stryzhonok */ public class CustomSid implements Sid { private String sid; public CustomSid(String sid) { this.sid = sid; } public String getSid() { return this.sid; } public void setSid(String sid) { this.sid = sid; } }
1,051
23.465116
75
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/sid/SidRetrievalStrategyTests.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.sid; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.security.access.hierarchicalroles.RoleHierarchy; import org.springframework.security.acls.domain.GrantedAuthoritySid; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.domain.SidRetrievalStrategyImpl; import org.springframework.security.acls.model.Sid; import org.springframework.security.acls.model.SidRetrievalStrategy; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests for {@link SidRetrievalStrategyImpl} * * @author Andrei Stefan * @author Luke Taylor */ @SuppressWarnings("unchecked") public class SidRetrievalStrategyTests { Authentication authentication = new TestingAuthenticationToken("scott", "password", "A", "B", "C"); @Test public void correctSidsAreRetrieved() { SidRetrievalStrategy retrStrategy = new SidRetrievalStrategyImpl(); List<Sid> sids = retrStrategy.getSids(this.authentication); assertThat(sids).isNotNull(); assertThat(sids).hasSize(4); assertThat(sids.get(0)).isNotNull(); assertThat(sids.get(0) instanceof PrincipalSid).isTrue(); for (int i = 1; i < sids.size(); i++) { assertThat(sids.get(i) instanceof GrantedAuthoritySid).isTrue(); } assertThat(((PrincipalSid) sids.get(0)).getPrincipal()).isEqualTo("scott"); assertThat(((GrantedAuthoritySid) sids.get(1)).getGrantedAuthority()).isEqualTo("A"); assertThat(((GrantedAuthoritySid) sids.get(2)).getGrantedAuthority()).isEqualTo("B"); assertThat(((GrantedAuthoritySid) sids.get(3)).getGrantedAuthority()).isEqualTo("C"); } @Test public void roleHierarchyIsUsedWhenSet() { RoleHierarchy rh = mock(RoleHierarchy.class); List rhAuthorities = AuthorityUtils.createAuthorityList("D"); given(rh.getReachableGrantedAuthorities(anyCollection())).willReturn(rhAuthorities); SidRetrievalStrategy strat = new SidRetrievalStrategyImpl(rh); List<Sid> sids = strat.getSids(this.authentication); assertThat(sids).hasSize(2); assertThat(sids.get(0)).isNotNull(); assertThat(sids.get(0) instanceof PrincipalSid).isTrue(); assertThat(((GrantedAuthoritySid) sids.get(1)).getGrantedAuthority()).isEqualTo("D"); } }
3,214
39.1875
100
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyWithAclClassTypeTests.java
/* * Copyright 2002-2017 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.util.Arrays; import java.util.Map; import javax.sql.DataSource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.convert.ConversionFailedException; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.acls.domain.ConsoleAuditLogger; import org.springframework.security.acls.domain.DefaultPermissionFactory; import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.ObjectIdentity; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests {@link BasicLookupStrategy} with Acl Class type id set to UUID. * * @author Paul Wheeler */ public class BasicLookupStrategyWithAclClassTypeTests extends AbstractBasicLookupStrategyTests { private static final BasicLookupStrategyTestsDbHelper DATABASE_HELPER = new BasicLookupStrategyTestsDbHelper(true); private BasicLookupStrategy uuidEnabledStrategy; @Override public JdbcTemplate getJdbcTemplate() { return DATABASE_HELPER.getJdbcTemplate(); } @Override public DataSource getDataSource() { return DATABASE_HELPER.getDataSource(); } @BeforeAll public static void createDatabase() throws Exception { DATABASE_HELPER.createDatabase(); } @AfterAll public static void dropDatabase() { DATABASE_HELPER.getDataSource().destroy(); } @Override @BeforeEach public void initializeBeans() { super.initializeBeans(); this.uuidEnabledStrategy = new BasicLookupStrategy(getDataSource(), aclCache(), aclAuthStrategy(), new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger())); this.uuidEnabledStrategy.setPermissionFactory(new DefaultPermissionFactory()); this.uuidEnabledStrategy.setAclClassIdSupported(true); this.uuidEnabledStrategy.setConversionService(new DefaultConversionService()); } @BeforeEach public void populateDatabaseForAclClassTypeTests() { String query = "INSERT INTO acl_class(ID,CLASS,CLASS_ID_TYPE) VALUES (3,'" + TARGET_CLASS_WITH_UUID + "', 'java.util.UUID');" + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (4,3,'" + OBJECT_IDENTITY_UUID.toString() + "',null,1,1);" + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (5,3,'" + OBJECT_IDENTITY_LONG_AS_UUID + "',null,1,1);" + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (5,4,0,1,8,0,0,0);" + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (6,5,0,1,8,0,0,0);"; DATABASE_HELPER.getJdbcTemplate().execute(query); } @Test public void testReadObjectIdentityUsingUuidType() { ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_UUID); Map<ObjectIdentity, Acl> foundAcls = this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID)); assertThat(foundAcls).hasSize(1); assertThat(foundAcls.get(oid)).isNotNull(); } @Test public void testReadObjectIdentityUsingLongTypeWithConversionServiceEnabled() { ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 100L); Map<ObjectIdentity, Acl> foundAcls = this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID)); assertThat(foundAcls).hasSize(1); assertThat(foundAcls.get(oid)).isNotNull(); } @Test public void testReadObjectIdentityUsingNonUuidInDatabase() { ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, OBJECT_IDENTITY_LONG_AS_UUID); assertThatExceptionOfType(ConversionFailedException.class) .isThrownBy(() -> this.uuidEnabledStrategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID))); } }
4,873
38.626016
136
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/jdbc/AbstractBasicLookupStrategyTests.java
/* * Copyright 2002-2017 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.UUID; import javax.sql.DataSource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.acls.TargetObject; import org.springframework.security.acls.TargetObjectWithUUID; import org.springframework.security.acls.domain.AclAuthorizationStrategy; import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl; import org.springframework.security.acls.domain.BasePermission; import org.springframework.security.acls.domain.ConsoleAuditLogger; import org.springframework.security.acls.domain.DefaultPermissionFactory; import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy; import org.springframework.security.acls.domain.GrantedAuthoritySid; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.domain.SpringCacheBasedAclCache; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AuditableAccessControlEntry; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.Sid; import org.springframework.security.core.authority.SimpleGrantedAuthority; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests {@link BasicLookupStrategy} * * @author Andrei Stefan */ public abstract class AbstractBasicLookupStrategyTests { protected static final Sid BEN_SID = new PrincipalSid("ben"); protected static final String TARGET_CLASS = TargetObject.class.getName(); protected static final String TARGET_CLASS_WITH_UUID = TargetObjectWithUUID.class.getName(); protected static final UUID OBJECT_IDENTITY_UUID = UUID.randomUUID(); protected static final Long OBJECT_IDENTITY_LONG_AS_UUID = 110L; private BasicLookupStrategy strategy; private static CacheManagerMock cacheManager; public abstract JdbcTemplate getJdbcTemplate(); public abstract DataSource getDataSource(); @BeforeAll public static void initCacheManaer() { cacheManager = new CacheManagerMock(); cacheManager.addCache("basiclookuptestcache"); } @AfterAll public static void shutdownCacheManager() { cacheManager.clear(); } @BeforeEach public void populateDatabase() { String query = "INSERT INTO acl_sid(ID,PRINCIPAL,SID) VALUES (1,1,'ben');" + "INSERT INTO acl_class(ID,CLASS) VALUES (2,'" + TARGET_CLASS + "');" + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (1,2,100,null,1,1);" + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (2,2,101,1,1,1);" + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (3,2,102,2,1,1);" + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (1,1,0,1,1,1,0,0);" + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (2,1,1,1,2,0,0,0);" + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (3,2,0,1,8,1,0,0);" + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (4,3,0,1,8,0,0,0);"; getJdbcTemplate().execute(query); } @BeforeEach public void initializeBeans() { this.strategy = new BasicLookupStrategy(getDataSource(), aclCache(), aclAuthStrategy(), new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger())); this.strategy.setPermissionFactory(new DefaultPermissionFactory()); } protected AclAuthorizationStrategy aclAuthStrategy() { return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMINISTRATOR")); } protected SpringCacheBasedAclCache aclCache() { return new SpringCacheBasedAclCache(getCache(), new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_USER"))); } protected Cache getCache() { Cache cache = cacheManager.getCacheManager().getCache("basiclookuptestcache"); cache.clear(); return cache; } @AfterEach public void emptyDatabase() { String query = "DELETE FROM acl_entry;" + "DELETE FROM acl_object_identity WHERE ID = 9;" + "DELETE FROM acl_object_identity WHERE ID = 8;" + "DELETE FROM acl_object_identity WHERE ID = 7;" + "DELETE FROM acl_object_identity WHERE ID = 6;" + "DELETE FROM acl_object_identity WHERE ID = 5;" + "DELETE FROM acl_object_identity WHERE ID = 4;" + "DELETE FROM acl_object_identity WHERE ID = 3;" + "DELETE FROM acl_object_identity WHERE ID = 2;" + "DELETE FROM acl_object_identity WHERE ID = 1;" + "DELETE FROM acl_class;" + "DELETE FROM acl_sid;"; getJdbcTemplate().execute(query); } @Test public void testAclsRetrievalWithDefaultBatchSize() throws Exception { ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 100L); ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, 101L); // Deliberately use an integer for the child, to reproduce bug report in SEC-819 ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 102); Map<ObjectIdentity, Acl> map = this.strategy .readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null); checkEntries(topParentOid, middleParentOid, childOid, map); } @Test public void testAclsRetrievalFromCacheOnly() throws Exception { ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 100); ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, 101L); ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 102L); // Objects were put in cache this.strategy.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null); // Let's empty the database to force acls retrieval from cache emptyDatabase(); Map<ObjectIdentity, Acl> map = this.strategy .readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null); checkEntries(topParentOid, middleParentOid, childOid, map); } @Test public void testAclsRetrievalWithCustomBatchSize() throws Exception { ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 100L); ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, 101); ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 102L); // Set a batch size to allow multiple database queries in order to retrieve all // acls this.strategy.setBatchSize(1); Map<ObjectIdentity, Acl> map = this.strategy .readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null); checkEntries(topParentOid, middleParentOid, childOid, map); } private void checkEntries(ObjectIdentity topParentOid, ObjectIdentity middleParentOid, ObjectIdentity childOid, Map<ObjectIdentity, Acl> map) { assertThat(map).hasSize(3); MutableAcl topParent = (MutableAcl) map.get(topParentOid); MutableAcl middleParent = (MutableAcl) map.get(middleParentOid); MutableAcl child = (MutableAcl) map.get(childOid); // Check the retrieved versions has IDs assertThat(topParent.getId()).isNotNull(); assertThat(middleParent.getId()).isNotNull(); assertThat(child.getId()).isNotNull(); // Check their parents were correctly retrieved assertThat(topParent.getParentAcl()).isNull(); assertThat(middleParent.getParentAcl().getObjectIdentity()).isEqualTo(topParentOid); assertThat(child.getParentAcl().getObjectIdentity()).isEqualTo(middleParentOid); // Check their ACEs were correctly retrieved assertThat(topParent.getEntries()).hasSize(2); assertThat(middleParent.getEntries()).hasSize(1); assertThat(child.getEntries()).hasSize(1); // Check object identities were correctly retrieved assertThat(topParent.getObjectIdentity()).isEqualTo(topParentOid); assertThat(middleParent.getObjectIdentity()).isEqualTo(middleParentOid); assertThat(child.getObjectIdentity()).isEqualTo(childOid); // Check each entry assertThat(topParent.isEntriesInheriting()).isTrue(); assertThat(Long.valueOf(1)).isEqualTo(topParent.getId()); assertThat(new PrincipalSid("ben")).isEqualTo(topParent.getOwner()); assertThat(Long.valueOf(1)).isEqualTo(topParent.getEntries().get(0).getId()); assertThat(topParent.getEntries().get(0).getPermission()).isEqualTo(BasePermission.READ); assertThat(topParent.getEntries().get(0).getSid()).isEqualTo(new PrincipalSid("ben")); assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(0)).isAuditFailure()).isFalse(); assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(0)).isAuditSuccess()).isFalse(); assertThat((topParent.getEntries().get(0)).isGranting()).isTrue(); assertThat(Long.valueOf(2)).isEqualTo(topParent.getEntries().get(1).getId()); assertThat(topParent.getEntries().get(1).getPermission()).isEqualTo(BasePermission.WRITE); assertThat(topParent.getEntries().get(1).getSid()).isEqualTo(new PrincipalSid("ben")); assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(1)).isAuditFailure()).isFalse(); assertThat(((AuditableAccessControlEntry) topParent.getEntries().get(1)).isAuditSuccess()).isFalse(); assertThat(topParent.getEntries().get(1).isGranting()).isFalse(); assertThat(middleParent.isEntriesInheriting()).isTrue(); assertThat(Long.valueOf(2)).isEqualTo(middleParent.getId()); assertThat(new PrincipalSid("ben")).isEqualTo(middleParent.getOwner()); assertThat(Long.valueOf(3)).isEqualTo(middleParent.getEntries().get(0).getId()); assertThat(middleParent.getEntries().get(0).getPermission()).isEqualTo(BasePermission.DELETE); assertThat(middleParent.getEntries().get(0).getSid()).isEqualTo(new PrincipalSid("ben")); assertThat(((AuditableAccessControlEntry) middleParent.getEntries().get(0)).isAuditFailure()).isFalse(); assertThat(((AuditableAccessControlEntry) middleParent.getEntries().get(0)).isAuditSuccess()).isFalse(); assertThat(middleParent.getEntries().get(0).isGranting()).isTrue(); assertThat(child.isEntriesInheriting()).isTrue(); assertThat(Long.valueOf(3)).isEqualTo(child.getId()); assertThat(new PrincipalSid("ben")).isEqualTo(child.getOwner()); assertThat(Long.valueOf(4)).isEqualTo(child.getEntries().get(0).getId()); assertThat(child.getEntries().get(0).getPermission()).isEqualTo(BasePermission.DELETE); assertThat(new PrincipalSid("ben")).isEqualTo(child.getEntries().get(0).getSid()); assertThat(((AuditableAccessControlEntry) child.getEntries().get(0)).isAuditFailure()).isFalse(); assertThat(((AuditableAccessControlEntry) child.getEntries().get(0)).isAuditSuccess()).isFalse(); assertThat((child.getEntries().get(0)).isGranting()).isFalse(); } @Test public void testAllParentsAreRetrievedWhenChildIsLoaded() { String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (6,2,103,1,1,1);"; getJdbcTemplate().execute(query); ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 100L); ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, 101L); ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 102L); ObjectIdentity middleParent2Oid = new ObjectIdentityImpl(TARGET_CLASS, 103L); // Retrieve the child Map<ObjectIdentity, Acl> map = this.strategy.readAclsById(Arrays.asList(childOid), null); // Check that the child and all its parents were retrieved assertThat(map.get(childOid)).isNotNull(); assertThat(map.get(childOid).getObjectIdentity()).isEqualTo(childOid); assertThat(map.get(middleParentOid)).isNotNull(); assertThat(map.get(middleParentOid).getObjectIdentity()).isEqualTo(middleParentOid); assertThat(map.get(topParentOid)).isNotNull(); assertThat(map.get(topParentOid).getObjectIdentity()).isEqualTo(topParentOid); // The second parent shouldn't have been retrieved assertThat(map.get(middleParent2Oid)).isNull(); } /** * Test created from SEC-590. */ @Test public void testReadAllObjectIdentitiesWhenLastElementIsAlreadyCached() { String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (6,2,105,null,1,1);" + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (7,2,106,6,1,1);" + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (8,2,107,6,1,1);" + "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (9,2,108,7,1,1);" + "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (7,6,0,1,1,1,0,0)"; getJdbcTemplate().execute(query); ObjectIdentity grandParentOid = new ObjectIdentityImpl(TARGET_CLASS, 104L); ObjectIdentity parent1Oid = new ObjectIdentityImpl(TARGET_CLASS, 105L); ObjectIdentity parent2Oid = new ObjectIdentityImpl(TARGET_CLASS, 106); ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 107); // First lookup only child, thus populating the cache with grandParent, // parent1 // and child List<Permission> checkPermission = Arrays.asList(BasePermission.READ); List<Sid> sids = Arrays.asList(BEN_SID); List<ObjectIdentity> childOids = Arrays.asList(childOid); this.strategy.setBatchSize(6); Map<ObjectIdentity, Acl> foundAcls = this.strategy.readAclsById(childOids, sids); Acl foundChildAcl = foundAcls.get(childOid); assertThat(foundChildAcl).isNotNull(); assertThat(foundChildAcl.isGranted(checkPermission, sids, false)).isTrue(); // Search for object identities has to be done in the following order: // last // element have to be one which // is already in cache and the element before it must not be stored in // cache List<ObjectIdentity> allOids = Arrays.asList(grandParentOid, parent1Oid, parent2Oid, childOid); foundAcls = this.strategy.readAclsById(allOids, sids); Acl foundParent2Acl = foundAcls.get(parent2Oid); assertThat(foundParent2Acl).isNotNull(); assertThat(foundParent2Acl.isGranted(checkPermission, sids, false)).isTrue(); } @Test public void nullOwnerIsNotSupported() { String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (6,2,104,null,null,1);"; getJdbcTemplate().execute(query); ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 104L); assertThatIllegalArgumentException() .isThrownBy(() -> this.strategy.readAclsById(Arrays.asList(oid), Arrays.asList(BEN_SID))); } @Test public void testCreatePrincipalSid() { Sid result = this.strategy.createSid(true, "sid"); assertThat(result.getClass()).isEqualTo(PrincipalSid.class); assertThat(((PrincipalSid) result).getPrincipal()).isEqualTo("sid"); } @Test public void testCreateGrantedAuthority() { Sid result = this.strategy.createSid(false, "sid"); assertThat(result.getClass()).isEqualTo(GrantedAuthoritySid.class); assertThat(((GrantedAuthoritySid) result).getGrantedAuthority()).isEqualTo("sid"); } @Test public void setObjectIdentityGeneratorWhenNullThenThrowsIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.strategy.setObjectIdentityGenerator(null)) .withMessage("objectIdentityGenerator cannot be null"); // @formatter:on } private static final class CacheManagerMock { private final List<String> cacheNames; private final CacheManager cacheManager; private CacheManagerMock() { this.cacheNames = new ArrayList<>(); this.cacheManager = mock(CacheManager.class); given(this.cacheManager.getCacheNames()).willReturn(this.cacheNames); } private CacheManager getCacheManager() { return this.cacheManager; } private void addCache(String name) { this.cacheNames.add(name); Cache cache = new ConcurrentMapCache(name); given(this.cacheManager.getCache(name)).willReturn(cache); } private void clear() { this.cacheNames.clear(); } } }
17,671
47.952909
163
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/jdbc/SpringCacheBasedAclCacheTests.java
/* * Copyright 2002-2017 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.security.acls.domain.AclAuthorizationStrategy; import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl; import org.springframework.security.acls.domain.AclImpl; import org.springframework.security.acls.domain.AuditLogger; import org.springframework.security.acls.domain.ConsoleAuditLogger; import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.domain.SpringCacheBasedAclCache; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.PermissionGrantingStrategy; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.util.FieldUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link org.springframework.security.acls.domain.SpringCacheBasedAclCache} * * @author Marten Deinum */ public class SpringCacheBasedAclCacheTests { private static final String TARGET_CLASS = "org.springframework.security.acls.TargetObject"; private static CacheManager cacheManager; @BeforeAll public static void initCacheManaer() { cacheManager = new ConcurrentMapCacheManager(); // Use disk caching immediately (to test for serialization issue reported in // SEC-527) cacheManager.getCache("springcasebasedacltests"); } @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } private Cache getCache() { Cache cache = cacheManager.getCache("springcasebasedacltests"); cache.clear(); return cache; } @Test public void constructorRejectsNullParameters() { assertThatIllegalArgumentException().isThrownBy(() -> new SpringCacheBasedAclCache(null, null, null)); } @SuppressWarnings("rawtypes") @Test public void cacheOperationsAclWithoutParent() { Cache cache = getCache(); Map realCache = (Map) cache.getNativeCache(); ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100L); AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl( new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL")); AuditLogger auditLogger = new ConsoleAuditLogger(); PermissionGrantingStrategy permissionGrantingStrategy = new DefaultPermissionGrantingStrategy(auditLogger); SpringCacheBasedAclCache myCache = new SpringCacheBasedAclCache(cache, permissionGrantingStrategy, aclAuthorizationStrategy); MutableAcl acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, auditLogger); assertThat(realCache).isEmpty(); myCache.putInCache(acl); // Check we can get from cache the same objects we put in assertThat(acl).isEqualTo(myCache.getFromCache(1L)); assertThat(acl).isEqualTo(myCache.getFromCache(identity)); // Put another object in cache ObjectIdentity identity2 = new ObjectIdentityImpl(TARGET_CLASS, 101L); MutableAcl acl2 = new AclImpl(identity2, 2L, aclAuthorizationStrategy, new ConsoleAuditLogger()); myCache.putInCache(acl2); // Try to evict an entry that doesn't exist myCache.evictFromCache(3L); myCache.evictFromCache(new ObjectIdentityImpl(TARGET_CLASS, 102L)); assertThat(realCache).hasSize(4); myCache.evictFromCache(1L); assertThat(realCache).hasSize(2); // Check the second object inserted assertThat(acl2).isEqualTo(myCache.getFromCache(2L)); assertThat(acl2).isEqualTo(myCache.getFromCache(identity2)); myCache.evictFromCache(identity2); assertThat(realCache).isEmpty(); } @SuppressWarnings("rawtypes") @Test public void cacheOperationsAclWithParent() throws Exception { Cache cache = getCache(); Map realCache = (Map) cache.getNativeCache(); Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 1L); ObjectIdentity identityParent = new ObjectIdentityImpl(TARGET_CLASS, 2L); AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl( new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL")); AuditLogger auditLogger = new ConsoleAuditLogger(); PermissionGrantingStrategy permissionGrantingStrategy = new DefaultPermissionGrantingStrategy(auditLogger); SpringCacheBasedAclCache myCache = new SpringCacheBasedAclCache(cache, permissionGrantingStrategy, aclAuthorizationStrategy); MutableAcl acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, auditLogger); MutableAcl parentAcl = new AclImpl(identityParent, 2L, aclAuthorizationStrategy, auditLogger); acl.setParent(parentAcl); assertThat(realCache).isEmpty(); myCache.putInCache(acl); assertThat(4).isEqualTo(realCache.size()); // Check we can get from cache the same objects we put in AclImpl aclFromCache = (AclImpl) myCache.getFromCache(1L); assertThat(aclFromCache).isEqualTo(acl); // SEC-951 check transient fields are set on parent assertThat(FieldUtils.getFieldValue(aclFromCache.getParentAcl(), "aclAuthorizationStrategy")).isNotNull(); assertThat(FieldUtils.getFieldValue(aclFromCache.getParentAcl(), "permissionGrantingStrategy")).isNotNull(); assertThat(myCache.getFromCache(identity)).isEqualTo(acl); assertThat(FieldUtils.getFieldValue(aclFromCache, "aclAuthorizationStrategy")).isNotNull(); AclImpl parentAclFromCache = (AclImpl) myCache.getFromCache(2L); assertThat(parentAclFromCache).isEqualTo(parentAcl); assertThat(FieldUtils.getFieldValue(parentAclFromCache, "aclAuthorizationStrategy")).isNotNull(); assertThat(myCache.getFromCache(identityParent)).isEqualTo(parentAcl); } }
7,193
44.821656
110
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java
/* * Copyright 2002-2018 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.sql.DataSource; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.Sid; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; /** * Unit and Integration tests the ACL JdbcAclService using an in-memory database. * * @author Nena Raab */ @ExtendWith(MockitoExtension.class) public class JdbcAclServiceTests { private EmbeddedDatabase embeddedDatabase; @Mock private DataSource dataSource; @Mock private LookupStrategy lookupStrategy; @Mock JdbcOperations jdbcOperations; private JdbcAclService aclServiceIntegration; private JdbcAclService aclService; @BeforeEach public void setUp() { // @formatter:off this.embeddedDatabase = new EmbeddedDatabaseBuilder() .addScript("createAclSchemaWithAclClassIdType.sql") .addScript("db/sql/test_data_hierarchy.sql") .build(); // @formatter:on this.aclService = new JdbcAclService(this.jdbcOperations, this.lookupStrategy); this.aclServiceIntegration = new JdbcAclService(this.embeddedDatabase, this.lookupStrategy); } @AfterEach public void tearDownEmbeddedDatabase() { this.embeddedDatabase.shutdown(); } // SEC-1898 @Test public void readAclByIdMissingAcl() { Map<ObjectIdentity, Acl> result = new HashMap<>(); given(this.lookupStrategy.readAclsById(anyList(), anyList())).willReturn(result); ObjectIdentity objectIdentity = new ObjectIdentityImpl(Object.class, 1); List<Sid> sids = Arrays.<Sid>asList(new PrincipalSid("user")); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> this.aclService.readAclById(objectIdentity, sids)); } @Test public void findOneChildren() { List<ObjectIdentity> result = new ArrayList<>(); result.add(new ObjectIdentityImpl(Object.class, "5577")); Object[] args = { "1", "org.springframework.security.acls.jdbc.JdbcAclServiceTests$MockLongIdDomainObject" }; given(this.jdbcOperations.query(anyString(), eq(args), any(RowMapper.class))).willReturn(result); ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 1L); List<ObjectIdentity> objectIdentities = this.aclService.findChildren(objectIdentity); assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("5577"); } @Test public void findNoChildren() { ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 1L); List<ObjectIdentity> objectIdentities = this.aclService.findChildren(objectIdentity); assertThat(objectIdentities).isNull(); } @Test public void findChildrenWithoutIdType() { ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 4711L); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity); assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities.get(0).getType()).isEqualTo(MockUntypedIdDomainObject.class.getName()); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo(5000L); } @Test public void findChildrenForUnknownObject() { ObjectIdentity objectIdentity = new ObjectIdentityImpl(Object.class, 33); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity); assertThat(objectIdentities).isNull(); } @Test public void findChildrenOfIdTypeLong() { ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US-PAL"); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity); assertThat(objectIdentities.size()).isEqualTo(2); assertThat(objectIdentities.get(0).getType()).isEqualTo(MockLongIdDomainObject.class.getName()); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo(4711L); assertThat(objectIdentities.get(1).getType()).isEqualTo(MockLongIdDomainObject.class.getName()); assertThat(objectIdentities.get(1).getIdentifier()).isEqualTo(4712L); } @Test public void findChildrenOfIdTypeString() { ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US"); this.aclServiceIntegration.setAclClassIdSupported(true); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity); assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities.get(0).getType()).isEqualTo("location"); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("US-PAL"); } @Test public void findChildrenOfIdTypeUUID() { ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockUntypedIdDomainObject.class, 5000L); this.aclServiceIntegration.setAclClassIdSupported(true); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity); assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities.get(0).getType()).isEqualTo("costcenter"); assertThat(objectIdentities.get(0).getIdentifier()) .isEqualTo(UUID.fromString("25d93b3f-c3aa-4814-9d5e-c7c96ced7762")); } @Test public void setObjectIdentityGeneratorWhenNullThenThrowsIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.aclServiceIntegration.setObjectIdentityGenerator(null)) .withMessage("objectIdentityGenerator cannot be null"); } @Test public void findChildrenWhenObjectIdentityGeneratorSetThenUsed() { this.aclServiceIntegration .setObjectIdentityGenerator((id, type) -> new ObjectIdentityImpl(type, "prefix:" + id)); ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US"); this.aclServiceIntegration.setAclClassIdSupported(true); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity); assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities.get(0).getType()).isEqualTo("location"); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("prefix:US-PAL"); } class MockLongIdDomainObject { private Object id; Object getId() { return this.id; } void setId(Object id) { this.id = id; } } class MockUntypedIdDomainObject { private Object id; Object getId() { return this.id; } void setId(Object id) { this.id = id; } } }
8,181
35.690583
111
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTestsWithAclClassId.java
/* * Copyright 2002-2017 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.util.UUID; import org.junit.jupiter.api.Test; import org.springframework.security.acls.TargetObjectWithUUID; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.ContextConfiguration; import org.springframework.transaction.annotation.Transactional; import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests the ACL system using ACL class id type of UUID and using an in-memory * database. * * @author Paul Wheeler */ @ContextConfiguration(locations = { "/jdbcMutableAclServiceTestsWithAclClass-context.xml" }) public class JdbcMutableAclServiceTestsWithAclClassId extends JdbcMutableAclServiceTests { private static final String TARGET_CLASS_WITH_UUID = TargetObjectWithUUID.class.getName(); private final ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, UUID.randomUUID()); private final ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, UUID.randomUUID()); private final ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, UUID.randomUUID()); @Override protected String getSqlClassPathResource() { return "createAclSchemaWithAclClassIdType.sql"; } @Override protected ObjectIdentity getTopParentOid() { return this.topParentOid; } @Override protected ObjectIdentity getMiddleParentOid() { return this.middleParentOid; } @Override protected ObjectIdentity getChildOid() { return this.childOid; } @Override protected String getTargetClass() { return TARGET_CLASS_WITH_UUID; } @Test @Transactional public void identityWithUuidIdIsSupportedByCreateAcl() { SecurityContextHolder.getContext().setAuthentication(getAuth()); UUID id = UUID.randomUUID(); ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, id); getJdbcMutableAclService().createAcl(oid); assertThat(getJdbcMutableAclService().readAclById(new ObjectIdentityImpl(TARGET_CLASS_WITH_UUID, id))) .isNotNull(); } }
2,829
31.906977
114
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTests.java
/* * Copyright 2002-2017 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import javax.sql.DataSource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.springframework.jdbc.core.JdbcTemplate; /** * Tests {@link BasicLookupStrategy} with Acl Class type id not specified. * * @author Andrei Stefan * @author Paul Wheeler */ public class BasicLookupStrategyTests extends AbstractBasicLookupStrategyTests { private static final BasicLookupStrategyTestsDbHelper DATABASE_HELPER = new BasicLookupStrategyTestsDbHelper(); @BeforeAll public static void createDatabase() throws Exception { DATABASE_HELPER.createDatabase(); } @AfterAll public static void dropDatabase() { DATABASE_HELPER.getDataSource().destroy(); } @Override public JdbcTemplate getJdbcTemplate() { return DATABASE_HELPER.getJdbcTemplate(); } @Override public DataSource getDataSource() { return DATABASE_HELPER.getDataSource(); } }
1,566
26.491228
112
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/jdbc/AclClassIdUtilsTests.java
/* * Copyright 2002-2018 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.io.Serializable; import java.math.BigInteger; import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.convert.ConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; /** * Tests for {@link AclClassIdUtils}. * * @author paulwheeler */ @ExtendWith(MockitoExtension.class) public class AclClassIdUtilsTests { private static final Long DEFAULT_IDENTIFIER = 999L; private static final BigInteger BIGINT_IDENTIFIER = new BigInteger("999"); private static final String DEFAULT_IDENTIFIER_AS_STRING = DEFAULT_IDENTIFIER.toString(); @Mock private ResultSet resultSet; @Mock private ConversionService conversionService; private AclClassIdUtils aclClassIdUtils; @BeforeEach public void setUp() { this.aclClassIdUtils = new AclClassIdUtils(); } @Test public void shouldReturnLongIfIdentifierIsLong() throws SQLException { Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnLongIfIdentifierIsBigInteger() throws SQLException { Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(BIGINT_IDENTIFIER, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnLongIfClassIdTypeIsNull() throws SQLException { given(this.resultSet.getString("class_id_type")).willReturn(null); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnLongIfNoClassIdTypeColumn() throws SQLException { given(this.resultSet.getString("class_id_type")).willThrow(SQLException.class); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnLongIfTypeClassNotFound() throws SQLException { given(this.resultSet.getString("class_id_type")).willReturn("com.example.UnknownType"); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnLongEvenIfCustomConversionServiceDoesNotSupportLongConversion() throws SQLException { given(this.resultSet.getString("class_id_type")).willReturn("java.lang.Long"); given(this.conversionService.canConvert(String.class, Long.class)).willReturn(false); this.aclClassIdUtils.setConversionService(this.conversionService); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnLongWhenLongClassIdType() throws SQLException { given(this.resultSet.getString("class_id_type")).willReturn("java.lang.Long"); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(DEFAULT_IDENTIFIER_AS_STRING, this.resultSet); assertThat(newIdentifier).isEqualTo(DEFAULT_IDENTIFIER); } @Test public void shouldReturnUUIDWhenUUIDClassIdType() throws SQLException { UUID identifier = UUID.randomUUID(); given(this.resultSet.getString("class_id_type")).willReturn("java.util.UUID"); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(identifier.toString(), this.resultSet); assertThat(newIdentifier).isEqualTo(identifier); } @Test public void shouldReturnStringWhenStringClassIdType() throws SQLException { String identifier = "MY_STRING_IDENTIFIER"; given(this.resultSet.getString("class_id_type")).willReturn("java.lang.String"); Serializable newIdentifier = this.aclClassIdUtils.identifierFrom(identifier, this.resultSet); assertThat(newIdentifier).isEqualTo(identifier); } @Test public void shouldNotAcceptNullConversionServiceInConstruction() { assertThatIllegalArgumentException().isThrownBy(() -> new AclClassIdUtils(null)); } @Test public void shouldNotAcceptNullConversionServiceInSetter() { assertThatIllegalArgumentException().isThrownBy(() -> this.aclClassIdUtils.setConversionService(null)); } }
5,304
36.892857
113
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcMutableAclServiceTests.java
/* * Copyright 2004, 2005, 2006, 2017 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.acls.TargetObject; import org.springframework.security.acls.domain.AclImpl; import org.springframework.security.acls.domain.BasePermission; import org.springframework.security.acls.domain.CumulativePermission; import org.springframework.security.acls.domain.GrantedAuthoritySid; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.AccessControlEntry; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AclCache; import org.springframework.security.acls.model.AlreadyExistsException; import org.springframework.security.acls.model.ChildrenExistException; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.Sid; import org.springframework.security.acls.sid.CustomSid; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; import org.springframework.transaction.annotation.Transactional; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /** * Integration tests the ACL system using an in-memory database. * * @author Ben Alex * @author Andrei Stefan */ @Transactional @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "/jdbcMutableAclServiceTests-context.xml" }) public class JdbcMutableAclServiceTests { private static final String TARGET_CLASS = TargetObject.class.getName(); private final Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_ADMINISTRATOR"); public static final String SELECT_ALL_CLASSES = "SELECT * FROM acl_class WHERE class = ?"; private final ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 100L); private final ObjectIdentity middleParentOid = new ObjectIdentityImpl(TARGET_CLASS, 101L); private final ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 102L); @Autowired private JdbcMutableAclService jdbcMutableAclService; @Autowired private AclCache aclCache; @Autowired private LookupStrategy lookupStrategy; @Autowired private DataSource dataSource; @Autowired private JdbcTemplate jdbcTemplate; protected String getSqlClassPathResource() { return "createAclSchema.sql"; } protected ObjectIdentity getTopParentOid() { return this.topParentOid; } protected ObjectIdentity getMiddleParentOid() { return this.middleParentOid; } protected ObjectIdentity getChildOid() { return this.childOid; } protected String getTargetClass() { return TARGET_CLASS; } @BeforeTransaction public void createTables() throws Exception { try { new DatabaseSeeder(this.dataSource, new ClassPathResource(getSqlClassPathResource())); // new DatabaseSeeder(dataSource, new // ClassPathResource("createAclSchemaPostgres.sql")); } catch (Exception ex) { ex.printStackTrace(); throw ex; } } @AfterTransaction public void clearContextAndData() { SecurityContextHolder.clearContext(); this.jdbcTemplate.execute("drop table acl_entry"); this.jdbcTemplate.execute("drop table acl_object_identity"); this.jdbcTemplate.execute("drop table acl_class"); this.jdbcTemplate.execute("drop table acl_sid"); this.aclCache.clearCache(); } @Test @Transactional public void testLifecycle() { SecurityContextHolder.getContext().setAuthentication(this.auth); MutableAcl topParent = this.jdbcMutableAclService.createAcl(getTopParentOid()); MutableAcl middleParent = this.jdbcMutableAclService.createAcl(getMiddleParentOid()); MutableAcl child = this.jdbcMutableAclService.createAcl(getChildOid()); // Specify the inheritance hierarchy middleParent.setParent(topParent); child.setParent(middleParent); // Now let's add a couple of permissions topParent.insertAce(0, BasePermission.READ, new PrincipalSid(this.auth), true); topParent.insertAce(1, BasePermission.WRITE, new PrincipalSid(this.auth), false); middleParent.insertAce(0, BasePermission.DELETE, new PrincipalSid(this.auth), true); child.insertAce(0, BasePermission.DELETE, new PrincipalSid(this.auth), false); // Explicitly save the changed ACL this.jdbcMutableAclService.updateAcl(topParent); this.jdbcMutableAclService.updateAcl(middleParent); this.jdbcMutableAclService.updateAcl(child); // Let's check if we can read them back correctly Map<ObjectIdentity, Acl> map = this.jdbcMutableAclService .readAclsById(Arrays.asList(getTopParentOid(), getMiddleParentOid(), getChildOid())); assertThat(map).hasSize(3); // Get the retrieved versions MutableAcl retrievedTopParent = (MutableAcl) map.get(getTopParentOid()); MutableAcl retrievedMiddleParent = (MutableAcl) map.get(getMiddleParentOid()); MutableAcl retrievedChild = (MutableAcl) map.get(getChildOid()); // Check the retrieved versions has IDs assertThat(retrievedTopParent.getId()).isNotNull(); assertThat(retrievedMiddleParent.getId()).isNotNull(); assertThat(retrievedChild.getId()).isNotNull(); // Check their parents were correctly persisted assertThat(retrievedTopParent.getParentAcl()).isNull(); assertThat(retrievedMiddleParent.getParentAcl().getObjectIdentity()).isEqualTo(getTopParentOid()); assertThat(retrievedChild.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid()); // Check their ACEs were correctly persisted assertThat(retrievedTopParent.getEntries()).hasSize(2); assertThat(retrievedMiddleParent.getEntries()).hasSize(1); assertThat(retrievedChild.getEntries()).hasSize(1); // Check the retrieved rights are correct List<Permission> read = Arrays.asList(BasePermission.READ); List<Permission> write = Arrays.asList(BasePermission.WRITE); List<Permission> delete = Arrays.asList(BasePermission.DELETE); List<Sid> pSid = Arrays.asList((Sid) new PrincipalSid(this.auth)); assertThat(retrievedTopParent.isGranted(read, pSid, false)).isTrue(); assertThat(retrievedTopParent.isGranted(write, pSid, false)).isFalse(); assertThat(retrievedMiddleParent.isGranted(delete, pSid, false)).isTrue(); assertThat(retrievedChild.isGranted(delete, pSid, false)).isFalse(); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> retrievedChild.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), pSid, false)); // Now check the inherited rights (when not explicitly overridden) also look OK assertThat(retrievedChild.isGranted(read, pSid, false)).isTrue(); assertThat(retrievedChild.isGranted(write, pSid, false)).isFalse(); assertThat(retrievedChild.isGranted(delete, pSid, false)).isFalse(); // Next change the child so it doesn't inherit permissions from above retrievedChild.setEntriesInheriting(false); this.jdbcMutableAclService.updateAcl(retrievedChild); MutableAcl nonInheritingChild = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid()); assertThat(nonInheritingChild.isEntriesInheriting()).isFalse(); // Check the child permissions no longer inherit assertThat(nonInheritingChild.isGranted(delete, pSid, true)).isFalse(); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> nonInheritingChild.isGranted(read, pSid, true)); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> nonInheritingChild.isGranted(write, pSid, true)); // Let's add an identical permission to the child, but it'll appear AFTER the // current permission, so has no impact nonInheritingChild.insertAce(1, BasePermission.DELETE, new PrincipalSid(this.auth), true); // Let's also add another permission to the child nonInheritingChild.insertAce(2, BasePermission.CREATE, new PrincipalSid(this.auth), true); // Save the changed child this.jdbcMutableAclService.updateAcl(nonInheritingChild); MutableAcl retrievedNonInheritingChild = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid()); assertThat(retrievedNonInheritingChild.getEntries()).hasSize(3); // Output permissions for (int i = 0; i < retrievedNonInheritingChild.getEntries().size(); i++) { System.out.println(retrievedNonInheritingChild.getEntries().get(i)); } // Check the permissions are as they should be assertThat(retrievedNonInheritingChild.isGranted(delete, pSid, true)).isFalse(); // as // earlier // permission // overrode assertThat(retrievedNonInheritingChild.isGranted(Arrays.asList(BasePermission.CREATE), pSid, true)).isTrue(); // Now check the first ACE (index 0) really is DELETE for our Sid and is // non-granting AccessControlEntry entry = retrievedNonInheritingChild.getEntries().get(0); assertThat(entry.getPermission().getMask()).isEqualTo(BasePermission.DELETE.getMask()); assertThat(entry.getSid()).isEqualTo(new PrincipalSid(this.auth)); assertThat(entry.isGranting()).isFalse(); assertThat(entry.getId()).isNotNull(); // Now delete that first ACE retrievedNonInheritingChild.deleteAce(0); // Save and check it worked MutableAcl savedChild = this.jdbcMutableAclService.updateAcl(retrievedNonInheritingChild); assertThat(savedChild.getEntries()).hasSize(2); assertThat(savedChild.isGranted(delete, pSid, false)).isTrue(); SecurityContextHolder.clearContext(); } /** * Test method that demonstrates eviction failure from cache - SEC-676 */ @Test @Transactional public void deleteAclAlsoDeletesChildren() { SecurityContextHolder.getContext().setAuthentication(this.auth); this.jdbcMutableAclService.createAcl(getTopParentOid()); MutableAcl middleParent = this.jdbcMutableAclService.createAcl(getMiddleParentOid()); MutableAcl child = this.jdbcMutableAclService.createAcl(getChildOid()); child.setParent(middleParent); this.jdbcMutableAclService.updateAcl(middleParent); this.jdbcMutableAclService.updateAcl(child); // Check the childOid really is a child of middleParentOid Acl childAcl = this.jdbcMutableAclService.readAclById(getChildOid()); assertThat(childAcl.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid()); // Delete the mid-parent and test if the child was deleted, as well this.jdbcMutableAclService.deleteAcl(getMiddleParentOid(), true); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> this.jdbcMutableAclService.readAclById(getMiddleParentOid())); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> this.jdbcMutableAclService.readAclById(getChildOid())); Acl acl = this.jdbcMutableAclService.readAclById(getTopParentOid()); assertThat(acl).isNotNull(); assertThat(getTopParentOid()).isEqualTo(acl.getObjectIdentity()); } @Test public void constructorRejectsNullParameters() { assertThatIllegalArgumentException() .isThrownBy(() -> new JdbcMutableAclService(null, this.lookupStrategy, this.aclCache)); assertThatIllegalArgumentException() .isThrownBy(() -> new JdbcMutableAclService(this.dataSource, null, this.aclCache)); assertThatIllegalArgumentException() .isThrownBy(() -> new JdbcMutableAclService(this.dataSource, this.lookupStrategy, null)); } @Test public void createAclRejectsNullParameter() { assertThatIllegalArgumentException().isThrownBy(() -> this.jdbcMutableAclService.createAcl(null)); } @Test @Transactional public void createAclForADuplicateDomainObject() { SecurityContextHolder.getContext().setAuthentication(this.auth); ObjectIdentity duplicateOid = new ObjectIdentityImpl(TARGET_CLASS, 100L); this.jdbcMutableAclService.createAcl(duplicateOid); // Try to add the same object second time assertThatExceptionOfType(AlreadyExistsException.class) .isThrownBy(() -> this.jdbcMutableAclService.createAcl(duplicateOid)); } @Test @Transactional public void deleteAclRejectsNullParameters() { assertThatIllegalArgumentException().isThrownBy(() -> this.jdbcMutableAclService.deleteAcl(null, true)); } @Test @Transactional public void deleteAclWithChildrenThrowsException() { SecurityContextHolder.getContext().setAuthentication(this.auth); MutableAcl parent = this.jdbcMutableAclService.createAcl(getTopParentOid()); MutableAcl child = this.jdbcMutableAclService.createAcl(getMiddleParentOid()); // Specify the inheritance hierarchy child.setParent(parent); this.jdbcMutableAclService.updateAcl(child); // switch on FK this.jdbcMutableAclService.setForeignKeysInDatabase(false); try { // checking in the class, not database assertThatExceptionOfType(ChildrenExistException.class) .isThrownBy(() -> this.jdbcMutableAclService.deleteAcl(getTopParentOid(), false)); } finally { // restore to the default this.jdbcMutableAclService.setForeignKeysInDatabase(true); } } @Test @Transactional public void deleteAclRemovesRowsFromDatabase() { SecurityContextHolder.getContext().setAuthentication(this.auth); MutableAcl child = this.jdbcMutableAclService.createAcl(getChildOid()); child.insertAce(0, BasePermission.DELETE, new PrincipalSid(this.auth), false); this.jdbcMutableAclService.updateAcl(child); // Remove the child and check all related database rows were removed accordingly this.jdbcMutableAclService.deleteAcl(getChildOid(), false); assertThat(this.jdbcTemplate.queryForList(SELECT_ALL_CLASSES, new Object[] { getTargetClass() })).hasSize(1); assertThat(this.jdbcTemplate.queryForList("select * from acl_object_identity")).isEmpty(); assertThat(this.jdbcTemplate.queryForList("select * from acl_entry")).isEmpty(); // Check the cache assertThat(this.aclCache.getFromCache(getChildOid())).isNull(); assertThat(this.aclCache.getFromCache(102L)).isNull(); } /** SEC-1107 */ @Test @Transactional public void identityWithIntegerIdIsSupportedByCreateAcl() { SecurityContextHolder.getContext().setAuthentication(this.auth); ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 101); this.jdbcMutableAclService.createAcl(oid); assertThat(this.jdbcMutableAclService.readAclById(new ObjectIdentityImpl(TARGET_CLASS, 101L))).isNotNull(); } @Test @Transactional public void createAclWhenCustomSecurityContextHolderStrategyThenUses() { SecurityContextHolderStrategy securityContextHolderStrategy = mock(SecurityContextHolderStrategy.class); SecurityContext context = new SecurityContextImpl(this.auth); given(securityContextHolderStrategy.getContext()).willReturn(context); JdbcMutableAclService service = new JdbcMutableAclService(this.dataSource, this.lookupStrategy, this.aclCache); service.setSecurityContextHolderStrategy(securityContextHolderStrategy); ObjectIdentity oid = new ObjectIdentityImpl(TARGET_CLASS, 101); service.createAcl(oid); verify(securityContextHolderStrategy).getContext(); } /** * SEC-655 */ @Test @Transactional public void childrenAreClearedFromCacheWhenParentIsUpdated() { Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_ADMINISTRATOR"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity parentOid = new ObjectIdentityImpl(TARGET_CLASS, 104L); ObjectIdentity childOid = new ObjectIdentityImpl(TARGET_CLASS, 105L); MutableAcl parent = this.jdbcMutableAclService.createAcl(parentOid); MutableAcl child = this.jdbcMutableAclService.createAcl(childOid); child.setParent(parent); this.jdbcMutableAclService.updateAcl(child); parent = (AclImpl) this.jdbcMutableAclService.readAclById(parentOid); parent.insertAce(0, BasePermission.READ, new PrincipalSid("ben"), true); this.jdbcMutableAclService.updateAcl(parent); parent = (AclImpl) this.jdbcMutableAclService.readAclById(parentOid); parent.insertAce(1, BasePermission.READ, new PrincipalSid("scott"), true); this.jdbcMutableAclService.updateAcl(parent); child = (MutableAcl) this.jdbcMutableAclService.readAclById(childOid); parent = (MutableAcl) child.getParentAcl(); assertThat(parent.getEntries()).hasSize(2) .withFailMessage("Fails because child has a stale reference to its parent"); assertThat(parent.getEntries().get(0).getPermission().getMask()).isEqualTo(1); assertThat(parent.getEntries().get(0).getSid()).isEqualTo(new PrincipalSid("ben")); assertThat(parent.getEntries().get(1).getPermission().getMask()).isEqualTo(1); assertThat(parent.getEntries().get(1).getSid()).isEqualTo(new PrincipalSid("scott")); } /** * SEC-655 */ @Test @Transactional public void childrenAreClearedFromCacheWhenParentisUpdated2() { Authentication auth = new TestingAuthenticationToken("system", "secret", "ROLE_IGNORED"); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentityImpl rootObject = new ObjectIdentityImpl(TARGET_CLASS, 1L); MutableAcl parent = this.jdbcMutableAclService.createAcl(rootObject); MutableAcl child = this.jdbcMutableAclService.createAcl(new ObjectIdentityImpl(TARGET_CLASS, 2L)); child.setParent(parent); this.jdbcMutableAclService.updateAcl(child); parent.insertAce(0, BasePermission.ADMINISTRATION, new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), true); this.jdbcMutableAclService.updateAcl(parent); parent.insertAce(1, BasePermission.DELETE, new PrincipalSid("terry"), true); this.jdbcMutableAclService.updateAcl(parent); child = (MutableAcl) this.jdbcMutableAclService.readAclById(new ObjectIdentityImpl(TARGET_CLASS, 2L)); parent = (MutableAcl) child.getParentAcl(); assertThat(parent.getEntries()).hasSize(2); assertThat(parent.getEntries().get(0).getPermission().getMask()).isEqualTo(16); assertThat(parent.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_ADMINISTRATOR")); assertThat(parent.getEntries().get(1).getPermission().getMask()).isEqualTo(8); assertThat(parent.getEntries().get(1).getSid()).isEqualTo(new PrincipalSid("terry")); } @Test @Transactional public void cumulativePermissions() { Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_ADMINISTRATOR"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, 110L); MutableAcl topParent = this.jdbcMutableAclService.createAcl(topParentOid); // Add an ACE permission entry Permission cm = new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION); assertThat(cm.getMask()).isEqualTo(17); Sid benSid = new PrincipalSid(auth); topParent.insertAce(0, cm, benSid, true); assertThat(topParent.getEntries()).hasSize(1); // Explicitly save the changed ACL topParent = this.jdbcMutableAclService.updateAcl(topParent); // Check the mask was retrieved correctly assertThat(topParent.getEntries().get(0).getPermission().getMask()).isEqualTo(17); assertThat(topParent.isGranted(Arrays.asList(cm), Arrays.asList(benSid), true)).isTrue(); SecurityContextHolder.clearContext(); } @Test public void testProcessingCustomSid() { CustomJdbcMutableAclService customJdbcMutableAclService = spy( new CustomJdbcMutableAclService(this.dataSource, this.lookupStrategy, this.aclCache)); CustomSid customSid = new CustomSid("Custom sid"); given(customJdbcMutableAclService.createOrRetrieveSidPrimaryKey("Custom sid", false, false)).willReturn(1L); Long result = customJdbcMutableAclService.createOrRetrieveSidPrimaryKey(customSid, false); assertThat(Long.valueOf(1L)).isEqualTo(result); } protected Authentication getAuth() { return this.auth; } protected JdbcMutableAclService getJdbcMutableAclService() { return this.jdbcMutableAclService; } /** * This class needed to show how to extend {@link JdbcMutableAclService} for * processing custom {@link Sid} implementations */ private class CustomJdbcMutableAclService extends JdbcMutableAclService { CustomJdbcMutableAclService(DataSource dataSource, LookupStrategy lookupStrategy, AclCache aclCache) { super(dataSource, lookupStrategy, aclCache); } @Override protected Long createOrRetrieveSidPrimaryKey(Sid sid, boolean allowCreate) { String sidName; boolean isPrincipal = false; if (sid instanceof CustomSid) { sidName = ((CustomSid) sid).getSid(); } else if (sid instanceof GrantedAuthoritySid) { sidName = ((GrantedAuthoritySid) sid).getGrantedAuthority(); } else { sidName = ((PrincipalSid) sid).getPrincipal(); isPrincipal = true; } return createOrRetrieveSidPrimaryKey(sidName, isPrincipal, allowCreate); } } }
22,523
44.228916
113
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/jdbc/DatabaseSeeder.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.io.IOException; import javax.sql.DataSource; import org.springframework.core.io.Resource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.util.Assert; import org.springframework.util.FileCopyUtils; /** * Seeds the database for {@link JdbcMutableAclServiceTests}. * * @author Ben Alex */ public class DatabaseSeeder { public DatabaseSeeder(DataSource dataSource, Resource resource) throws IOException { Assert.notNull(dataSource, "dataSource required"); Assert.notNull(resource, "resource required"); JdbcTemplate template = new JdbcTemplate(dataSource); String sql = new String(FileCopyUtils.copyToByteArray(resource.getInputStream())); template.execute(sql); } }
1,403
30.909091
85
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/jdbc/BasicLookupStrategyTestsDbHelper.java
/* * Copyright 2002-2017 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; import org.springframework.util.FileCopyUtils; /** * Helper class to initialize the database for BasicLookupStrategyTests. * * @author Andrei Stefan * @author Paul Wheeler */ public class BasicLookupStrategyTestsDbHelper { private static final String ACL_SCHEMA_SQL_FILE = "createAclSchema.sql"; private static final String ACL_SCHEMA_SQL_FILE_WITH_ACL_CLASS_ID = "createAclSchemaWithAclClassIdType.sql"; private SingleConnectionDataSource dataSource; private JdbcTemplate jdbcTemplate; private boolean withAclClassIdType; public BasicLookupStrategyTestsDbHelper() { } public BasicLookupStrategyTestsDbHelper(boolean withAclClassIdType) { this.withAclClassIdType = withAclClassIdType; } public void createDatabase() throws Exception { // Use a different connection url so the tests can run in parallel String connectionUrl; String sqlClassPathResource; if (!this.withAclClassIdType) { connectionUrl = "jdbc:hsqldb:mem:lookupstrategytest"; sqlClassPathResource = ACL_SCHEMA_SQL_FILE; } else { connectionUrl = "jdbc:hsqldb:mem:lookupstrategytestWithAclClassIdType"; sqlClassPathResource = ACL_SCHEMA_SQL_FILE_WITH_ACL_CLASS_ID; } this.dataSource = new SingleConnectionDataSource(connectionUrl, "sa", "", true); this.dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); this.jdbcTemplate = new JdbcTemplate(this.dataSource); Resource resource = new ClassPathResource(sqlClassPathResource); String sql = new String(FileCopyUtils.copyToByteArray(resource.getInputStream())); this.jdbcTemplate.execute(sql); } public JdbcTemplate getJdbcTemplate() { return this.jdbcTemplate; } public SingleConnectionDataSource getDataSource() { return this.dataSource; } }
2,624
32.227848
109
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProviderTests.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.afterinvocation; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.SidRetrievalStrategy; import org.springframework.security.core.Authentication; import org.springframework.security.core.SpringSecurityMessageSource; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; /** * @author Luke Taylor */ @SuppressWarnings({ "unchecked" }) public class AclEntryAfterInvocationProviderTests { @Test public void rejectsMissingPermissions() { assertThatIllegalArgumentException() .isThrownBy(() -> new AclEntryAfterInvocationProvider(mock(AclService.class), null)); assertThatIllegalArgumentException().isThrownBy( () -> new AclEntryAfterInvocationProvider(mock(AclService.class), Collections.<Permission>emptyList())); } @Test public void accessIsAllowedIfPermissionIsGranted() { AclService service = mock(AclService.class); Acl acl = mock(Acl.class); given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(true); given(service.readAclById(any(), any())).willReturn(acl); AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class))); provider.setMessageSource(new SpringSecurityMessageSource()); provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class)); provider.setProcessDomainObjectClass(Object.class); provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class)); Object returned = new Object(); assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("AFTER_ACL_READ"), returned)); } @Test public void accessIsGrantedIfNoAttributesDefined() { AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(mock(AclService.class), Arrays.asList(mock(Permission.class))); Object returned = new Object(); assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(), Collections.<ConfigAttribute>emptyList(), returned)); } @Test public void accessIsGrantedIfObjectTypeNotSupported() { AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(mock(AclService.class), Arrays.asList(mock(Permission.class))); provider.setProcessDomainObjectClass(String.class); // Not a String Object returned = new Object(); assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("AFTER_ACL_READ"), returned)); } @Test public void accessIsDeniedIfPermissionIsNotGranted() { AclService service = mock(AclService.class); Acl acl = mock(Acl.class); given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(false); // Try a second time with no permissions found given(acl.isGranted(any(), any(List.class), anyBoolean())).willThrow(new NotFoundException("")); given(service.readAclById(any(), any())).willReturn(acl); AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class))); provider.setProcessConfigAttribute("MY_ATTRIBUTE"); provider.setMessageSource(new SpringSecurityMessageSource()); provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class)); provider.setProcessDomainObjectClass(Object.class); provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class)); assertThatExceptionOfType(AccessDeniedException.class) .isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object())); // Second scenario with no acls found assertThatExceptionOfType(AccessDeniedException.class) .isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object())); } @Test public void nullReturnObjectIsIgnored() { AclService service = mock(AclService.class); AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class))); assertThat(provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null)).isNull(); verify(service, never()).readAclById(any(ObjectIdentity.class), any(List.class)); } }
6,116
44.649254
108
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationCollectionFilteringProviderTests.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.afterinvocation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.SidRetrievalStrategy; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; /** * @author Luke Taylor */ @SuppressWarnings({ "unchecked" }) public class AclEntryAfterInvocationCollectionFilteringProviderTests { @Test public void objectsAreRemovedIfPermissionDenied() { AclService service = mock(AclService.class); Acl acl = mock(Acl.class); given(acl.isGranted(any(), any(), anyBoolean())).willReturn(false); given(service.readAclById(any(), any())).willReturn(acl); AclEntryAfterInvocationCollectionFilteringProvider provider = new AclEntryAfterInvocationCollectionFilteringProvider( service, Arrays.asList(mock(Permission.class))); provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class)); provider.setProcessDomainObjectClass(Object.class); provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class)); Object returned = provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), new ArrayList(Arrays.asList(new Object(), new Object()))); assertThat(returned).isInstanceOf(List.class); assertThat(((List) returned)).isEmpty(); returned = provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("UNSUPPORTED", "AFTER_ACL_COLLECTION_READ"), new Object[] { new Object(), new Object() }); assertThat(returned instanceof Object[]).isTrue(); assertThat(((Object[]) returned).length == 0).isTrue(); } @Test public void accessIsGrantedIfNoAttributesDefined() { AclEntryAfterInvocationCollectionFilteringProvider provider = new AclEntryAfterInvocationCollectionFilteringProvider( mock(AclService.class), Arrays.asList(mock(Permission.class))); Object returned = new Object(); assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(), Collections.<ConfigAttribute>emptyList(), returned)); } @Test public void nullReturnObjectIsIgnored() { AclService service = mock(AclService.class); AclEntryAfterInvocationCollectionFilteringProvider provider = new AclEntryAfterInvocationCollectionFilteringProvider( service, Arrays.asList(mock(Permission.class))); assertThat(provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), null)).isNull(); verify(service, never()).readAclById(any(ObjectIdentity.class), any(List.class)); } }
4,054
42.602151
119
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/domain/AclAuthorizationStrategyImplTests.java
/* * Copyright 2002-2022 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.util.Arrays; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.acls.model.Acl; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.core.context.SecurityContextImpl; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; /** * @author Rob Winch * */ @ExtendWith(MockitoExtension.class) public class AclAuthorizationStrategyImplTests { SecurityContext context; @Mock Acl acl; @Mock SecurityContextHolderStrategy securityContextHolderStrategy; GrantedAuthority authority; AclAuthorizationStrategyImpl strategy; @BeforeEach public void setup() { this.authority = new SimpleGrantedAuthority("ROLE_AUTH"); TestingAuthenticationToken authentication = new TestingAuthenticationToken("foo", "bar", Arrays.asList(this.authority)); authentication.setAuthenticated(true); this.context = new SecurityContextImpl(authentication); SecurityContextHolder.setContext(this.context); } @AfterEach public void cleanup() { SecurityContextHolder.clearContext(); } // gh-4085 @Test public void securityCheckWhenCustomAuthorityThenNameIsUsed() { this.strategy = new AclAuthorizationStrategyImpl(new CustomAuthority()); this.strategy.securityCheck(this.acl, AclAuthorizationStrategy.CHANGE_GENERAL); } // gh-9425 @Test public void securityCheckWhenAclOwnedByGrantedAuthority() { given(this.acl.getOwner()).willReturn(new GrantedAuthoritySid("ROLE_AUTH")); this.strategy = new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_SYSTEM_ADMIN")); this.strategy.securityCheck(this.acl, AclAuthorizationStrategy.CHANGE_GENERAL); } @Test public void securityCheckWhenCustomSecurityContextHolderStrategyThenUses() { given(this.securityContextHolderStrategy.getContext()).willReturn(this.context); given(this.acl.getOwner()).willReturn(new GrantedAuthoritySid("ROLE_AUTH")); this.strategy = new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_SYSTEM_ADMIN")); this.strategy.setSecurityContextHolderStrategy(this.securityContextHolderStrategy); this.strategy.securityCheck(this.acl, AclAuthorizationStrategy.CHANGE_GENERAL); verify(this.securityContextHolderStrategy).getContext(); } @SuppressWarnings("serial") class CustomAuthority implements GrantedAuthority { @Override public String getAuthority() { return AclAuthorizationStrategyImplTests.this.authority.getAuthority(); } } }
3,729
32.909091
100
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/domain/AclImplementationSecurityCheckTests.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatNoException; /** * Test class for {@link AclAuthorizationStrategyImpl} and {@link AclImpl} security * checks. * * @author Andrei Stefan */ public class AclImplementationSecurityCheckTests { private static final String TARGET_CLASS = "org.springframework.security.acls.TargetObject"; @BeforeEach public void setUp() { SecurityContextHolder.clearContext(); } @AfterEach public void tearDown() { SecurityContextHolder.clearContext(); } @Test public void testSecurityCheckNoACEs() { Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL", "ROLE_AUDITING", "ROLE_OWNERSHIP"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100L); AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl( new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL")); Acl acl = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger()); aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL); aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING); aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP); // Create another authorization strategy AclAuthorizationStrategy aclAuthorizationStrategy2 = new AclAuthorizationStrategyImpl( new SimpleGrantedAuthority("ROLE_ONE"), new SimpleGrantedAuthority("ROLE_TWO"), new SimpleGrantedAuthority("ROLE_THREE")); Acl acl2 = new AclImpl(identity, 1L, aclAuthorizationStrategy2, new ConsoleAuditLogger()); // Check access in case the principal has no authorization rights assertThatExceptionOfType(NotFoundException.class).isThrownBy( () -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_GENERAL)); assertThatExceptionOfType(NotFoundException.class).isThrownBy( () -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_AUDITING)); assertThatExceptionOfType(NotFoundException.class).isThrownBy( () -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); } @Test public void testSecurityCheckWithMultipleACEs() { // Create a simple authentication with ROLE_GENERAL Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100L); // Authorization strategy will require a different role for each access AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl( new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL")); // Let's give the principal the ADMINISTRATION permission, without // granting access MutableAcl aclFirstDeny = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger()); aclFirstDeny.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false); // The CHANGE_GENERAL test should pass as the principal has ROLE_GENERAL aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_GENERAL); // The CHANGE_AUDITING and CHANGE_OWNERSHIP should fail since the // principal doesn't have these authorities, // nor granting access assertThatExceptionOfType(AccessDeniedException.class).isThrownBy( () -> aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING)); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy( () -> aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); // Add granting access to this principal aclFirstDeny.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true); // and try again for CHANGE_AUDITING - the first ACE's granting flag // (false) will deny this access assertThatExceptionOfType(AccessDeniedException.class).isThrownBy( () -> aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING)); // Create another ACL and give the principal the ADMINISTRATION // permission, with granting access MutableAcl aclFirstAllow = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger()); aclFirstAllow.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true); // The CHANGE_AUDITING test should pass as there is one ACE with // granting access aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING); // Add a deny ACE and test again for CHANGE_AUDITING aclFirstAllow.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false); assertThatNoException().isThrownBy( () -> aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING)); // Create an ACL with no ACE MutableAcl aclNoACE = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger()); assertThatExceptionOfType(NotFoundException.class).isThrownBy( () -> aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_AUDITING)); // and still grant access for CHANGE_GENERAL assertThatNoException().isThrownBy( () -> aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_GENERAL)); } @Test public void testSecurityCheckWithInheritableACEs() { // Create a simple authentication with ROLE_GENERAL Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_GENERAL"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100); // Authorization strategy will require a different role for each access AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl( new SimpleGrantedAuthority("ROLE_ONE"), new SimpleGrantedAuthority("ROLE_TWO"), new SimpleGrantedAuthority("ROLE_GENERAL")); // Let's give the principal an ADMINISTRATION permission, with granting // access MutableAcl parentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger()); parentAcl.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true); MutableAcl childAcl = new AclImpl(identity, 2, aclAuthorizationStrategy, new ConsoleAuditLogger()); // Check against the 'child' acl, which doesn't offer any authorization // rights on CHANGE_OWNERSHIP assertThatExceptionOfType(NotFoundException.class).isThrownBy( () -> aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); // Link the child with its parent and test again against the // CHANGE_OWNERSHIP right childAcl.setParent(parentAcl); childAcl.setEntriesInheriting(true); assertThatNoException().isThrownBy( () -> aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); // Create a root parent and link it to the middle parent MutableAcl rootParentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger()); parentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger()); rootParentAcl.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true); parentAcl.setEntriesInheriting(true); parentAcl.setParent(rootParentAcl); childAcl.setParent(parentAcl); assertThatNoException().isThrownBy( () -> aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); } @Test public void testSecurityCheckPrincipalOwner() { Authentication auth = new TestingAuthenticationToken("user", "password", "ROLE_ONE"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, 100); AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl( new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL")); Acl acl = new AclImpl(identity, 1, aclAuthorizationStrategy, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), null, null, false, new PrincipalSid(auth)); assertThatNoException() .isThrownBy(() -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL)); assertThatExceptionOfType(NotFoundException.class).isThrownBy( () -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING)); assertThatNoException().isThrownBy( () -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP)); } }
10,531
53.854167
108
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityImplTests.java
/* * Copyright 2002-2017 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.junit.jupiter.api.Test; import org.springframework.security.acls.model.ObjectIdentity; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatNoException; /** * Tests for {@link ObjectIdentityImpl}. * * @author Andrei Stefan */ @SuppressWarnings("unused") public class ObjectIdentityImplTests { private static final String DOMAIN_CLASS = "org.springframework.security.acls.domain.ObjectIdentityImplTests$MockIdDomainObject"; @Test public void constructorsRespectRequiredFields() { // Check one-argument constructor required field assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(null)); // Check String-Serializable constructor required field assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl("", 1L)); // Check Serializable parameter is not null assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(DOMAIN_CLASS, null)); // The correct way of using String-Serializable constructor assertThatNoException().isThrownBy(() -> new ObjectIdentityImpl(DOMAIN_CLASS, 1L)); // Check the Class-Serializable constructor assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(MockIdDomainObject.class, null)); } @Test public void gettersReturnExpectedValues() { ObjectIdentity obj = new ObjectIdentityImpl(DOMAIN_CLASS, 1L); assertThat(obj.getIdentifier()).isEqualTo(1L); assertThat(obj.getType()).isEqualTo(MockIdDomainObject.class.getName()); } @Test public void testGetIdMethodConstraints() { // Check the getId() method is present assertThatExceptionOfType(IdentityUnavailableException.class) .isThrownBy(() -> new ObjectIdentityImpl("A_STRING_OBJECT")); // getId() should return a non-null value MockIdDomainObject mockId = new MockIdDomainObject(); assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(mockId)); // getId() should return a Serializable object mockId.setId(new MockIdDomainObject()); assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(mockId)); // getId() should return a Serializable object mockId.setId(100L); assertThatNoException().isThrownBy(() -> new ObjectIdentityImpl(mockId)); } @Test public void constructorRejectsInvalidTypeParameter() { assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl("", 1L)); } @Test public void testEquals() { ObjectIdentity obj = new ObjectIdentityImpl(DOMAIN_CLASS, 1L); MockIdDomainObject mockObj = new MockIdDomainObject(); mockObj.setId(1L); String string = "SOME_STRING"; assertThat(string).isNotSameAs(obj); assertThat(obj).isNotNull(); assertThat(obj).isNotEqualTo("DIFFERENT_OBJECT_TYPE"); assertThat(obj).isNotEqualTo(new ObjectIdentityImpl(DOMAIN_CLASS, 2L)); assertThat(obj).isNotEqualTo(new ObjectIdentityImpl( "org.springframework.security.acls.domain.ObjectIdentityImplTests$MockOtherIdDomainObject", 1L)); assertThat(new ObjectIdentityImpl(DOMAIN_CLASS, 1L)).isEqualTo(obj); assertThat(new ObjectIdentityImpl(mockObj)).isEqualTo(obj); } @Test public void hashcodeIsDifferentForDifferentJavaTypes() { ObjectIdentity obj = new ObjectIdentityImpl(Object.class, 1L); ObjectIdentity obj2 = new ObjectIdentityImpl(String.class, 1L); assertThat(obj.hashCode()).isNotEqualTo(obj2.hashCode()); } @Test public void longAndIntegerIdsWithSameValueAreEqualAndHaveSameHashcode() { ObjectIdentity obj = new ObjectIdentityImpl(Object.class, 5L); ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, 5); assertThat(obj2).isEqualTo(obj); assertThat(obj2.hashCode()).isEqualTo(obj.hashCode()); } @Test public void equalStringIdsAreEqualAndHaveSameHashcode() { ObjectIdentity obj = new ObjectIdentityImpl(Object.class, "1000"); ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, "1000"); assertThat(obj2).isEqualTo(obj); assertThat(obj2.hashCode()).isEqualTo(obj.hashCode()); } @Test public void stringAndNumericIdsAreNotEqual() { ObjectIdentity obj = new ObjectIdentityImpl(Object.class, "1000"); ObjectIdentity obj2 = new ObjectIdentityImpl(Object.class, 1000L); assertThat(obj).isNotEqualTo(obj2); } private class MockIdDomainObject { private Object id; public Object getId() { return this.id; } public void setId(Object id) { this.id = id; } } private class MockOtherIdDomainObject { private Object id; public Object getId() { return this.id; } public void setId(Object id) { this.id = id; } } }
5,431
34.045161
130
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/domain/SpecialPermission.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.springframework.security.acls.model.Permission; /** * A test permission. * * @author Ben Alex */ public class SpecialPermission extends BasePermission { public static final Permission ENTER = new SpecialPermission(1 << 5, 'E'); // 32 public static final Permission LEAVE = new SpecialPermission(1 << 6, 'L'); protected SpecialPermission(int mask, char code) { super(mask, code); } }
1,087
28.405405
81
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/domain/AclImplTests.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.security.acls.model.AccessControlEntry; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AlreadyExistsException; import org.springframework.security.acls.model.AuditableAccessControlEntry; import org.springframework.security.acls.model.AuditableAcl; import org.springframework.security.acls.model.ChildrenExistException; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.MutableAclService; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.PermissionGrantingStrategy; import org.springframework.security.acls.model.Sid; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.util.FieldUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.Mockito.mock; /** * Tests for {@link AclImpl}. * * @author Andrei Stefan */ public class AclImplTests { private static final String TARGET_CLASS = "org.springframework.security.acls.TargetObject"; private static final List<Permission> READ = Arrays.asList(BasePermission.READ); private static final List<Permission> WRITE = Arrays.asList(BasePermission.WRITE); private static final List<Permission> CREATE = Arrays.asList(BasePermission.CREATE); private static final List<Permission> DELETE = Arrays.asList(BasePermission.DELETE); private static final List<Sid> SCOTT = Arrays.asList((Sid) new PrincipalSid("scott")); private static final List<Sid> BEN = Arrays.asList((Sid) new PrincipalSid("ben")); Authentication auth = new TestingAuthenticationToken("joe", "ignored", "ROLE_ADMINISTRATOR"); AclAuthorizationStrategy authzStrategy; PermissionGrantingStrategy pgs; AuditLogger mockAuditLogger; ObjectIdentity objectIdentity = new ObjectIdentityImpl(TARGET_CLASS, 100); private DefaultPermissionFactory permissionFactory; @BeforeEach public void setUp() { SecurityContextHolder.getContext().setAuthentication(this.auth); this.authzStrategy = mock(AclAuthorizationStrategy.class); this.mockAuditLogger = mock(AuditLogger.class); this.pgs = new DefaultPermissionGrantingStrategy(this.mockAuditLogger); this.auth.setAuthenticated(true); this.permissionFactory = new DefaultPermissionFactory(); } @AfterEach public void tearDown() { SecurityContextHolder.clearContext(); } @Test public void constructorsRejectNullObjectIdentity() { assertThatIllegalArgumentException().isThrownBy( () -> new AclImpl(null, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe"))); assertThatIllegalArgumentException() .isThrownBy(() -> new AclImpl(null, 1, this.authzStrategy, this.mockAuditLogger)); } @Test public void constructorsRejectNullId() { assertThatIllegalArgumentException().isThrownBy(() -> new AclImpl(this.objectIdentity, null, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe"))); assertThatIllegalArgumentException() .isThrownBy(() -> new AclImpl(this.objectIdentity, null, this.authzStrategy, this.mockAuditLogger)); } @Test public void constructorsRejectNullAclAuthzStrategy() { assertThatIllegalArgumentException().isThrownBy(() -> new AclImpl(this.objectIdentity, 1, null, new DefaultPermissionGrantingStrategy(this.mockAuditLogger), null, null, true, new PrincipalSid("joe"))); assertThatIllegalArgumentException() .isThrownBy(() -> new AclImpl(this.objectIdentity, 1, null, this.mockAuditLogger)); } @Test public void insertAceRejectsNullParameters() { MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); assertThatIllegalArgumentException() .isThrownBy(() -> acl.insertAce(0, null, new GrantedAuthoritySid("ROLE_IGNORED"), true)); assertThatIllegalArgumentException().isThrownBy(() -> acl.insertAce(0, BasePermission.READ, null, true)); } @Test public void insertAceAddsElementAtCorrectIndex() { MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); MockAclService service = new MockAclService(); // Insert one permission acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true); service.updateAcl(acl); // Check it was successfully added assertThat(acl.getEntries()).hasSize(1); assertThat(acl).isEqualTo(acl.getEntries().get(0).getAcl()); assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(0).getPermission()); assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST1")); // Add a second permission acl.insertAce(1, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true); service.updateAcl(acl); // Check it was added on the last position assertThat(acl.getEntries()).hasSize(2); assertThat(acl).isEqualTo(acl.getEntries().get(1).getAcl()); assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(1).getPermission()); assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2")); // Add a third permission, after the first one acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_TEST3"), false); service.updateAcl(acl); assertThat(acl.getEntries()).hasSize(3); // Check the third entry was added between the two existent ones assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(0).getPermission()); assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST1")); assertThat(BasePermission.WRITE).isEqualTo(acl.getEntries().get(1).getPermission()); assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST3")); assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(2).getPermission()); assertThat(acl.getEntries().get(2).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2")); } @Test public void insertAceFailsForNonExistentElement() { MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); MockAclService service = new MockAclService(); // Insert one permission acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true); service.updateAcl(acl); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> acl.insertAce(55, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true)); } @Test public void deleteAceKeepsInitialOrdering() { MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); MockAclService service = new MockAclService(); // Add several permissions acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true); acl.insertAce(1, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true); acl.insertAce(2, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST3"), true); service.updateAcl(acl); // Delete first permission and check the order of the remaining permissions is // kept acl.deleteAce(0); assertThat(acl.getEntries()).hasSize(2); assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2")); assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST3")); // Add one more permission and remove the permission in the middle acl.insertAce(2, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST4"), true); service.updateAcl(acl); acl.deleteAce(1); assertThat(acl.getEntries()).hasSize(2); assertThat(acl.getEntries().get(0).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST2")); assertThat(acl.getEntries().get(1).getSid()).isEqualTo(new GrantedAuthoritySid("ROLE_TEST4")); // Remove remaining permissions acl.deleteAce(1); acl.deleteAce(0); assertThat(acl.getEntries()).isEmpty(); } @Test public void deleteAceFailsForNonExistentElement() { AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl( new SimpleGrantedAuthority("ROLE_OWNERSHIP"), new SimpleGrantedAuthority("ROLE_AUDITING"), new SimpleGrantedAuthority("ROLE_GENERAL")); MutableAcl acl = new AclImpl(this.objectIdentity, (1), strategy, this.pgs, null, null, true, new PrincipalSid("joe")); assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> acl.deleteAce(99)); } @Test public void isGrantingRejectsEmptyParameters() { MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); Sid ben = new PrincipalSid("ben"); assertThatIllegalArgumentException() .isThrownBy(() -> acl.isGranted(new ArrayList<>(0), Arrays.asList(ben), false)); assertThatIllegalArgumentException().isThrownBy(() -> acl.isGranted(READ, new ArrayList<>(0), false)); } @Test public void isGrantingGrantsAccessForAclWithNoParent() { Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_GENERAL", "ROLE_GUEST"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity rootOid = new ObjectIdentityImpl(TARGET_CLASS, 100); // Create an ACL which owner is not the authenticated principal MutableAcl rootAcl = new AclImpl(rootOid, 1, this.authzStrategy, this.pgs, null, null, false, new PrincipalSid("joe")); // Grant some permissions rootAcl.insertAce(0, BasePermission.READ, new PrincipalSid("ben"), false); rootAcl.insertAce(1, BasePermission.WRITE, new PrincipalSid("scott"), true); rootAcl.insertAce(2, BasePermission.WRITE, new PrincipalSid("rod"), false); rootAcl.insertAce(3, BasePermission.WRITE, new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), true); // Check permissions granting List<Permission> permissions = Arrays.asList(BasePermission.READ, BasePermission.CREATE); List<Sid> sids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_GUEST")); assertThat(rootAcl.isGranted(permissions, sids, false)).isFalse(); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> rootAcl.isGranted(permissions, SCOTT, false)); assertThat(rootAcl.isGranted(WRITE, SCOTT, false)).isTrue(); assertThat(rootAcl.isGranted(WRITE, Arrays.asList(new PrincipalSid("rod"), new GrantedAuthoritySid("WRITE_ACCESS_ROLE")), false)).isFalse(); assertThat(rootAcl.isGranted(WRITE, Arrays.asList(new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), new PrincipalSid("rod")), false)).isTrue(); // Change the type of the Sid and check the granting process assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> rootAcl.isGranted(WRITE, Arrays.asList(new GrantedAuthoritySid("rod"), new PrincipalSid("WRITE_ACCESS_ROLE")), false)); } @Test public void isGrantingGrantsAccessForInheritableAcls() { Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_GENERAL"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity grandParentOid = new ObjectIdentityImpl(TARGET_CLASS, 100); ObjectIdentity parentOid1 = new ObjectIdentityImpl(TARGET_CLASS, 101); ObjectIdentity parentOid2 = new ObjectIdentityImpl(TARGET_CLASS, 102); ObjectIdentity childOid1 = new ObjectIdentityImpl(TARGET_CLASS, 103); ObjectIdentity childOid2 = new ObjectIdentityImpl(TARGET_CLASS, 104); // Create ACLs PrincipalSid joe = new PrincipalSid("joe"); MutableAcl grandParentAcl = new AclImpl(grandParentOid, 1, this.authzStrategy, this.pgs, null, null, false, joe); MutableAcl parentAcl1 = new AclImpl(parentOid1, 2, this.authzStrategy, this.pgs, null, null, true, joe); MutableAcl parentAcl2 = new AclImpl(parentOid2, 3, this.authzStrategy, this.pgs, null, null, true, joe); MutableAcl childAcl1 = new AclImpl(childOid1, 4, this.authzStrategy, this.pgs, null, null, true, joe); MutableAcl childAcl2 = new AclImpl(childOid2, 4, this.authzStrategy, this.pgs, null, null, false, joe); // Create hierarchies childAcl2.setParent(childAcl1); childAcl1.setParent(parentAcl1); parentAcl2.setParent(grandParentAcl); parentAcl1.setParent(grandParentAcl); // Add some permissions grandParentAcl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true); grandParentAcl.insertAce(1, BasePermission.WRITE, new PrincipalSid("ben"), true); grandParentAcl.insertAce(2, BasePermission.DELETE, new PrincipalSid("ben"), false); grandParentAcl.insertAce(3, BasePermission.DELETE, new PrincipalSid("scott"), true); parentAcl1.insertAce(0, BasePermission.READ, new PrincipalSid("scott"), true); parentAcl1.insertAce(1, BasePermission.DELETE, new PrincipalSid("scott"), false); parentAcl2.insertAce(0, BasePermission.CREATE, new PrincipalSid("ben"), true); childAcl1.insertAce(0, BasePermission.CREATE, new PrincipalSid("scott"), true); // Check granting process for parent1 assertThat(parentAcl1.isGranted(READ, SCOTT, false)).isTrue(); assertThat(parentAcl1.isGranted(READ, Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_USER_READ")), false)) .isTrue(); assertThat(parentAcl1.isGranted(WRITE, BEN, false)).isTrue(); assertThat(parentAcl1.isGranted(DELETE, BEN, false)).isFalse(); assertThat(parentAcl1.isGranted(DELETE, SCOTT, false)).isFalse(); // Check granting process for parent2 assertThat(parentAcl2.isGranted(CREATE, BEN, false)).isTrue(); assertThat(parentAcl2.isGranted(WRITE, BEN, false)).isTrue(); assertThat(parentAcl2.isGranted(DELETE, BEN, false)).isFalse(); // Check granting process for child1 assertThat(childAcl1.isGranted(CREATE, SCOTT, false)).isTrue(); assertThat(childAcl1.isGranted(READ, Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_USER_READ")), false)) .isTrue(); assertThat(childAcl1.isGranted(DELETE, BEN, false)).isFalse(); // Check granting process for child2 (doesn't inherit the permissions from its // parent) assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> childAcl2.isGranted(CREATE, SCOTT, false)); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> childAcl2.isGranted(CREATE, Arrays.asList((Sid) new PrincipalSid("joe")), false)); } @Test public void updatedAceValuesAreCorrectlyReflectedInAcl() { Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_GENERAL"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, false, new PrincipalSid("joe")); MockAclService service = new MockAclService(); acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true); acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true); acl.insertAce(2, BasePermission.CREATE, new PrincipalSid("ben"), true); service.updateAcl(acl); assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(0).getPermission()); assertThat(BasePermission.WRITE).isEqualTo(acl.getEntries().get(1).getPermission()); assertThat(BasePermission.CREATE).isEqualTo(acl.getEntries().get(2).getPermission()); // Change each permission acl.updateAce(0, BasePermission.CREATE); acl.updateAce(1, BasePermission.DELETE); acl.updateAce(2, BasePermission.READ); // Check the change was successfully made assertThat(BasePermission.CREATE).isEqualTo(acl.getEntries().get(0).getPermission()); assertThat(BasePermission.DELETE).isEqualTo(acl.getEntries().get(1).getPermission()); assertThat(BasePermission.READ).isEqualTo(acl.getEntries().get(2).getPermission()); } @Test public void auditableEntryFlagsAreUpdatedCorrectly() { Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_AUDITING", "ROLE_GENERAL"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, false, new PrincipalSid("joe")); MockAclService service = new MockAclService(); acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true); acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true); service.updateAcl(acl); assertThat(((AuditableAccessControlEntry) acl.getEntries().get(0)).isAuditFailure()).isFalse(); assertThat(((AuditableAccessControlEntry) acl.getEntries().get(1)).isAuditFailure()).isFalse(); assertThat(((AuditableAccessControlEntry) acl.getEntries().get(0)).isAuditSuccess()).isFalse(); assertThat(((AuditableAccessControlEntry) acl.getEntries().get(1)).isAuditSuccess()).isFalse(); // Change each permission ((AuditableAcl) acl).updateAuditing(0, true, true); ((AuditableAcl) acl).updateAuditing(1, true, true); // Check the change was successfuly made assertThat(acl.getEntries()).extracting("auditSuccess").containsOnly(true, true); assertThat(acl.getEntries()).extracting("auditFailure").containsOnly(true, true); } @Test public void gettersAndSettersAreConsistent() { Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_GENERAL"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity identity = new ObjectIdentityImpl(TARGET_CLASS, (100)); ObjectIdentity identity2 = new ObjectIdentityImpl(TARGET_CLASS, (101)); MutableAcl acl = new AclImpl(identity, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); MutableAcl parentAcl = new AclImpl(identity2, 2, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); MockAclService service = new MockAclService(); acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true); acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true); service.updateAcl(acl); assertThat(1).isEqualTo(acl.getId()); assertThat(identity).isEqualTo(acl.getObjectIdentity()); assertThat(new PrincipalSid("joe")).isEqualTo(acl.getOwner()); assertThat(acl.getParentAcl()).isNull(); assertThat(acl.isEntriesInheriting()).isTrue(); assertThat(acl.getEntries()).hasSize(2); acl.setParent(parentAcl); assertThat(parentAcl).isEqualTo(acl.getParentAcl()); acl.setEntriesInheriting(false); assertThat(acl.isEntriesInheriting()).isFalse(); acl.setOwner(new PrincipalSid("ben")); assertThat(new PrincipalSid("ben")).isEqualTo(acl.getOwner()); } @Test public void isSidLoadedBehavesAsExpected() { List<Sid> loadedSids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_IGNORED")); MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, loadedSids, true, new PrincipalSid("joe")); assertThat(acl.isSidLoaded(loadedSids)).isTrue(); assertThat(acl.isSidLoaded(Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"), new PrincipalSid("ben")))) .isTrue(); assertThat(acl.isSidLoaded(Arrays.asList((Sid) new GrantedAuthoritySid("ROLE_IGNORED")))).isTrue(); assertThat(acl.isSidLoaded(BEN)).isTrue(); assertThat(acl.isSidLoaded(null)).isTrue(); assertThat(acl.isSidLoaded(new ArrayList<>(0))).isTrue(); assertThat(acl.isSidLoaded( Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_IGNORED")))) .isTrue(); assertThat(acl.isSidLoaded( Arrays.asList(new GrantedAuthoritySid("ROLE_GENERAL"), new GrantedAuthoritySid("ROLE_IGNORED")))) .isFalse(); assertThat(acl.isSidLoaded( Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_GENERAL")))) .isFalse(); } @Test public void insertAceRaisesNotFoundExceptionForIndexLessThanZero() { AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> acl.insertAce(-1, mock(Permission.class), mock(Sid.class), true)); } @Test public void deleteAceRaisesNotFoundExceptionForIndexLessThanZero() { AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> acl.deleteAce(-1)); } @Test public void insertAceRaisesNotFoundExceptionForIndexGreaterThanSize() { AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); // Insert at zero, OK. acl.insertAce(0, mock(Permission.class), mock(Sid.class), true); // Size is now 1 assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> acl.insertAce(2, mock(Permission.class), mock(Sid.class), true)); } // SEC-1151 @Test public void deleteAceRaisesNotFoundExceptionForIndexEqualToSize() { AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); acl.insertAce(0, mock(Permission.class), mock(Sid.class), true); // Size is now 1 assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> acl.deleteAce(1)); } // SEC-1795 @Test public void changingParentIsSuccessful() { AclImpl parentAcl = new AclImpl(this.objectIdentity, 1L, this.authzStrategy, this.mockAuditLogger); AclImpl childAcl = new AclImpl(this.objectIdentity, 2L, this.authzStrategy, this.mockAuditLogger); AclImpl changeParentAcl = new AclImpl(this.objectIdentity, 3L, this.authzStrategy, this.mockAuditLogger); childAcl.setParent(parentAcl); childAcl.setParent(changeParentAcl); } // SEC-2342 @Test public void maskPermissionGrantingStrategy() { DefaultPermissionGrantingStrategy maskPgs = new MaskPermissionGrantingStrategy(this.mockAuditLogger); MockAclService service = new MockAclService(); AclImpl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, maskPgs, null, null, true, new PrincipalSid("joe")); Permission permission = this.permissionFactory .buildFromMask(BasePermission.READ.getMask() | BasePermission.WRITE.getMask()); Sid sid = new PrincipalSid("ben"); acl.insertAce(0, permission, sid, true); service.updateAcl(acl); List<Permission> permissions = Arrays.asList(BasePermission.READ); List<Sid> sids = Arrays.asList(sid); assertThat(acl.isGranted(permissions, sids, false)).isTrue(); } @Test public void hashCodeWithoutStackOverFlow() throws Exception { Sid sid = new PrincipalSid("pSid"); ObjectIdentity oid = new ObjectIdentityImpl("type", 1); AclAuthorizationStrategy authStrategy = new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("role")); PermissionGrantingStrategy grantingStrategy = new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()); AclImpl acl = new AclImpl(oid, 1L, authStrategy, grantingStrategy, null, null, false, sid); AccessControlEntryImpl ace = new AccessControlEntryImpl(1L, acl, sid, BasePermission.READ, true, true, true); Field fieldAces = FieldUtils.getField(AclImpl.class, "aces"); fieldAces.setAccessible(true); List<AccessControlEntryImpl> aces = (List<AccessControlEntryImpl>) fieldAces.get(acl); aces.add(ace); ace.hashCode(); } private static class MaskPermissionGrantingStrategy extends DefaultPermissionGrantingStrategy { MaskPermissionGrantingStrategy(AuditLogger auditLogger) { super(auditLogger); } @Override protected boolean isGranted(AccessControlEntry ace, Permission p) { if (p.getMask() != 0) { return (p.getMask() & ace.getPermission().getMask()) != 0; } return super.isGranted(ace, p); } } private class MockAclService implements MutableAclService { @Override public MutableAcl createAcl(ObjectIdentity objectIdentity) throws AlreadyExistsException { return null; } @Override public void deleteAcl(ObjectIdentity objectIdentity, boolean deleteChildren) throws ChildrenExistException { } /* * Mock implementation that populates the aces list with fully initialized * AccessControlEntries * * @see org.springframework.security.acls.MutableAclService#updateAcl(org. * springframework .security.acls.MutableAcl) */ @Override @SuppressWarnings("unchecked") public MutableAcl updateAcl(MutableAcl acl) throws NotFoundException { List<AccessControlEntry> oldAces = acl.getEntries(); Field acesField = FieldUtils.getField(AclImpl.class, "aces"); acesField.setAccessible(true); List newAces; try { newAces = (List) acesField.get(acl); newAces.clear(); for (int i = 0; i < oldAces.size(); i++) { AccessControlEntry ac = oldAces.get(i); // Just give an ID to all this acl's aces, rest of the fields are just // copied newAces.add(new AccessControlEntryImpl((i + 1), ac.getAcl(), ac.getSid(), ac.getPermission(), ac.isGranting(), ((AuditableAccessControlEntry) ac).isAuditSuccess(), ((AuditableAccessControlEntry) ac).isAuditFailure())); } } catch (IllegalAccessException ex) { ex.printStackTrace(); } return acl; } @Override public List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity) { return null; } @Override public Acl readAclById(ObjectIdentity object) throws NotFoundException { return null; } @Override public Acl readAclById(ObjectIdentity object, List<Sid> sids) throws NotFoundException { return null; } @Override public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects) throws NotFoundException { return null; } @Override public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) throws NotFoundException { return null; } } }
27,275
45.946644
114
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/domain/AuditLoggerTests.java
/* * Copyright 2002-2017 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.security.acls.model.AccessControlEntry; import org.springframework.security.acls.model.AuditableAccessControlEntry; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Test class for {@link ConsoleAuditLogger}. * * @author Andrei Stefan */ public class AuditLoggerTests { private PrintStream console; private ByteArrayOutputStream bytes = new ByteArrayOutputStream(); private ConsoleAuditLogger logger; private AuditableAccessControlEntry ace; @BeforeEach public void setUp() { this.logger = new ConsoleAuditLogger(); this.ace = mock(AuditableAccessControlEntry.class); this.console = System.out; System.setOut(new PrintStream(this.bytes)); } @AfterEach public void tearDown() { System.setOut(this.console); this.bytes.reset(); } @Test public void nonAuditableAceIsIgnored() { AccessControlEntry ace = mock(AccessControlEntry.class); this.logger.logIfNeeded(true, ace); assertThat(this.bytes.size()).isZero(); } @Test public void successIsNotLoggedIfAceDoesntRequireSuccessAudit() { given(this.ace.isAuditSuccess()).willReturn(false); this.logger.logIfNeeded(true, this.ace); assertThat(this.bytes.size()).isZero(); } @Test public void successIsLoggedIfAceRequiresSuccessAudit() { given(this.ace.isAuditSuccess()).willReturn(true); this.logger.logIfNeeded(true, this.ace); assertThat(this.bytes.toString()).startsWith("GRANTED due to ACE"); } @Test public void failureIsntLoggedIfAceDoesntRequireFailureAudit() { given(this.ace.isAuditFailure()).willReturn(false); this.logger.logIfNeeded(false, this.ace); assertThat(this.bytes.size()).isZero(); } @Test public void failureIsLoggedIfAceRequiresFailureAudit() { given(this.ace.isAuditFailure()).willReturn(true); this.logger.logIfNeeded(false, this.ace); assertThat(this.bytes.toString()).startsWith("DENIED due to ACE"); } }
2,842
28.010204
75
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/domain/AccessControlImplEntryTests.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.junit.jupiter.api.Test; import org.springframework.security.acls.model.AccessControlEntry; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AuditableAccessControlEntry; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.Sid; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests for {@link AccessControlEntryImpl}. * * @author Andrei Stefan */ public class AccessControlImplEntryTests { @Test public void testConstructorRequiredFields() { // Check Acl field is present assertThatIllegalArgumentException().isThrownBy(() -> new AccessControlEntryImpl(null, null, new PrincipalSid("johndoe"), BasePermission.ADMINISTRATION, true, true, true)); // Check Sid field is present assertThatIllegalArgumentException().isThrownBy(() -> new AccessControlEntryImpl(null, mock(Acl.class), null, BasePermission.ADMINISTRATION, true, true, true)); // Check Permission field is present assertThatIllegalArgumentException().isThrownBy(() -> new AccessControlEntryImpl(null, mock(Acl.class), new PrincipalSid("johndoe"), null, true, true, true)); } @Test public void testAccessControlEntryImplGetters() { Acl mockAcl = mock(Acl.class); Sid sid = new PrincipalSid("johndoe"); // Create a sample entry AccessControlEntry ace = new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, true); // and check every get() method assertThat(ace.getId()).isEqualTo(1L); assertThat(ace.getAcl()).isEqualTo(mockAcl); assertThat(ace.getSid()).isEqualTo(sid); assertThat(ace.isGranting()).isTrue(); assertThat(ace.getPermission()).isEqualTo(BasePermission.ADMINISTRATION); assertThat(((AuditableAccessControlEntry) ace).isAuditFailure()).isTrue(); assertThat(((AuditableAccessControlEntry) ace).isAuditSuccess()).isTrue(); } @Test public void testEquals() { final Acl mockAcl = mock(Acl.class); final ObjectIdentity oid = mock(ObjectIdentity.class); given(mockAcl.getObjectIdentity()).willReturn(oid); Sid sid = new PrincipalSid("johndoe"); AccessControlEntry ace = new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, true); assertThat(ace).isNotNull(); assertThat(ace).isNotEqualTo(100L); assertThat(ace).isEqualTo(ace); assertThat(ace).isEqualTo( new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, true)); assertThat(ace).isNotEqualTo( new AccessControlEntryImpl(2L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, true)); assertThat(ace).isNotEqualTo(new AccessControlEntryImpl(1L, mockAcl, new PrincipalSid("scott"), BasePermission.ADMINISTRATION, true, true, true)); assertThat(ace) .isNotEqualTo(new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.WRITE, true, true, true)); assertThat(ace).isNotEqualTo( new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, false, true, true)); assertThat(ace).isNotEqualTo( new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, false, true)); assertThat(ace).isNotEqualTo( new AccessControlEntryImpl(1L, mockAcl, sid, BasePermission.ADMINISTRATION, true, true, false)); } }
4,165
41.948454
114
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/domain/PermissionTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.security.acls.model.Permission; import static org.assertj.core.api.Assertions.assertThat; /** * Tests classes associated with Permission. * * @author Ben Alex */ public class PermissionTests { private DefaultPermissionFactory permissionFactory; @BeforeEach public void createPermissionfactory() { this.permissionFactory = new DefaultPermissionFactory(); } @Test public void basePermissionTest() { Permission p = this.permissionFactory.buildFromName("WRITE"); assertThat(p).isNotNull(); } @Test public void expectedIntegerValues() { assertThat(BasePermission.READ.getMask()).isEqualTo(1); assertThat(BasePermission.ADMINISTRATION.getMask()).isEqualTo(16); assertThat(new CumulativePermission().set(BasePermission.READ).set(BasePermission.WRITE) .set(BasePermission.CREATE).getMask()).isEqualTo(7); assertThat(new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION).getMask()) .isEqualTo(17); } @Test public void fromInteger() { Permission permission = this.permissionFactory.buildFromMask(7); permission = this.permissionFactory.buildFromMask(4); } @Test public void stringConversion() { this.permissionFactory.registerPublicPermissions(SpecialPermission.class); assertThat(BasePermission.READ.toString()).isEqualTo("BasePermission[...............................R=1]"); assertThat(BasePermission.ADMINISTRATION.toString()) .isEqualTo("BasePermission[...........................A....=16]"); assertThat(new CumulativePermission().set(BasePermission.READ).toString()) .isEqualTo("CumulativePermission[...............................R=1]"); assertThat( new CumulativePermission().set(SpecialPermission.ENTER).set(BasePermission.ADMINISTRATION).toString()) .isEqualTo("CumulativePermission[..........................EA....=48]"); assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ).toString()) .isEqualTo("CumulativePermission[...........................A...R=17]"); assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ) .clear(BasePermission.ADMINISTRATION).toString()) .isEqualTo("CumulativePermission[...............................R=1]"); assertThat(new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ) .clear(BasePermission.ADMINISTRATION).clear(BasePermission.READ).toString()) .isEqualTo("CumulativePermission[................................=0]"); } }
3,305
38.357143
111
java
null
spring-security-main/acl/src/test/java/org/springframework/security/acls/domain/ObjectIdentityRetrievalStrategyImplTests.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.junit.jupiter.api.Test; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ObjectIdentityRetrievalStrategyImpl} * * @author Andrei Stefan */ public class ObjectIdentityRetrievalStrategyImplTests { @Test public void testObjectIdentityCreation() { MockIdDomainObject domain = new MockIdDomainObject(); domain.setId(1); ObjectIdentityRetrievalStrategy retStrategy = new ObjectIdentityRetrievalStrategyImpl(); ObjectIdentity identity = retStrategy.getObjectIdentity(domain); assertThat(identity).isNotNull(); assertThat(new ObjectIdentityImpl(domain)).isEqualTo(identity); } @SuppressWarnings("unused") private class MockIdDomainObject { private Object id; public Object getId() { return this.id; } public void setId(Object id) { this.id = id; } } }
1,652
27.016949
90
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/package-info.java
/* * Copyright 2002-2016 the original author or 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 * * https://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. */ /** * The Spring Security ACL package which implements instance-based security for domain * objects. * <p> * Consider using the annotation based approach ({@code @PreAuthorize}, * {@code @PostFilter} annotations) combined with a * {@link org.springframework.security.acls.AclPermissionEvaluator} in preference to the * older and more verbose attribute/voter/after-invocation approach from versions before * Spring Security 3.0. */ package org.springframework.security.acls;
1,106
38.535714
88
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/AclEntryVoter.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.access.AuthorizationServiceException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.vote.AbstractAclVoter; import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl; import org.springframework.security.acls.domain.SidRetrievalStrategyImpl; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.Sid; import org.springframework.security.acls.model.SidRetrievalStrategy; import org.springframework.security.core.Authentication; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * <p> * Given a domain object instance passed as a method argument, ensures the principal has * appropriate permission as indicated by the {@link AclService}. * <p> * The <tt>AclService</tt> is used to retrieve the access control list (ACL) permissions * associated with a domain object instance for the current <tt>Authentication</tt> * object. * <p> * The voter will vote if any {@link ConfigAttribute#getAttribute()} matches the * {@link #processConfigAttribute}. The provider will then locate the first method * argument of type {@link #processDomainObjectClass}. Assuming that method argument is * non-null, the provider will then lookup the ACLs from the <code>AclManager</code> and * ensure the principal is {@link Acl#isGranted(List, List, boolean)} when presenting the * {@link #requirePermission} array to that method. * <p> * If the method argument is <tt>null</tt>, the voter will abstain from voting. If the * method argument could not be found, an {@link AuthorizationServiceException} will be * thrown. * <p> * In practical terms users will typically setup a number of <tt>AclEntryVoter</tt>s. Each * will have a different {@link #setProcessDomainObjectClass processDomainObjectClass}, * {@link #processConfigAttribute} and {@link #requirePermission} combination. For * example, a small application might employ the following instances of * <tt>AclEntryVoter</tt>: * <ul> * <li>Process domain object class <code>BankAccount</code>, configuration attribute * <code>VOTE_ACL_BANK_ACCONT_READ</code>, require permission * <code>BasePermission.READ</code></li> * <li>Process domain object class <code>BankAccount</code>, configuration attribute * <code>VOTE_ACL_BANK_ACCOUNT_WRITE</code>, require permission list * <code>BasePermission.WRITE</code> and <code>BasePermission.CREATE</code> (allowing the * principal to have <b>either</b> of these two permissions)</li> * <li>Process domain object class <code>Customer</code>, configuration attribute * <code>VOTE_ACL_CUSTOMER_READ</code>, require permission * <code>BasePermission.READ</code></li> * <li>Process domain object class <code>Customer</code>, configuration attribute * <code>VOTE_ACL_CUSTOMER_WRITE</code>, require permission list * <code>BasePermission.WRITE</code> and <code>BasePermission.CREATE</code></li> * </ul> * Alternatively, you could have used a common superclass or interface for the * {@link #processDomainObjectClass} if both <code>BankAccount</code> and * <code>Customer</code> had common parents. * * <p> * If the principal does not have sufficient permissions, the voter will vote to deny * access. * * <p> * All comparisons and prefixes are case sensitive. * * @author Ben Alex */ public class AclEntryVoter extends AbstractAclVoter { private static final Log logger = LogFactory.getLog(AclEntryVoter.class); private final AclService aclService; private final String processConfigAttribute; private final List<Permission> requirePermission; private ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy = new ObjectIdentityRetrievalStrategyImpl(); private SidRetrievalStrategy sidRetrievalStrategy = new SidRetrievalStrategyImpl(); private String internalMethod; public AclEntryVoter(AclService aclService, String processConfigAttribute, Permission[] requirePermission) { Assert.notNull(processConfigAttribute, "A processConfigAttribute is mandatory"); Assert.notNull(aclService, "An AclService is mandatory"); Assert.isTrue(!ObjectUtils.isEmpty(requirePermission), "One or more requirePermission entries is mandatory"); this.aclService = aclService; this.processConfigAttribute = processConfigAttribute; this.requirePermission = Arrays.asList(requirePermission); } /** * Optionally specifies a method of the domain object that will be used to obtain a * contained domain object. That contained domain object will be used for the ACL * evaluation. This is useful if a domain object contains a parent that an ACL * evaluation should be targeted for, instead of the child domain object (which * perhaps is being created and as such does not yet have any ACL permissions) * @return <code>null</code> to use the domain object, or the name of a method (that * requires no arguments) that should be invoked to obtain an <code>Object</code> * which will be the domain object used for ACL evaluation */ protected String getInternalMethod() { return this.internalMethod; } public void setInternalMethod(String internalMethod) { this.internalMethod = internalMethod; } protected String getProcessConfigAttribute() { return this.processConfigAttribute; } public void setObjectIdentityRetrievalStrategy(ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy) { Assert.notNull(objectIdentityRetrievalStrategy, "ObjectIdentityRetrievalStrategy required"); this.objectIdentityRetrievalStrategy = objectIdentityRetrievalStrategy; } public void setSidRetrievalStrategy(SidRetrievalStrategy sidRetrievalStrategy) { Assert.notNull(sidRetrievalStrategy, "SidRetrievalStrategy required"); this.sidRetrievalStrategy = sidRetrievalStrategy; } @Override public boolean supports(ConfigAttribute attribute) { return (attribute.getAttribute() != null) && attribute.getAttribute().equals(getProcessConfigAttribute()); } @Override public int vote(Authentication authentication, MethodInvocation object, Collection<ConfigAttribute> attributes) { for (ConfigAttribute attr : attributes) { if (!supports(attr)) { continue; } // Need to make an access decision on this invocation // Attempt to locate the domain object instance to process Object domainObject = getDomainObjectInstance(object); // If domain object is null, vote to abstain if (domainObject == null) { logger.debug("Voting to abstain - domainObject is null"); return ACCESS_ABSTAIN; } // Evaluate if we are required to use an inner domain object if (StringUtils.hasText(this.internalMethod)) { domainObject = invokeInternalMethod(domainObject); } // Obtain the OID applicable to the domain object ObjectIdentity objectIdentity = this.objectIdentityRetrievalStrategy.getObjectIdentity(domainObject); // Obtain the SIDs applicable to the principal List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication); Acl acl; try { // Lookup only ACLs for SIDs we're interested in acl = this.aclService.readAclById(objectIdentity, sids); } catch (NotFoundException ex) { logger.debug("Voting to deny access - no ACLs apply for this principal"); return ACCESS_DENIED; } try { if (acl.isGranted(this.requirePermission, sids, false)) { logger.debug("Voting to grant access"); return ACCESS_GRANTED; } logger.debug("Voting to deny access - ACLs returned, but insufficient permissions for this principal"); return ACCESS_DENIED; } catch (NotFoundException ex) { logger.debug("Voting to deny access - no ACLs apply for this principal"); return ACCESS_DENIED; } } // No configuration attribute matched, so abstain return ACCESS_ABSTAIN; } private Object invokeInternalMethod(Object domainObject) { try { Class<?> domainObjectType = domainObject.getClass(); Method method = domainObjectType.getMethod(this.internalMethod, new Class[0]); return method.invoke(domainObject); } catch (NoSuchMethodException ex) { throw new AuthorizationServiceException("Object of class '" + domainObject.getClass() + "' does not provide the requested internalMethod: " + this.internalMethod); } catch (IllegalAccessException ex) { logger.debug("IllegalAccessException", ex); throw new AuthorizationServiceException( "Problem invoking internalMethod: " + this.internalMethod + " for object: " + domainObject); } catch (InvocationTargetException ex) { logger.debug("InvocationTargetException", ex); throw new AuthorizationServiceException( "Problem invoking internalMethod: " + this.internalMethod + " for object: " + domainObject); } } }
10,123
40.834711
117
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/AclPermissionCacheOptimizer.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.access.PermissionCacheOptimizer; import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl; import org.springframework.security.acls.domain.SidRetrievalStrategyImpl; import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy; import org.springframework.security.acls.model.Sid; import org.springframework.security.acls.model.SidRetrievalStrategy; import org.springframework.security.core.Authentication; /** * Batch loads ACLs for collections of objects to allow optimised filtering. * * @author Luke Taylor * @since 3.1 */ public class AclPermissionCacheOptimizer implements PermissionCacheOptimizer { private final Log logger = LogFactory.getLog(getClass()); private final AclService aclService; private SidRetrievalStrategy sidRetrievalStrategy = new SidRetrievalStrategyImpl(); private ObjectIdentityRetrievalStrategy oidRetrievalStrategy = new ObjectIdentityRetrievalStrategyImpl(); public AclPermissionCacheOptimizer(AclService aclService) { this.aclService = aclService; } @Override public void cachePermissionsFor(Authentication authentication, Collection<?> objects) { if (objects.isEmpty()) { return; } List<ObjectIdentity> oidsToCache = new ArrayList<>(objects.size()); for (Object domainObject : objects) { if (domainObject != null) { ObjectIdentity oid = this.oidRetrievalStrategy.getObjectIdentity(domainObject); oidsToCache.add(oid); } } List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication); this.logger.debug(LogMessage.of(() -> "Eagerly loading Acls for " + oidsToCache.size() + " objects")); this.aclService.readAclsById(oidsToCache, sids); } public void setObjectIdentityRetrievalStrategy(ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy) { this.oidRetrievalStrategy = objectIdentityRetrievalStrategy; } public void setSidRetrievalStrategy(SidRetrievalStrategy sidRetrievalStrategy) { this.sidRetrievalStrategy = sidRetrievalStrategy; } }
3,040
35.638554
114
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/AclPermissionEvaluator.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls; import java.io.Serializable; import java.util.Arrays; import java.util.List; import java.util.Locale; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.access.PermissionEvaluator; import org.springframework.security.acls.domain.DefaultPermissionFactory; import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl; import org.springframework.security.acls.domain.PermissionFactory; import org.springframework.security.acls.domain.SidRetrievalStrategyImpl; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentityGenerator; import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.Sid; import org.springframework.security.acls.model.SidRetrievalStrategy; import org.springframework.security.core.Authentication; /** * Used by Spring Security's expression-based access control implementation to evaluate * permissions for a particular object using the ACL module. Similar in behaviour to * {@link org.springframework.security.acls.AclEntryVoter AclEntryVoter}. * * @author Luke Taylor * @since 3.0 */ public class AclPermissionEvaluator implements PermissionEvaluator { private final Log logger = LogFactory.getLog(getClass()); private final AclService aclService; private ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy = new ObjectIdentityRetrievalStrategyImpl(); private ObjectIdentityGenerator objectIdentityGenerator = new ObjectIdentityRetrievalStrategyImpl(); private SidRetrievalStrategy sidRetrievalStrategy = new SidRetrievalStrategyImpl(); private PermissionFactory permissionFactory = new DefaultPermissionFactory(); public AclPermissionEvaluator(AclService aclService) { this.aclService = aclService; } /** * Determines whether the user has the given permission(s) on the domain object using * the ACL configuration. If the domain object is null, returns false (this can always * be overridden using a null check in the expression itself). */ @Override public boolean hasPermission(Authentication authentication, Object domainObject, Object permission) { if (domainObject == null) { return false; } ObjectIdentity objectIdentity = this.objectIdentityRetrievalStrategy.getObjectIdentity(domainObject); return checkPermission(authentication, objectIdentity, permission); } @Override public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) { ObjectIdentity objectIdentity = this.objectIdentityGenerator.createObjectIdentity(targetId, targetType); return checkPermission(authentication, objectIdentity, permission); } private boolean checkPermission(Authentication authentication, ObjectIdentity oid, Object permission) { // Obtain the SIDs applicable to the principal List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication); List<Permission> requiredPermission = resolvePermission(permission); this.logger.debug(LogMessage.of(() -> "Checking permission '" + permission + "' for object '" + oid + "'")); try { // Lookup only ACLs for SIDs we're interested in Acl acl = this.aclService.readAclById(oid, sids); if (acl.isGranted(requiredPermission, sids, false)) { this.logger.debug("Access is granted"); return true; } this.logger.debug("Returning false - ACLs returned, but insufficient permissions for this principal"); } catch (NotFoundException nfe) { this.logger.debug("Returning false - no ACLs apply for this principal"); } return false; } List<Permission> resolvePermission(Object permission) { if (permission instanceof Integer) { return Arrays.asList(this.permissionFactory.buildFromMask((Integer) permission)); } if (permission instanceof Permission) { return Arrays.asList((Permission) permission); } if (permission instanceof Permission[]) { return Arrays.asList((Permission[]) permission); } if (permission instanceof String permString) { Permission p = buildPermission(permString); if (p != null) { return Arrays.asList(p); } } throw new IllegalArgumentException("Unsupported permission: " + permission); } private Permission buildPermission(String permString) { try { return this.permissionFactory.buildFromName(permString); } catch (IllegalArgumentException notfound) { return this.permissionFactory.buildFromName(permString.toUpperCase(Locale.ENGLISH)); } } public void setObjectIdentityRetrievalStrategy(ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy) { this.objectIdentityRetrievalStrategy = objectIdentityRetrievalStrategy; } public void setObjectIdentityGenerator(ObjectIdentityGenerator objectIdentityGenerator) { this.objectIdentityGenerator = objectIdentityGenerator; } public void setSidRetrievalStrategy(SidRetrievalStrategy sidRetrievalStrategy) { this.sidRetrievalStrategy = sidRetrievalStrategy; } public void setPermissionFactory(PermissionFactory permissionFactory) { this.permissionFactory = permissionFactory; } }
6,137
38.346154
117
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcMutableAclService.java
/* * Copyright 2004, 2005, 2006, 2017, 2018 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import javax.sql.DataSource; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.security.acls.domain.AccessControlEntryImpl; import org.springframework.security.acls.domain.GrantedAuthoritySid; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.AccessControlEntry; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AclCache; import org.springframework.security.acls.model.AlreadyExistsException; import org.springframework.security.acls.model.ChildrenExistException; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.MutableAclService; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.Sid; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.Assert; /** * Provides a base JDBC implementation of {@link MutableAclService}. * <p> * The default settings are for HSQLDB. If you are using a different database you will * probably need to set the {@link #setSidIdentityQuery(String) sidIdentityQuery} and * {@link #setClassIdentityQuery(String) classIdentityQuery} properties appropriately. The * other queries, SQL inserts and updates can also be customized to accomodate schema * variations, but must produce results consistent with those expected by the defaults. * <p> * See the appendix of the Spring Security reference manual for more information on the * expected schema and how it is used. Information on using PostgreSQL is also included. * * @author Ben Alex * @author Johannes Zlattinger */ public class JdbcMutableAclService extends JdbcAclService implements MutableAclService { private static final String DEFAULT_INSERT_INTO_ACL_CLASS = "insert into acl_class (class) values (?)"; private static final String DEFAULT_INSERT_INTO_ACL_CLASS_WITH_ID = "insert into acl_class (class, class_id_type) values (?, ?)"; private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); private boolean foreignKeysInDatabase = true; private final AclCache aclCache; private String deleteEntryByObjectIdentityForeignKey = "delete from acl_entry where acl_object_identity=?"; private String deleteObjectIdentityByPrimaryKey = "delete from acl_object_identity where id=?"; private String classIdentityQuery = "call identity()"; private String sidIdentityQuery = "call identity()"; private String insertClass = DEFAULT_INSERT_INTO_ACL_CLASS; private String insertEntry = "insert into acl_entry " + "(acl_object_identity, ace_order, sid, mask, granting, audit_success, audit_failure)" + "values (?, ?, ?, ?, ?, ?, ?)"; private String insertObjectIdentity = "insert into acl_object_identity " + "(object_id_class, object_id_identity, owner_sid, entries_inheriting) " + "values (?, ?, ?, ?)"; private String insertSid = "insert into acl_sid (principal, sid) values (?, ?)"; private String selectClassPrimaryKey = "select id from acl_class where class=?"; private String selectObjectIdentityPrimaryKey = "select acl_object_identity.id from acl_object_identity, acl_class " + "where acl_object_identity.object_id_class = acl_class.id and acl_class.class=? " + "and acl_object_identity.object_id_identity = ?"; private String selectSidPrimaryKey = "select id from acl_sid where principal=? and sid=?"; private String updateObjectIdentity = "update acl_object_identity set " + "parent_object = ?, owner_sid = ?, entries_inheriting = ?" + " where id = ?"; public JdbcMutableAclService(DataSource dataSource, LookupStrategy lookupStrategy, AclCache aclCache) { super(dataSource, lookupStrategy); Assert.notNull(aclCache, "AclCache required"); this.aclCache = aclCache; } @Override public MutableAcl createAcl(ObjectIdentity objectIdentity) throws AlreadyExistsException { Assert.notNull(objectIdentity, "Object Identity required"); // Check this object identity hasn't already been persisted if (retrieveObjectIdentityPrimaryKey(objectIdentity) != null) { throw new AlreadyExistsException("Object identity '" + objectIdentity + "' already exists"); } // Need to retrieve the current principal, in order to know who "owns" this ACL // (can be changed later on) Authentication auth = this.securityContextHolderStrategy.getContext().getAuthentication(); PrincipalSid sid = new PrincipalSid(auth); // Create the acl_object_identity row createObjectIdentity(objectIdentity, sid); // Retrieve the ACL via superclass (ensures cache registration, proper retrieval // etc) Acl acl = readAclById(objectIdentity); Assert.isInstanceOf(MutableAcl.class, acl, "MutableAcl should be been returned"); return (MutableAcl) acl; } /** * Creates a new row in acl_entry for every ACE defined in the passed MutableAcl * object. * @param acl containing the ACEs to insert */ protected void createEntries(final MutableAcl acl) { if (acl.getEntries().isEmpty()) { return; } this.jdbcOperations.batchUpdate(this.insertEntry, new BatchPreparedStatementSetter() { @Override public int getBatchSize() { return acl.getEntries().size(); } @Override public void setValues(PreparedStatement stmt, int i) throws SQLException { AccessControlEntry entry_ = acl.getEntries().get(i); Assert.isTrue(entry_ instanceof AccessControlEntryImpl, "Unknown ACE class"); AccessControlEntryImpl entry = (AccessControlEntryImpl) entry_; stmt.setLong(1, (Long) acl.getId()); stmt.setInt(2, i); stmt.setLong(3, createOrRetrieveSidPrimaryKey(entry.getSid(), true)); stmt.setInt(4, entry.getPermission().getMask()); stmt.setBoolean(5, entry.isGranting()); stmt.setBoolean(6, entry.isAuditSuccess()); stmt.setBoolean(7, entry.isAuditFailure()); } }); } /** * Creates an entry in the acl_object_identity table for the passed ObjectIdentity. * The Sid is also necessary, as acl_object_identity has defined the sid column as * non-null. * @param object to represent an acl_object_identity for * @param owner for the SID column (will be created if there is no acl_sid entry for * this particular Sid already) */ protected void createObjectIdentity(ObjectIdentity object, Sid owner) { Long sidId = createOrRetrieveSidPrimaryKey(owner, true); Long classId = createOrRetrieveClassPrimaryKey(object.getType(), true, object.getIdentifier().getClass()); this.jdbcOperations.update(this.insertObjectIdentity, classId, object.getIdentifier().toString(), sidId, Boolean.TRUE); } /** * Retrieves the primary key from {@code acl_class}, creating a new row if needed and * the {@code allowCreate} property is {@code true}. * @param type to find or create an entry for (often the fully-qualified class name) * @param allowCreate true if creation is permitted if not found * @return the primary key or null if not found */ protected Long createOrRetrieveClassPrimaryKey(String type, boolean allowCreate, Class idType) { List<Long> classIds = this.jdbcOperations.queryForList(this.selectClassPrimaryKey, new Object[] { type }, Long.class); if (!classIds.isEmpty()) { return classIds.get(0); } if (allowCreate) { if (!isAclClassIdSupported()) { this.jdbcOperations.update(this.insertClass, type); } else { this.jdbcOperations.update(this.insertClass, type, idType.getCanonicalName()); } Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(), "Transaction must be running"); return this.jdbcOperations.queryForObject(this.classIdentityQuery, Long.class); } return null; } /** * Retrieves the primary key from acl_sid, creating a new row if needed and the * allowCreate property is true. * @param sid to find or create * @param allowCreate true if creation is permitted if not found * @return the primary key or null if not found * @throws IllegalArgumentException if the <tt>Sid</tt> is not a recognized * implementation. */ protected Long createOrRetrieveSidPrimaryKey(Sid sid, boolean allowCreate) { Assert.notNull(sid, "Sid required"); if (sid instanceof PrincipalSid) { String sidName = ((PrincipalSid) sid).getPrincipal(); return createOrRetrieveSidPrimaryKey(sidName, true, allowCreate); } if (sid instanceof GrantedAuthoritySid) { String sidName = ((GrantedAuthoritySid) sid).getGrantedAuthority(); return createOrRetrieveSidPrimaryKey(sidName, false, allowCreate); } throw new IllegalArgumentException("Unsupported implementation of Sid"); } /** * Retrieves the primary key from acl_sid, creating a new row if needed and the * allowCreate property is true. * @param sidName name of Sid to find or to create * @param sidIsPrincipal whether it's a user or granted authority like role * @param allowCreate true if creation is permitted if not found * @return the primary key or null if not found */ protected Long createOrRetrieveSidPrimaryKey(String sidName, boolean sidIsPrincipal, boolean allowCreate) { List<Long> sidIds = this.jdbcOperations.queryForList(this.selectSidPrimaryKey, new Object[] { sidIsPrincipal, sidName }, Long.class); if (!sidIds.isEmpty()) { return sidIds.get(0); } if (allowCreate) { this.jdbcOperations.update(this.insertSid, sidIsPrincipal, sidName); Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(), "Transaction must be running"); return this.jdbcOperations.queryForObject(this.sidIdentityQuery, Long.class); } return null; } @Override public void deleteAcl(ObjectIdentity objectIdentity, boolean deleteChildren) throws ChildrenExistException { Assert.notNull(objectIdentity, "Object Identity required"); Assert.notNull(objectIdentity.getIdentifier(), "Object Identity doesn't provide an identifier"); if (deleteChildren) { List<ObjectIdentity> children = findChildren(objectIdentity); if (children != null) { for (ObjectIdentity child : children) { deleteAcl(child, true); } } } else { if (!this.foreignKeysInDatabase) { // We need to perform a manual verification for what a FK would normally // do. We generally don't do this, in the interests of deadlock management List<ObjectIdentity> children = findChildren(objectIdentity); if (children != null) { throw new ChildrenExistException( "Cannot delete '" + objectIdentity + "' (has " + children.size() + " children)"); } } } Long oidPrimaryKey = retrieveObjectIdentityPrimaryKey(objectIdentity); // Delete this ACL's ACEs in the acl_entry table deleteEntries(oidPrimaryKey); // Delete this ACL's acl_object_identity row deleteObjectIdentity(oidPrimaryKey); // Clear the cache this.aclCache.evictFromCache(objectIdentity); } /** * Deletes all ACEs defined in the acl_entry table belonging to the presented * ObjectIdentity primary key. * @param oidPrimaryKey the rows in acl_entry to delete */ protected void deleteEntries(Long oidPrimaryKey) { this.jdbcOperations.update(this.deleteEntryByObjectIdentityForeignKey, oidPrimaryKey); } /** * Deletes a single row from acl_object_identity that is associated with the presented * ObjectIdentity primary key. * <p> * We do not delete any entries from acl_class, even if no classes are using that * class any longer. This is a deadlock avoidance approach. * @param oidPrimaryKey to delete the acl_object_identity */ protected void deleteObjectIdentity(Long oidPrimaryKey) { // Delete the acl_object_identity row this.jdbcOperations.update(this.deleteObjectIdentityByPrimaryKey, oidPrimaryKey); } /** * Retrieves the primary key from the acl_object_identity table for the passed * ObjectIdentity. Unlike some other methods in this implementation, this method will * NOT create a row (use {@link #createObjectIdentity(ObjectIdentity, Sid)} instead). * @param oid to find * @return the object identity or null if not found */ protected Long retrieveObjectIdentityPrimaryKey(ObjectIdentity oid) { try { return this.jdbcOperations.queryForObject(this.selectObjectIdentityPrimaryKey, Long.class, oid.getType(), oid.getIdentifier().toString()); } catch (DataAccessException notFound) { return null; } } /** * This implementation will simply delete all ACEs in the database and recreate them * on each invocation of this method. A more comprehensive implementation might use * dirty state checking, or more likely use ORM capabilities for create, update and * delete operations of {@link MutableAcl}. */ @Override public MutableAcl updateAcl(MutableAcl acl) throws NotFoundException { Assert.notNull(acl.getId(), "Object Identity doesn't provide an identifier"); // Delete this ACL's ACEs in the acl_entry table deleteEntries(retrieveObjectIdentityPrimaryKey(acl.getObjectIdentity())); // Create this ACL's ACEs in the acl_entry table createEntries(acl); // Change the mutable columns in acl_object_identity updateObjectIdentity(acl); // Clear the cache, including children clearCacheIncludingChildren(acl.getObjectIdentity()); // Retrieve the ACL via superclass (ensures cache registration, proper retrieval // etc) return (MutableAcl) super.readAclById(acl.getObjectIdentity()); } private void clearCacheIncludingChildren(ObjectIdentity objectIdentity) { Assert.notNull(objectIdentity, "ObjectIdentity required"); List<ObjectIdentity> children = findChildren(objectIdentity); if (children != null) { for (ObjectIdentity child : children) { clearCacheIncludingChildren(child); } } this.aclCache.evictFromCache(objectIdentity); } /** * Updates an existing acl_object_identity row, with new information presented in the * passed MutableAcl object. Also will create an acl_sid entry if needed for the Sid * that owns the MutableAcl. * @param acl to modify (a row must already exist in acl_object_identity) * @throws NotFoundException if the ACL could not be found to update. */ protected void updateObjectIdentity(MutableAcl acl) { Long parentId = null; if (acl.getParentAcl() != null) { Assert.isInstanceOf(ObjectIdentityImpl.class, acl.getParentAcl().getObjectIdentity(), "Implementation only supports ObjectIdentityImpl"); ObjectIdentityImpl oii = (ObjectIdentityImpl) acl.getParentAcl().getObjectIdentity(); parentId = retrieveObjectIdentityPrimaryKey(oii); } Assert.notNull(acl.getOwner(), "Owner is required in this implementation"); Long ownerSid = createOrRetrieveSidPrimaryKey(acl.getOwner(), true); int count = this.jdbcOperations.update(this.updateObjectIdentity, parentId, ownerSid, acl.isEntriesInheriting(), acl.getId()); if (count != 1) { throw new NotFoundException("Unable to locate ACL to update"); } } /** * Sets the query that will be used to retrieve the identity of a newly created row in * the <tt>acl_class</tt> table. * @param classIdentityQuery the query, which should return the identifier. Defaults * to <tt>call identity()</tt> */ public void setClassIdentityQuery(String classIdentityQuery) { Assert.hasText(classIdentityQuery, "New classIdentityQuery query is required"); this.classIdentityQuery = classIdentityQuery; } /** * Sets the query that will be used to retrieve the identity of a newly created row in * the <tt>acl_sid</tt> table. * @param sidIdentityQuery the query, which should return the identifier. Defaults to * <tt>call identity()</tt> */ public void setSidIdentityQuery(String sidIdentityQuery) { Assert.hasText(sidIdentityQuery, "New sidIdentityQuery query is required"); this.sidIdentityQuery = sidIdentityQuery; } public void setDeleteEntryByObjectIdentityForeignKeySql(String deleteEntryByObjectIdentityForeignKey) { this.deleteEntryByObjectIdentityForeignKey = deleteEntryByObjectIdentityForeignKey; } public void setDeleteObjectIdentityByPrimaryKeySql(String deleteObjectIdentityByPrimaryKey) { this.deleteObjectIdentityByPrimaryKey = deleteObjectIdentityByPrimaryKey; } public void setInsertClassSql(String insertClass) { this.insertClass = insertClass; } public void setInsertEntrySql(String insertEntry) { this.insertEntry = insertEntry; } public void setInsertObjectIdentitySql(String insertObjectIdentity) { this.insertObjectIdentity = insertObjectIdentity; } public void setInsertSidSql(String insertSid) { this.insertSid = insertSid; } public void setClassPrimaryKeyQuery(String selectClassPrimaryKey) { this.selectClassPrimaryKey = selectClassPrimaryKey; } public void setObjectIdentityPrimaryKeyQuery(String selectObjectIdentityPrimaryKey) { this.selectObjectIdentityPrimaryKey = selectObjectIdentityPrimaryKey; } public void setSidPrimaryKeyQuery(String selectSidPrimaryKey) { this.selectSidPrimaryKey = selectSidPrimaryKey; } public void setUpdateObjectIdentity(String updateObjectIdentity) { this.updateObjectIdentity = updateObjectIdentity; } /** * @param foreignKeysInDatabase if false this class will perform additional FK * constrain checking, which may cause deadlocks (the default is true, so deadlocks * are avoided but the database is expected to enforce FKs) */ public void setForeignKeysInDatabase(boolean foreignKeysInDatabase) { this.foreignKeysInDatabase = foreignKeysInDatabase; } @Override public void setAclClassIdSupported(boolean aclClassIdSupported) { super.setAclClassIdSupported(aclClassIdSupported); if (aclClassIdSupported) { // Change the default insert if it hasn't been overridden if (this.insertClass.equals(DEFAULT_INSERT_INTO_ACL_CLASS)) { this.insertClass = DEFAULT_INSERT_INTO_ACL_CLASS_WITH_ID; } else { log.debug("Insert class statement has already been overridden, so not overridding the default"); } } } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } }
19,634
38.908537
130
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/jdbc/package-info.java
/* * Copyright 2002-2016 the original author or 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 * * https://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. */ /** * JDBC-based persistence of ACL information */ package org.springframework.security.acls.jdbc;
724
33.52381
75
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java
/* * Copyright 2004, 2005, 2006, 2017 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.io.Serializable; import java.lang.reflect.Field; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.sql.DataSource; import org.springframework.core.convert.ConversionException; import org.springframework.core.convert.ConversionService; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.security.acls.domain.AccessControlEntryImpl; import org.springframework.security.acls.domain.AclAuthorizationStrategy; import org.springframework.security.acls.domain.AclImpl; import org.springframework.security.acls.domain.AuditLogger; import org.springframework.security.acls.domain.DefaultPermissionFactory; import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy; import org.springframework.security.acls.domain.GrantedAuthoritySid; import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl; import org.springframework.security.acls.domain.PermissionFactory; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.AccessControlEntry; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AclCache; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentityGenerator; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.PermissionGrantingStrategy; import org.springframework.security.acls.model.Sid; import org.springframework.security.acls.model.UnloadedSidException; import org.springframework.security.util.FieldUtils; import org.springframework.util.Assert; /** * Performs lookups in a manner that is compatible with ANSI SQL. * <p> * NB: This implementation does attempt to provide reasonably optimised lookups - within * the constraints of a normalised database and standard ANSI SQL features. If you are * willing to sacrifice either of these constraints (e.g. use a particular database * feature such as hierarchical queries or materalized views, or reduce normalisation) you * are likely to achieve better performance. In such situations you will need to provide * your own custom <code>LookupStrategy</code>. This class does not support subclassing, * as it is likely to change in future releases and therefore subclassing is unsupported. * <p> * There are two SQL queries executed, one in the <tt>lookupPrimaryKeys</tt> method and * one in <tt>lookupObjectIdentities</tt>. These are built from the same select and "order * by" clause, using a different where clause in each case. In order to use custom schema * or column names, each of these SQL clauses can be customized, but they must be * consistent with each other and with the expected result set generated by the default * values. * * @author Ben Alex */ public class BasicLookupStrategy implements LookupStrategy { private static final String DEFAULT_SELECT_CLAUSE_COLUMNS = "select acl_object_identity.object_id_identity, " + "acl_entry.ace_order, " + "acl_object_identity.id as acl_id, " + "acl_object_identity.parent_object, " + "acl_object_identity.entries_inheriting, " + "acl_entry.id as ace_id, " + "acl_entry.mask, " + "acl_entry.granting, " + "acl_entry.audit_success, " + "acl_entry.audit_failure, " + "acl_sid.principal as ace_principal, " + "acl_sid.sid as ace_sid, " + "acli_sid.principal as acl_principal, " + "acli_sid.sid as acl_sid, " + "acl_class.class "; private static final String DEFAULT_SELECT_CLAUSE_ACL_CLASS_ID_TYPE_COLUMN = ", acl_class.class_id_type "; private static final String DEFAULT_SELECT_CLAUSE_FROM = "from acl_object_identity " + "left join acl_sid acli_sid on acli_sid.id = acl_object_identity.owner_sid " + "left join acl_class on acl_class.id = acl_object_identity.object_id_class " + "left join acl_entry on acl_object_identity.id = acl_entry.acl_object_identity " + "left join acl_sid on acl_entry.sid = acl_sid.id " + "where ( "; public static final String DEFAULT_SELECT_CLAUSE = DEFAULT_SELECT_CLAUSE_COLUMNS + DEFAULT_SELECT_CLAUSE_FROM; public static final String DEFAULT_ACL_CLASS_ID_SELECT_CLAUSE = DEFAULT_SELECT_CLAUSE_COLUMNS + DEFAULT_SELECT_CLAUSE_ACL_CLASS_ID_TYPE_COLUMN + DEFAULT_SELECT_CLAUSE_FROM; private static final String DEFAULT_LOOKUP_KEYS_WHERE_CLAUSE = "(acl_object_identity.id = ?)"; private static final String DEFAULT_LOOKUP_IDENTITIES_WHERE_CLAUSE = "(acl_object_identity.object_id_identity = ? and acl_class.class = ?)"; public static final String DEFAULT_ORDER_BY_CLAUSE = ") order by acl_object_identity.object_id_identity" + " asc, acl_entry.ace_order asc"; private final AclAuthorizationStrategy aclAuthorizationStrategy; private ObjectIdentityGenerator objectIdentityGenerator; private PermissionFactory permissionFactory = new DefaultPermissionFactory(); private final AclCache aclCache; private final PermissionGrantingStrategy grantingStrategy; private final JdbcTemplate jdbcTemplate; private int batchSize = 50; private final Field fieldAces = FieldUtils.getField(AclImpl.class, "aces"); private final Field fieldAcl = FieldUtils.getField(AccessControlEntryImpl.class, "acl"); // SQL Customization fields private String selectClause = DEFAULT_SELECT_CLAUSE; private String lookupPrimaryKeysWhereClause = DEFAULT_LOOKUP_KEYS_WHERE_CLAUSE; private String lookupObjectIdentitiesWhereClause = DEFAULT_LOOKUP_IDENTITIES_WHERE_CLAUSE; private String orderByClause = DEFAULT_ORDER_BY_CLAUSE; private AclClassIdUtils aclClassIdUtils; /** * Constructor accepting mandatory arguments * @param dataSource to access the database * @param aclCache the cache where fully-loaded elements can be stored * @param aclAuthorizationStrategy authorization strategy (required) */ public BasicLookupStrategy(DataSource dataSource, AclCache aclCache, AclAuthorizationStrategy aclAuthorizationStrategy, AuditLogger auditLogger) { this(dataSource, aclCache, aclAuthorizationStrategy, new DefaultPermissionGrantingStrategy(auditLogger)); } /** * Creates a new instance * @param dataSource to access the database * @param aclCache the cache where fully-loaded elements can be stored * @param aclAuthorizationStrategy authorization strategy (required) * @param grantingStrategy the PermissionGrantingStrategy */ public BasicLookupStrategy(DataSource dataSource, AclCache aclCache, AclAuthorizationStrategy aclAuthorizationStrategy, PermissionGrantingStrategy grantingStrategy) { Assert.notNull(dataSource, "DataSource required"); Assert.notNull(aclCache, "AclCache required"); Assert.notNull(aclAuthorizationStrategy, "AclAuthorizationStrategy required"); Assert.notNull(grantingStrategy, "grantingStrategy required"); this.jdbcTemplate = new JdbcTemplate(dataSource); this.aclCache = aclCache; this.aclAuthorizationStrategy = aclAuthorizationStrategy; this.grantingStrategy = grantingStrategy; this.objectIdentityGenerator = new ObjectIdentityRetrievalStrategyImpl(); this.aclClassIdUtils = new AclClassIdUtils(); this.fieldAces.setAccessible(true); this.fieldAcl.setAccessible(true); } private String computeRepeatingSql(String repeatingSql, int requiredRepetitions) { Assert.isTrue(requiredRepetitions > 0, "requiredRepetitions must be > 0"); String startSql = this.selectClause; String endSql = this.orderByClause; StringBuilder sqlStringBldr = new StringBuilder( startSql.length() + endSql.length() + requiredRepetitions * (repeatingSql.length() + 4)); sqlStringBldr.append(startSql); for (int i = 1; i <= requiredRepetitions; i++) { sqlStringBldr.append(repeatingSql); if (i != requiredRepetitions) { sqlStringBldr.append(" or "); } } sqlStringBldr.append(endSql); return sqlStringBldr.toString(); } @SuppressWarnings("unchecked") private List<AccessControlEntryImpl> readAces(AclImpl acl) { try { return (List<AccessControlEntryImpl>) this.fieldAces.get(acl); } catch (IllegalAccessException ex) { throw new IllegalStateException("Could not obtain AclImpl.aces field", ex); } } private void setAclOnAce(AccessControlEntryImpl ace, AclImpl acl) { try { this.fieldAcl.set(ace, acl); } catch (IllegalAccessException ex) { throw new IllegalStateException("Could not or set AclImpl on AccessControlEntryImpl fields", ex); } } private void setAces(AclImpl acl, List<AccessControlEntryImpl> aces) { try { this.fieldAces.set(acl, aces); } catch (IllegalAccessException ex) { throw new IllegalStateException("Could not set AclImpl entries", ex); } } /** * Locates the primary key IDs specified in "findNow", adding AclImpl instances with * StubAclParents to the "acls" Map. * @param acls the AclImpls (with StubAclParents) * @param findNow Long-based primary keys to retrieve * @param sids */ private void lookupPrimaryKeys(final Map<Serializable, Acl> acls, final Set<Long> findNow, final List<Sid> sids) { Assert.notNull(acls, "ACLs are required"); Assert.notEmpty(findNow, "Items to find now required"); String sql = computeRepeatingSql(this.lookupPrimaryKeysWhereClause, findNow.size()); Set<Long> parentsToLookup = this.jdbcTemplate.query(sql, (ps) -> setKeys(ps, findNow), new ProcessResultSet(acls, sids)); // Lookup the parents, now that our JdbcTemplate has released the database // connection (SEC-547) if (parentsToLookup.size() > 0) { lookupPrimaryKeys(acls, parentsToLookup, sids); } } private void setKeys(PreparedStatement ps, Set<Long> findNow) throws SQLException { int i = 0; for (Long toFind : findNow) { i++; ps.setLong(i, toFind); } } /** * The main method. * <p> * WARNING: This implementation completely disregards the "sids" argument! Every item * in the cache is expected to contain all SIDs. If you have serious performance needs * (e.g. a very large number of SIDs per object identity), you'll probably want to * develop a custom {@link LookupStrategy} implementation instead. * <p> * The implementation works in batch sizes specified by {@link #batchSize}. * @param objects the identities to lookup (required) * @param sids the SIDs for which identities are required (ignored by this * implementation) * @return a <tt>Map</tt> where keys represent the {@link ObjectIdentity} of the * located {@link Acl} and values are the located {@link Acl} (never <tt>null</tt> * although some entries may be missing; this method should not throw * {@link NotFoundException}, as a chain of {@link LookupStrategy}s may be used to * automatically create entries if required) */ @Override public final Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) { Assert.isTrue(this.batchSize >= 1, "BatchSize must be >= 1"); Assert.notEmpty(objects, "Objects to lookup required"); // Map<ObjectIdentity,Acl> // contains FULLY loaded Acl objects Map<ObjectIdentity, Acl> result = new HashMap<>(); Set<ObjectIdentity> currentBatchToLoad = new HashSet<>(); for (int i = 0; i < objects.size(); i++) { final ObjectIdentity oid = objects.get(i); boolean aclFound = false; // Check we don't already have this ACL in the results if (result.containsKey(oid)) { aclFound = true; } // Check cache for the present ACL entry if (!aclFound) { Acl acl = this.aclCache.getFromCache(oid); // Ensure any cached element supports all the requested SIDs // (they should always, as our base impl doesn't filter on SID) if (acl != null) { Assert.state(acl.isSidLoaded(sids), "Error: SID-filtered element detected when implementation does not perform SID filtering " + "- have you added something to the cache manually?"); result.put(acl.getObjectIdentity(), acl); aclFound = true; } } // Load the ACL from the database if (!aclFound) { currentBatchToLoad.add(oid); } // Is it time to load from JDBC the currentBatchToLoad? if ((currentBatchToLoad.size() == this.batchSize) || ((i + 1) == objects.size())) { if (currentBatchToLoad.size() > 0) { Map<ObjectIdentity, Acl> loadedBatch = lookupObjectIdentities(currentBatchToLoad, sids); // Add loaded batch (all elements 100% initialized) to results result.putAll(loadedBatch); // Add the loaded batch to the cache for (Acl loadedAcl : loadedBatch.values()) { this.aclCache.putInCache((AclImpl) loadedAcl); } currentBatchToLoad.clear(); } } } return result; } /** * Looks up a batch of <code>ObjectIdentity</code>s directly from the database. * <p> * The caller is responsible for optimization issues, such as selecting the identities * to lookup, ensuring the cache doesn't contain them already, and adding the returned * elements to the cache etc. * <p> * This subclass is required to return fully valid <code>Acl</code>s, including * properly-configured parent ACLs. */ private Map<ObjectIdentity, Acl> lookupObjectIdentities(final Collection<ObjectIdentity> objectIdentities, List<Sid> sids) { Assert.notEmpty(objectIdentities, "Must provide identities to lookup"); // contains Acls with StubAclParents Map<Serializable, Acl> acls = new HashMap<>(); // Make the "acls" map contain all requested objectIdentities // (including markers to each parent in the hierarchy) String sql = computeRepeatingSql(this.lookupObjectIdentitiesWhereClause, objectIdentities.size()); Set<Long> parentsToLookup = this.jdbcTemplate.query(sql, (ps) -> setupLookupObjectIdentitiesStatement(ps, objectIdentities), new ProcessResultSet(acls, sids)); // Lookup the parents, now that our JdbcTemplate has released the database // connection (SEC-547) if (parentsToLookup.size() > 0) { lookupPrimaryKeys(acls, parentsToLookup, sids); } // Finally, convert our "acls" containing StubAclParents into true Acls Map<ObjectIdentity, Acl> resultMap = new HashMap<>(); for (Acl inputAcl : acls.values()) { Assert.isInstanceOf(AclImpl.class, inputAcl, "Map should have contained an AclImpl"); Assert.isInstanceOf(Long.class, ((AclImpl) inputAcl).getId(), "Acl.getId() must be Long"); Acl result = convert(acls, (Long) ((AclImpl) inputAcl).getId()); resultMap.put(result.getObjectIdentity(), result); } return resultMap; } private void setupLookupObjectIdentitiesStatement(PreparedStatement ps, Collection<ObjectIdentity> objectIdentities) throws SQLException { int i = 0; for (ObjectIdentity oid : objectIdentities) { // Determine prepared statement values for this iteration String type = oid.getType(); // No need to check for nulls, as guaranteed non-null by // ObjectIdentity.getIdentifier() interface contract String identifier = oid.getIdentifier().toString(); // Inject values ps.setString((2 * i) + 1, identifier); ps.setString((2 * i) + 2, type); i++; } } /** * The final phase of converting the <code>Map</code> of <code>AclImpl</code> * instances which contain <code>StubAclParent</code>s into proper, valid * <code>AclImpl</code>s with correct ACL parents. * @param inputMap the unconverted <code>AclImpl</code>s * @param currentIdentity the current<code>Acl</code> that we wish to convert (this * may be */ private AclImpl convert(Map<Serializable, Acl> inputMap, Long currentIdentity) { Assert.notEmpty(inputMap, "InputMap required"); Assert.notNull(currentIdentity, "CurrentIdentity required"); // Retrieve this Acl from the InputMap Acl uncastAcl = inputMap.get(currentIdentity); Assert.isInstanceOf(AclImpl.class, uncastAcl, "The inputMap contained a non-AclImpl"); AclImpl inputAcl = (AclImpl) uncastAcl; Acl parent = inputAcl.getParentAcl(); if ((parent != null) && parent instanceof StubAclParent) { // Lookup the parent StubAclParent stubAclParent = (StubAclParent) parent; parent = convert(inputMap, stubAclParent.getId()); } // Now we have the parent (if there is one), create the true AclImpl AclImpl result = new AclImpl(inputAcl.getObjectIdentity(), inputAcl.getId(), this.aclAuthorizationStrategy, this.grantingStrategy, parent, null, inputAcl.isEntriesInheriting(), inputAcl.getOwner()); // Copy the "aces" from the input to the destination // Obtain the "aces" from the input ACL List<AccessControlEntryImpl> aces = readAces(inputAcl); // Create a list in which to store the "aces" for the "result" AclImpl instance List<AccessControlEntryImpl> acesNew = new ArrayList<>(); // Iterate over the "aces" input and replace each nested // AccessControlEntryImpl.getAcl() with the new "result" AclImpl instance // This ensures StubAclParent instances are removed, as per SEC-951 for (AccessControlEntryImpl ace : aces) { setAclOnAce(ace, result); acesNew.add(ace); } // Finally, now that the "aces" have been converted to have the "result" AclImpl // instance, modify the "result" AclImpl instance setAces(result, acesNew); return result; } /** * Creates a particular implementation of {@link Sid} depending on the arguments. * @param sid the name of the sid representing its unique identifier. In typical ACL * database schema it's located in table {@code acl_sid} table, {@code sid} column. * @param isPrincipal whether it's a user or granted authority like role * @return the instance of Sid with the {@code sidName} as an identifier */ protected Sid createSid(boolean isPrincipal, String sid) { if (isPrincipal) { return new PrincipalSid(sid); } return new GrantedAuthoritySid(sid); } /** * Sets the {@code PermissionFactory} instance which will be used to convert loaded * permission data values to {@code Permission}s. A {@code DefaultPermissionFactory} * will be used by default. * @param permissionFactory */ public final void setPermissionFactory(PermissionFactory permissionFactory) { this.permissionFactory = permissionFactory; } public final void setBatchSize(int batchSize) { this.batchSize = batchSize; } /** * The SQL for the select clause. If customizing in order to modify column names, * schema etc, the other SQL customization fields must also be set to match. * @param selectClause the select clause, which defaults to * {@link #DEFAULT_SELECT_CLAUSE}. */ public final void setSelectClause(String selectClause) { this.selectClause = selectClause; } /** * The SQL for the where clause used in the <tt>lookupPrimaryKey</tt> method. */ public final void setLookupPrimaryKeysWhereClause(String lookupPrimaryKeysWhereClause) { this.lookupPrimaryKeysWhereClause = lookupPrimaryKeysWhereClause; } /** * The SQL for the where clause used in the <tt>lookupObjectIdentities</tt> method. */ public final void setLookupObjectIdentitiesWhereClause(String lookupObjectIdentitiesWhereClause) { this.lookupObjectIdentitiesWhereClause = lookupObjectIdentitiesWhereClause; } /** * The SQL for the "order by" clause used in both queries. */ public final void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public final void setAclClassIdSupported(boolean aclClassIdSupported) { if (aclClassIdSupported) { Assert.isTrue(this.selectClause.equals(DEFAULT_SELECT_CLAUSE), "Cannot set aclClassIdSupported and override the select clause; " + "just override the select clause"); this.selectClause = DEFAULT_ACL_CLASS_ID_SELECT_CLAUSE; } } public final void setObjectIdentityGenerator(ObjectIdentityGenerator objectIdentityGenerator) { Assert.notNull(objectIdentityGenerator, "objectIdentityGenerator cannot be null"); this.objectIdentityGenerator = objectIdentityGenerator; } public final void setConversionService(ConversionService conversionService) { this.aclClassIdUtils = new AclClassIdUtils(conversionService); } private class ProcessResultSet implements ResultSetExtractor<Set<Long>> { private final Map<Serializable, Acl> acls; private final List<Sid> sids; ProcessResultSet(Map<Serializable, Acl> acls, List<Sid> sids) { Assert.notNull(acls, "ACLs cannot be null"); this.acls = acls; this.sids = sids; // can be null } /** * Implementation of {@link ResultSetExtractor#extractData(ResultSet)}. Creates an * {@link Acl} for each row in the {@link ResultSet} and ensures it is in member * field <tt>acls</tt>. Any {@link Acl} with a parent will have the parents id * returned in a set. The returned set of ids may requires further processing. * @param rs The {@link ResultSet} to be processed * @return a list of parent IDs remaining to be looked up (may be empty, but never * <tt>null</tt>) * @throws SQLException */ @Override public Set<Long> extractData(ResultSet rs) throws SQLException { Set<Long> parentIdsToLookup = new HashSet<>(); // Set of parent_id Longs while (rs.next()) { // Convert current row into an Acl (albeit with a StubAclParent) convertCurrentResultIntoObject(this.acls, rs); // Figure out if this row means we need to lookup another parent long parentId = rs.getLong("parent_object"); if (parentId != 0) { // See if it's already in the "acls" if (this.acls.containsKey(parentId)) { continue; // skip this while iteration } // Now try to find it in the cache MutableAcl cached = BasicLookupStrategy.this.aclCache.getFromCache(parentId); if ((cached == null) || !cached.isSidLoaded(this.sids)) { parentIdsToLookup.add(parentId); } else { // Pop into the acls map, so our convert method doesn't // need to deal with an unsynchronized AclCache this.acls.put(cached.getId(), cached); } } } // Return the parents left to lookup to the caller return parentIdsToLookup; } /** * Accepts the current <code>ResultSet</code> row, and converts it into an * <code>AclImpl</code> that contains a <code>StubAclParent</code> * @param acls the Map we should add the converted Acl to * @param rs the ResultSet focused on a current row * @throws SQLException if something goes wrong converting values * @throws ConversionException if can't convert to the desired Java type */ private void convertCurrentResultIntoObject(Map<Serializable, Acl> acls, ResultSet rs) throws SQLException { Long id = rs.getLong("acl_id"); // If we already have an ACL for this ID, just create the ACE Acl acl = acls.get(id); if (acl == null) { // Make an AclImpl and pop it into the Map // If the Java type is a String, check to see if we can convert it to the // target id type, e.g. UUID. Serializable identifier = (Serializable) rs.getObject("object_id_identity"); identifier = BasicLookupStrategy.this.aclClassIdUtils.identifierFrom(identifier, rs); ObjectIdentity objectIdentity = BasicLookupStrategy.this.objectIdentityGenerator .createObjectIdentity(identifier, rs.getString("class")); Acl parentAcl = null; long parentAclId = rs.getLong("parent_object"); if (parentAclId != 0) { parentAcl = new StubAclParent(parentAclId); } boolean entriesInheriting = rs.getBoolean("entries_inheriting"); Sid owner = createSid(rs.getBoolean("acl_principal"), rs.getString("acl_sid")); acl = new AclImpl(objectIdentity, id, BasicLookupStrategy.this.aclAuthorizationStrategy, BasicLookupStrategy.this.grantingStrategy, parentAcl, null, entriesInheriting, owner); acls.put(id, acl); } // Add an extra ACE to the ACL (ORDER BY maintains the ACE list order) // It is permissible to have no ACEs in an ACL (which is detected by a null // ACE_SID) if (rs.getString("ace_sid") != null) { Long aceId = rs.getLong("ace_id"); Sid recipient = createSid(rs.getBoolean("ace_principal"), rs.getString("ace_sid")); int mask = rs.getInt("mask"); Permission permission = BasicLookupStrategy.this.permissionFactory.buildFromMask(mask); boolean granting = rs.getBoolean("granting"); boolean auditSuccess = rs.getBoolean("audit_success"); boolean auditFailure = rs.getBoolean("audit_failure"); AccessControlEntryImpl ace = new AccessControlEntryImpl(aceId, acl, recipient, permission, granting, auditSuccess, auditFailure); // Field acesField = FieldUtils.getField(AclImpl.class, "aces"); List<AccessControlEntryImpl> aces = readAces((AclImpl) acl); // Add the ACE if it doesn't already exist in the ACL.aces field if (!aces.contains(ace)) { aces.add(ace); } } } } private static class StubAclParent implements Acl { private final Long id; StubAclParent(Long id) { this.id = id; } Long getId() { return this.id; } @Override public List<AccessControlEntry> getEntries() { throw new UnsupportedOperationException("Stub only"); } @Override public ObjectIdentity getObjectIdentity() { throw new UnsupportedOperationException("Stub only"); } @Override public Sid getOwner() { throw new UnsupportedOperationException("Stub only"); } @Override public Acl getParentAcl() { throw new UnsupportedOperationException("Stub only"); } @Override public boolean isEntriesInheriting() { throw new UnsupportedOperationException("Stub only"); } @Override public boolean isGranted(List<Permission> permission, List<Sid> sids, boolean administrativeMode) throws NotFoundException, UnloadedSidException { throw new UnsupportedOperationException("Stub only"); } @Override public boolean isSidLoaded(List<Sid> sids) { throw new UnsupportedOperationException("Stub only"); } } }
26,762
38.415317
141
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/jdbc/LookupStrategy.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.util.List; import java.util.Map; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.Sid; /** * Performs lookups for {@link org.springframework.security.acls.model.AclService}. * * @author Ben Alex */ public interface LookupStrategy { /** * Perform database-specific optimized lookup. * @param objects the identities to lookup (required) * @param sids the SIDs for which identities are required (may be <tt>null</tt> - * implementations may elect not to provide SID optimisations) * @return a <tt>Map</tt> where keys represent the {@link ObjectIdentity} of the * located {@link Acl} and values are the located {@link Acl} (never <tt>null</tt> * although some entries may be missing; this method should not throw * {@link NotFoundException}, as a chain of {@link LookupStrategy}s may be used to * automatically create entries if required) */ Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids); }
1,822
36.979167
85
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java
/* * Copyright 2004, 2005, 2006, 2017, 2018 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.convert.ConversionService; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentityGenerator; import org.springframework.security.acls.model.Sid; import org.springframework.util.Assert; /** * Simple JDBC-based implementation of <code>AclService</code>. * <p> * Requires the "dirty" flags in {@link org.springframework.security.acls.domain.AclImpl} * and {@link org.springframework.security.acls.domain.AccessControlEntryImpl} to be set, * so that the implementation can detect changed parameters easily. * * @author Ben Alex */ public class JdbcAclService implements AclService { protected static final Log log = LogFactory.getLog(JdbcAclService.class); private static final String DEFAULT_SELECT_ACL_CLASS_COLUMNS = "class.class as class"; private static final String DEFAULT_SELECT_ACL_CLASS_COLUMNS_WITH_ID_TYPE = DEFAULT_SELECT_ACL_CLASS_COLUMNS + ", class.class_id_type as class_id_type"; private static final String DEFAULT_SELECT_ACL_WITH_PARENT_SQL = "select obj.object_id_identity as obj_id, " + DEFAULT_SELECT_ACL_CLASS_COLUMNS + " from acl_object_identity obj, acl_object_identity parent, acl_class class " + "where obj.parent_object = parent.id and obj.object_id_class = class.id " + "and parent.object_id_identity = ? and parent.object_id_class = (" + "select id FROM acl_class where acl_class.class = ?)"; private static final String DEFAULT_SELECT_ACL_WITH_PARENT_SQL_WITH_CLASS_ID_TYPE = "select obj.object_id_identity as obj_id, " + DEFAULT_SELECT_ACL_CLASS_COLUMNS_WITH_ID_TYPE + " from acl_object_identity obj, acl_object_identity parent, acl_class class " + "where obj.parent_object = parent.id and obj.object_id_class = class.id " + "and parent.object_id_identity = ? and parent.object_id_class = (" + "select id FROM acl_class where acl_class.class = ?)"; protected final JdbcOperations jdbcOperations; private final LookupStrategy lookupStrategy; private boolean aclClassIdSupported; private String findChildrenSql = DEFAULT_SELECT_ACL_WITH_PARENT_SQL; private AclClassIdUtils aclClassIdUtils; private ObjectIdentityGenerator objectIdentityGenerator; public JdbcAclService(DataSource dataSource, LookupStrategy lookupStrategy) { this(new JdbcTemplate(dataSource), lookupStrategy); } public JdbcAclService(JdbcOperations jdbcOperations, LookupStrategy lookupStrategy) { Assert.notNull(jdbcOperations, "JdbcOperations required"); Assert.notNull(lookupStrategy, "LookupStrategy required"); this.jdbcOperations = jdbcOperations; this.lookupStrategy = lookupStrategy; this.aclClassIdUtils = new AclClassIdUtils(); this.objectIdentityGenerator = new ObjectIdentityRetrievalStrategyImpl(); } @Override public List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity) { Object[] args = { parentIdentity.getIdentifier().toString(), parentIdentity.getType() }; List<ObjectIdentity> objects = this.jdbcOperations.query(this.findChildrenSql, args, (rs, rowNum) -> mapObjectIdentityRow(rs)); return (!objects.isEmpty()) ? objects : null; } private ObjectIdentity mapObjectIdentityRow(ResultSet rs) throws SQLException { String javaType = rs.getString("class"); Serializable identifier = (Serializable) rs.getObject("obj_id"); identifier = this.aclClassIdUtils.identifierFrom(identifier, rs); return this.objectIdentityGenerator.createObjectIdentity(identifier, javaType); } @Override public Acl readAclById(ObjectIdentity object, List<Sid> sids) throws NotFoundException { Map<ObjectIdentity, Acl> map = readAclsById(Collections.singletonList(object), sids); Assert.isTrue(map.containsKey(object), () -> "There should have been an Acl entry for ObjectIdentity " + object); return map.get(object); } @Override public Acl readAclById(ObjectIdentity object) throws NotFoundException { return readAclById(object, null); } @Override public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects) throws NotFoundException { return readAclsById(objects, null); } @Override public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) throws NotFoundException { Map<ObjectIdentity, Acl> result = this.lookupStrategy.readAclsById(objects, sids); // Check every requested object identity was found (throw NotFoundException if // needed) for (ObjectIdentity oid : objects) { if (!result.containsKey(oid)) { throw new NotFoundException("Unable to find ACL information for object identity '" + oid + "'"); } } return result; } /** * Allows customization of the SQL query used to find child object identities. * @param findChildrenSql */ public void setFindChildrenQuery(String findChildrenSql) { this.findChildrenSql = findChildrenSql; } public void setAclClassIdSupported(boolean aclClassIdSupported) { this.aclClassIdSupported = aclClassIdSupported; if (aclClassIdSupported) { // Change the default children select if it hasn't been overridden if (this.findChildrenSql.equals(DEFAULT_SELECT_ACL_WITH_PARENT_SQL)) { this.findChildrenSql = DEFAULT_SELECT_ACL_WITH_PARENT_SQL_WITH_CLASS_ID_TYPE; } else { log.debug("Find children statement has already been overridden, so not overridding the default"); } } } public void setConversionService(ConversionService conversionService) { this.aclClassIdUtils = new AclClassIdUtils(conversionService); } public void setObjectIdentityGenerator(ObjectIdentityGenerator objectIdentityGenerator) { Assert.notNull(objectIdentityGenerator, "objectIdentityGenerator cannot be null"); this.objectIdentityGenerator = objectIdentityGenerator; } protected boolean isAclClassIdSupported() { return this.aclClassIdSupported; } }
7,161
38.351648
128
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/jdbc/AclClassIdUtils.java
/* * Copyright 2002-2018 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.convert.ConversionFailedException; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.util.Assert; /** * Utility class for helping convert database representations of * {@link ObjectIdentity#getIdentifier()} into the correct Java type as specified by * <code>acl_class.class_id_type</code>. * * @author paulwheeler */ class AclClassIdUtils { private static final String DEFAULT_CLASS_ID_TYPE_COLUMN_NAME = "class_id_type"; private static final Log log = LogFactory.getLog(AclClassIdUtils.class); private ConversionService conversionService; AclClassIdUtils() { GenericConversionService genericConversionService = new GenericConversionService(); genericConversionService.addConverter(String.class, Long.class, new StringToLongConverter()); genericConversionService.addConverter(String.class, UUID.class, new StringToUUIDConverter()); this.conversionService = genericConversionService; } AclClassIdUtils(ConversionService conversionService) { Assert.notNull(conversionService, "conversionService must not be null"); this.conversionService = conversionService; } /** * Converts the raw type from the database into the right Java type. For most * applications the 'raw type' will be Long, for some applications it could be String. * @param identifier The identifier from the database * @param resultSet Result set of the query * @return The identifier in the appropriate target Java type. Typically Long or UUID. * @throws SQLException */ Serializable identifierFrom(Serializable identifier, ResultSet resultSet) throws SQLException { if (isString(identifier) && hasValidClassIdType(resultSet) && canConvertFromStringTo(classIdTypeFrom(resultSet))) { return convertFromStringTo((String) identifier, classIdTypeFrom(resultSet)); } // Assume it should be a Long type return convertToLong(identifier); } private boolean hasValidClassIdType(ResultSet resultSet) { try { return classIdTypeFrom(resultSet) != null; } catch (SQLException ex) { log.debug("Unable to obtain the class id type", ex); return false; } } private <T extends Serializable> Class<T> classIdTypeFrom(ResultSet resultSet) throws SQLException { return classIdTypeFrom(resultSet.getString(DEFAULT_CLASS_ID_TYPE_COLUMN_NAME)); } private <T extends Serializable> Class<T> classIdTypeFrom(String className) { if (className == null) { return null; } try { return (Class) Class.forName(className); } catch (ClassNotFoundException ex) { log.debug("Unable to find class id type on classpath", ex); return null; } } private <T> boolean canConvertFromStringTo(Class<T> targetType) { return this.conversionService.canConvert(String.class, targetType); } private <T extends Serializable> T convertFromStringTo(String identifier, Class<T> targetType) { return this.conversionService.convert(identifier, targetType); } /** * Converts to a {@link Long}, attempting to use the {@link ConversionService} if * available. * @param identifier The identifier * @return Long version of the identifier * @throws NumberFormatException if the string cannot be parsed to a long. * @throws org.springframework.core.convert.ConversionException if a conversion * exception occurred * @throws IllegalArgumentException if targetType is null */ private Long convertToLong(Serializable identifier) { if (this.conversionService.canConvert(identifier.getClass(), Long.class)) { return this.conversionService.convert(identifier, Long.class); } return Long.valueOf(identifier.toString()); } private boolean isString(Serializable object) { return object.getClass().isAssignableFrom(String.class); } void setConversionService(ConversionService conversionService) { Assert.notNull(conversionService, "conversionService must not be null"); this.conversionService = conversionService; } private static class StringToLongConverter implements Converter<String, Long> { @Override public Long convert(String identifierAsString) { if (identifierAsString == null) { throw new ConversionFailedException(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Long.class), null, null); } return Long.parseLong(identifierAsString); } } private static class StringToUUIDConverter implements Converter<String, UUID> { @Override public UUID convert(String identifierAsString) { if (identifierAsString == null) { throw new ConversionFailedException(TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(UUID.class), null, null); } return UUID.fromString(identifierAsString); } } }
5,819
33.43787
101
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/afterinvocation/package-info.java
/* * Copyright 2002-2016 the original author or 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 * * https://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. */ /** * After-invocation providers for collection and array filtering. Consider using a * {@code PostFilter} annotation in preference. */ package org.springframework.security.acls.afterinvocation;
821
36.363636
82
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/afterinvocation/CollectionFilterer.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.afterinvocation; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; /** * A filter used to filter Collections. * * @author Ben Alex * @author Paulo Neves */ class CollectionFilterer<T> implements Filterer<T> { protected static final Log logger = LogFactory.getLog(CollectionFilterer.class); private final Collection<T> collection; private final Set<T> removeList; CollectionFilterer(Collection<T> collection) { this.collection = collection; // We create a Set of objects to be removed from the Collection, // as ConcurrentModificationException prevents removal during // iteration, and making a new Collection to be returned is // problematic as the original Collection implementation passed // to the method may not necessarily be re-constructable (as // the Collection(collection) constructor is not guaranteed and // manually adding may lose sort order or other capabilities) this.removeList = new HashSet<>(); } @Override public Object getFilteredObject() { // Now the Iterator has ended, remove Objects from Collection Iterator<T> removeIter = this.removeList.iterator(); int originalSize = this.collection.size(); while (removeIter.hasNext()) { this.collection.remove(removeIter.next()); } logger.debug(LogMessage.of(() -> "Original collection contained " + originalSize + " elements; now contains " + this.collection.size() + " elements")); return this.collection; } @Override public Iterator<T> iterator() { return this.collection.iterator(); } @Override public void remove(T object) { this.removeList.add(object); } }
2,456
30.101266
111
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/afterinvocation/AbstractAclProvider.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.afterinvocation; import java.util.List; import org.springframework.security.access.AfterInvocationProvider; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.acls.domain.ObjectIdentityRetrievalStrategyImpl; import org.springframework.security.acls.domain.SidRetrievalStrategyImpl; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.Sid; import org.springframework.security.acls.model.SidRetrievalStrategy; import org.springframework.security.core.Authentication; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; /** * Abstract {@link AfterInvocationProvider} which provides commonly-used ACL-related * services. * * @author Ben Alex */ public abstract class AbstractAclProvider implements AfterInvocationProvider { protected final AclService aclService; protected String processConfigAttribute; protected Class<?> processDomainObjectClass = Object.class; protected ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy = new ObjectIdentityRetrievalStrategyImpl(); protected SidRetrievalStrategy sidRetrievalStrategy = new SidRetrievalStrategyImpl(); protected final List<Permission> requirePermission; public AbstractAclProvider(AclService aclService, String processConfigAttribute, List<Permission> requirePermission) { Assert.hasText(processConfigAttribute, "A processConfigAttribute is mandatory"); Assert.notNull(aclService, "An AclService is mandatory"); Assert.isTrue(!ObjectUtils.isEmpty(requirePermission), "One or more requirePermission entries is mandatory"); this.aclService = aclService; this.processConfigAttribute = processConfigAttribute; this.requirePermission = requirePermission; } protected Class<?> getProcessDomainObjectClass() { return this.processDomainObjectClass; } protected boolean hasPermission(Authentication authentication, Object domainObject) { // Obtain the OID applicable to the domain object ObjectIdentity objectIdentity = this.objectIdentityRetrievalStrategy.getObjectIdentity(domainObject); // Obtain the SIDs applicable to the principal List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication); try { // Lookup only ACLs for SIDs we're interested in Acl acl = this.aclService.readAclById(objectIdentity, sids); return acl.isGranted(this.requirePermission, sids, false); } catch (NotFoundException ex) { return false; } } public void setObjectIdentityRetrievalStrategy(ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy) { Assert.notNull(objectIdentityRetrievalStrategy, "ObjectIdentityRetrievalStrategy required"); this.objectIdentityRetrievalStrategy = objectIdentityRetrievalStrategy; } protected void setProcessConfigAttribute(String processConfigAttribute) { Assert.hasText(processConfigAttribute, "A processConfigAttribute is mandatory"); this.processConfigAttribute = processConfigAttribute; } public void setProcessDomainObjectClass(Class<?> processDomainObjectClass) { Assert.notNull(processDomainObjectClass, "processDomainObjectClass cannot be set to null"); this.processDomainObjectClass = processDomainObjectClass; } public void setSidRetrievalStrategy(SidRetrievalStrategy sidRetrievalStrategy) { Assert.notNull(sidRetrievalStrategy, "SidRetrievalStrategy required"); this.sidRetrievalStrategy = sidRetrievalStrategy; } @Override public boolean supports(ConfigAttribute attribute) { return this.processConfigAttribute.equals(attribute.getAttribute()); } /** * This implementation supports any type of class, because it does not query the * presented secure object. * @param clazz the secure object * @return always <code>true</code> */ @Override public boolean supports(Class<?> clazz) { return true; } }
4,844
37.76
119
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationCollectionFilteringProvider.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.afterinvocation; import java.util.Collection; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.AuthorizationServiceException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.Permission; import org.springframework.security.core.Authentication; /** * <p> * Given a <code>Collection</code> of domain object instances returned from a secure * object invocation, remove any <code>Collection</code> elements the principal does not * have appropriate permission to access as defined by the {@link AclService}. * <p> * The <code>AclService</code> is used to retrieve the access control list (ACL) * permissions associated with each <code>Collection</code> domain object instance element * for the current <code>Authentication</code> object. * <p> * This after invocation provider will fire if any {@link ConfigAttribute#getAttribute()} * matches the {@link #processConfigAttribute}. The provider will then lookup the ACLs * from the <code>AclService</code> and ensure the principal is * {@link org.springframework.security.acls.model.Acl#isGranted(List, List, boolean) * Acl.isGranted()} when presenting the {@link #requirePermission} array to that method. * <p> * If the principal does not have permission, that element will not be included in the * returned <code>Collection</code>. * <p> * Often users will setup a <code>BasicAclEntryAfterInvocationProvider</code> with a * {@link #processConfigAttribute} of <code>AFTER_ACL_COLLECTION_READ</code> and a * {@link #requirePermission} of <code>BasePermission.READ</code>. These are also the * defaults. * <p> * If the provided <code>returnObject</code> is <code>null</code>, a <code>null</code> * <code>Collection</code> will be returned. If the provided <code>returnObject</code> is * not a <code>Collection</code>, an {@link AuthorizationServiceException} will be thrown. * <p> * All comparisons and prefixes are case sensitive. * * @author Ben Alex * @author Paulo Neves */ public class AclEntryAfterInvocationCollectionFilteringProvider extends AbstractAclProvider { protected static final Log logger = LogFactory.getLog(AclEntryAfterInvocationCollectionFilteringProvider.class); public AclEntryAfterInvocationCollectionFilteringProvider(AclService aclService, List<Permission> requirePermission) { super(aclService, "AFTER_ACL_COLLECTION_READ", requirePermission); } @Override @SuppressWarnings("unchecked") public Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> config, Object returnedObject) throws AccessDeniedException { if (returnedObject == null) { logger.debug("Return object is null, skipping"); return null; } for (ConfigAttribute attr : config) { if (!this.supports(attr)) { continue; } // Need to process the Collection for this invocation Filterer filterer = getFilterer(returnedObject); // Locate unauthorised Collection elements for (Object domainObject : filterer) { // Ignore nulls or entries which aren't instances of the configured domain // object class if (domainObject == null || !getProcessDomainObjectClass().isAssignableFrom(domainObject.getClass())) { continue; } if (!hasPermission(authentication, domainObject)) { filterer.remove(domainObject); logger.debug(LogMessage.of(() -> "Principal is NOT authorised for element: " + domainObject)); } } return filterer.getFilteredObject(); } return returnedObject; } private Filterer getFilterer(Object returnedObject) { if (returnedObject instanceof Collection) { return new CollectionFilterer((Collection) returnedObject); } if (returnedObject.getClass().isArray()) { return new ArrayFilterer((Object[]) returnedObject); } throw new AuthorizationServiceException("A Collection or an array (or null) was required as the " + "returnedObject, but the returnedObject was: " + returnedObject); } }
4,918
39.652893
113
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/afterinvocation/ArrayFilterer.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.afterinvocation; import java.lang.reflect.Array; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; /** * A filter used to filter arrays. * * @author Ben Alex * @author Paulo Neves */ class ArrayFilterer<T> implements Filterer<T> { protected static final Log logger = LogFactory.getLog(ArrayFilterer.class); private final Set<T> removeList; private final T[] list; ArrayFilterer(T[] list) { this.list = list; // Collect the removed objects to a HashSet so that // it is fast to lookup them when a filtered array // is constructed. this.removeList = new HashSet<>(); } @Override @SuppressWarnings("unchecked") public T[] getFilteredObject() { // Recreate an array of same type and filter the removed objects. int originalSize = this.list.length; int sizeOfResultingList = originalSize - this.removeList.size(); T[] filtered = (T[]) Array.newInstance(this.list.getClass().getComponentType(), sizeOfResultingList); for (int i = 0, j = 0; i < this.list.length; i++) { T object = this.list[i]; if (!this.removeList.contains(object)) { filtered[j] = object; j++; } } logger.debug(LogMessage.of(() -> "Original array contained " + originalSize + " elements; now contains " + sizeOfResultingList + " elements")); return filtered; } @Override public Iterator<T> iterator() { return new ArrayFiltererIterator(); } @Override public void remove(T object) { this.removeList.add(object); } /** * Iterator for {@link ArrayFilterer} elements. */ private class ArrayFiltererIterator implements Iterator<T> { private int index = 0; @Override public boolean hasNext() { return this.index < ArrayFilterer.this.list.length; } @Override public T next() { if (hasNext()) { return ArrayFilterer.this.list[this.index++]; } throw new NoSuchElementException(); } } }
2,732
25.278846
106
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/afterinvocation/AclEntryAfterInvocationProvider.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.afterinvocation; import java.util.Collection; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; import org.springframework.context.support.MessageSourceAccessor; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.Permission; import org.springframework.security.core.Authentication; import org.springframework.security.core.SpringSecurityMessageSource; /** * Given a domain object instance returned from a secure object invocation, ensures the * principal has appropriate permission as defined by the {@link AclService}. * <p> * The <code>AclService</code> is used to retrieve the access control list (ACL) * permissions associated with a domain object instance for the current * <code>Authentication</code> object. * <p> * This after invocation provider will fire if any {@link ConfigAttribute#getAttribute()} * matches the {@link #processConfigAttribute}. The provider will then lookup the ACLs * from the <tt>AclService</tt> and ensure the principal is * {@link org.springframework.security.acls.model.Acl#isGranted(List, List, boolean) * Acl.isGranted(List, List, boolean)} when presenting the {@link #requirePermission} * array to that method. * <p> * Often users will set up an <code>AclEntryAfterInvocationProvider</code> with a * {@link #processConfigAttribute} of <code>AFTER_ACL_READ</code> and a * {@link #requirePermission} of <code>BasePermission.READ</code>. These are also the * defaults. * <p> * If the principal does not have sufficient permissions, an * <code>AccessDeniedException</code> will be thrown. * <p> * If the provided <tt>returnedObject</tt> is <code>null</code>, permission will always be * granted and <code>null</code> will be returned. * <p> * All comparisons and prefixes are case sensitive. */ public class AclEntryAfterInvocationProvider extends AbstractAclProvider implements MessageSourceAware { protected static final Log logger = LogFactory.getLog(AclEntryAfterInvocationProvider.class); protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); public AclEntryAfterInvocationProvider(AclService aclService, List<Permission> requirePermission) { this(aclService, "AFTER_ACL_READ", requirePermission); } public AclEntryAfterInvocationProvider(AclService aclService, String processConfigAttribute, List<Permission> requirePermission) { super(aclService, processConfigAttribute, requirePermission); } @Override public Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> config, Object returnedObject) throws AccessDeniedException { if (returnedObject == null) { // AclManager interface contract prohibits nulls // As they have permission to null/nothing, grant access logger.debug("Return object is null, skipping"); return null; } if (!getProcessDomainObjectClass().isAssignableFrom(returnedObject.getClass())) { logger.debug("Return object is not applicable for this provider, skipping"); return returnedObject; } for (ConfigAttribute attr : config) { if (!this.supports(attr)) { continue; } // Need to make an access decision on this invocation if (hasPermission(authentication, returnedObject)) { return returnedObject; } logger.debug("Denying access"); throw new AccessDeniedException(this.messages.getMessage("AclEntryAfterInvocationProvider.noPermission", new Object[] { authentication.getName(), returnedObject }, "Authentication {0} has NO permissions to the domain object {1}")); } return returnedObject; } @Override public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } }
4,701
38.512605
107
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/afterinvocation/Filterer.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.afterinvocation; import java.util.Iterator; /** * Filterer strategy interface. * * @author Ben Alex * @author Paulo Neves */ interface Filterer<T> extends Iterable<T> { /** * Gets the filtered collection or array. * @return the filtered collection or array */ Object getFilteredObject(); /** * Returns an iterator over the filtered collection or array. * @return an Iterator */ @Override Iterator<T> iterator(); /** * Removes the given object from the resulting list. * @param object the object to be removed */ void remove(T object); }
1,242
24.367347
75
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/AuditLogger.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.springframework.security.acls.model.AccessControlEntry; /** * Used by <code>AclImpl</code> to log audit events. * * @author Ben Alex */ public interface AuditLogger { void logIfNeeded(boolean granted, AccessControlEntry ace); }
925
28.870968
75
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/package-info.java
/* * Copyright 2002-2016 the original author or 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 * * https://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. */ /** * Basic implementation of access control lists (ACLs) interfaces. */ package org.springframework.security.acls.domain;
748
34.666667
75
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/BasePermission.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.springframework.security.acls.model.Permission; /** * A set of standard permissions. * * <p> * You may subclass this class to add additional permissions, or use this class as a guide * for creating your own permission classes. * </p> * * @author Ben Alex */ public class BasePermission extends AbstractPermission { public static final Permission READ = new BasePermission(1 << 0, 'R'); // 1 public static final Permission WRITE = new BasePermission(1 << 1, 'W'); // 2 public static final Permission CREATE = new BasePermission(1 << 2, 'C'); // 4 public static final Permission DELETE = new BasePermission(1 << 3, 'D'); // 8 public static final Permission ADMINISTRATION = new BasePermission(1 << 4, 'A'); // 16 protected BasePermission(int mask) { super(mask); } protected BasePermission(int mask, char code) { super(mask, code); } }
1,554
28.903846
90
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/SpringCacheBasedAclCache.java
/* * Copyright 2002-2013 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.io.Serializable; import org.springframework.cache.Cache; import org.springframework.security.acls.model.AclCache; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.PermissionGrantingStrategy; import org.springframework.security.util.FieldUtils; import org.springframework.util.Assert; /** * Simple implementation of {@link org.springframework.security.acls.model.AclCache} that * delegates to {@link Cache} implementation. * <p> * Designed to handle the transient fields in * {@link org.springframework.security.acls.domain.AclImpl}. Note that this implementation * assumes all {@link org.springframework.security.acls.domain.AclImpl} instances share * the same {@link org.springframework.security.acls.model.PermissionGrantingStrategy} and * {@link org.springframework.security.acls.domain.AclAuthorizationStrategy} instances. * * @author Marten Deinum * @since 3.2 */ public class SpringCacheBasedAclCache implements AclCache { private final Cache cache; private PermissionGrantingStrategy permissionGrantingStrategy; private AclAuthorizationStrategy aclAuthorizationStrategy; public SpringCacheBasedAclCache(Cache cache, PermissionGrantingStrategy permissionGrantingStrategy, AclAuthorizationStrategy aclAuthorizationStrategy) { Assert.notNull(cache, "Cache required"); Assert.notNull(permissionGrantingStrategy, "PermissionGrantingStrategy required"); Assert.notNull(aclAuthorizationStrategy, "AclAuthorizationStrategy required"); this.cache = cache; this.permissionGrantingStrategy = permissionGrantingStrategy; this.aclAuthorizationStrategy = aclAuthorizationStrategy; } @Override public void evictFromCache(Serializable pk) { Assert.notNull(pk, "Primary key (identifier) required"); MutableAcl acl = getFromCache(pk); if (acl != null) { this.cache.evict(acl.getId()); this.cache.evict(acl.getObjectIdentity()); } } @Override public void evictFromCache(ObjectIdentity objectIdentity) { Assert.notNull(objectIdentity, "ObjectIdentity required"); MutableAcl acl = getFromCache(objectIdentity); if (acl != null) { this.cache.evict(acl.getId()); this.cache.evict(acl.getObjectIdentity()); } } @Override public MutableAcl getFromCache(ObjectIdentity objectIdentity) { Assert.notNull(objectIdentity, "ObjectIdentity required"); return getFromCache((Object) objectIdentity); } @Override public MutableAcl getFromCache(Serializable pk) { Assert.notNull(pk, "Primary key (identifier) required"); return getFromCache((Object) pk); } @Override public void putInCache(MutableAcl acl) { Assert.notNull(acl, "Acl required"); Assert.notNull(acl.getObjectIdentity(), "ObjectIdentity required"); Assert.notNull(acl.getId(), "ID required"); if ((acl.getParentAcl() != null) && (acl.getParentAcl() instanceof MutableAcl)) { putInCache((MutableAcl) acl.getParentAcl()); } this.cache.put(acl.getObjectIdentity(), acl); this.cache.put(acl.getId(), acl); } private MutableAcl getFromCache(Object key) { Cache.ValueWrapper element = this.cache.get(key); if (element == null) { return null; } return initializeTransientFields((MutableAcl) element.get()); } private MutableAcl initializeTransientFields(MutableAcl value) { if (value instanceof AclImpl) { FieldUtils.setProtectedFieldValue("aclAuthorizationStrategy", value, this.aclAuthorizationStrategy); FieldUtils.setProtectedFieldValue("permissionGrantingStrategy", value, this.permissionGrantingStrategy); } if (value.getParentAcl() != null) { initializeTransientFields((MutableAcl) value.getParentAcl()); } return value; } @Override public void clearCache() { this.cache.clear(); } }
4,479
33.728682
107
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/AclAuthorizationStrategyImpl.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.util.Arrays; import java.util.List; import java.util.Set; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.Sid; import org.springframework.security.acls.model.SidRetrievalStrategy; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.util.Assert; /** * Default implementation of {@link AclAuthorizationStrategy}. * <p> * Permission will be granted if at least one of the following conditions is true for the * current principal. * <ul> * <li>is the owner (as defined by the ACL).</li> * <li>holds the relevant system-wide {@link GrantedAuthority} injected into the * constructor.</li> * <li>has {@link BasePermission#ADMINISTRATION} permission (as defined by the ACL).</li> * </ul> * * @author Ben Alex */ public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy { private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); private final GrantedAuthority gaGeneralChanges; private final GrantedAuthority gaModifyAuditing; private final GrantedAuthority gaTakeOwnership; private SidRetrievalStrategy sidRetrievalStrategy = new SidRetrievalStrategyImpl(); /** * Constructor. The only mandatory parameter relates to the system-wide * {@link GrantedAuthority} instances that can be held to always permit ACL changes. * @param auths the <code>GrantedAuthority</code>s that have special permissions * (index 0 is the authority needed to change ownership, index 1 is the authority * needed to modify auditing details, index 2 is the authority needed to change other * ACL and ACE details) (required) * <p> * Alternatively, a single value can be supplied for all three permissions. */ public AclAuthorizationStrategyImpl(GrantedAuthority... auths) { Assert.isTrue(auths != null && (auths.length == 3 || auths.length == 1), "One or three GrantedAuthority instances required"); if (auths.length == 3) { this.gaTakeOwnership = auths[0]; this.gaModifyAuditing = auths[1]; this.gaGeneralChanges = auths[2]; } else { this.gaTakeOwnership = auths[0]; this.gaModifyAuditing = auths[0]; this.gaGeneralChanges = auths[0]; } } @Override public void securityCheck(Acl acl, int changeType) { SecurityContext context = this.securityContextHolderStrategy.getContext(); if ((context == null) || (context.getAuthentication() == null) || !context.getAuthentication().isAuthenticated()) { throw new AccessDeniedException("Authenticated principal required to operate with ACLs"); } Authentication authentication = context.getAuthentication(); // Check if authorized by virtue of ACL ownership Sid currentUser = createCurrentUser(authentication); if (currentUser.equals(acl.getOwner()) && ((changeType == CHANGE_GENERAL) || (changeType == CHANGE_OWNERSHIP))) { return; } // Iterate this principal's authorities to determine right Set<String> authorities = AuthorityUtils.authorityListToSet(authentication.getAuthorities()); if (acl.getOwner() instanceof GrantedAuthoritySid && authorities.contains(((GrantedAuthoritySid) acl.getOwner()).getGrantedAuthority())) { return; } // Not authorized by ACL ownership; try via adminstrative permissions GrantedAuthority requiredAuthority = getRequiredAuthority(changeType); if (authorities.contains(requiredAuthority.getAuthority())) { return; } // Try to get permission via ACEs within the ACL List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication); if (acl.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), sids, false)) { return; } throw new AccessDeniedException( "Principal does not have required ACL permissions to perform requested operation"); } private GrantedAuthority getRequiredAuthority(int changeType) { if (changeType == CHANGE_AUDITING) { return this.gaModifyAuditing; } if (changeType == CHANGE_GENERAL) { return this.gaGeneralChanges; } if (changeType == CHANGE_OWNERSHIP) { return this.gaTakeOwnership; } throw new IllegalArgumentException("Unknown change type"); } /** * Creates a principal-like sid from the authentication information. * @param authentication the authentication information that can provide principal and * thus the sid's id will be dependant on the value inside * @return a sid with the ID taken from the authentication information */ protected Sid createCurrentUser(Authentication authentication) { return new PrincipalSid(authentication); } public void setSidRetrievalStrategy(SidRetrievalStrategy sidRetrievalStrategy) { Assert.notNull(sidRetrievalStrategy, "SidRetrievalStrategy required"); this.sidRetrievalStrategy = sidRetrievalStrategy; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } }
6,379
37.433735
108
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/SidRetrievalStrategyImpl.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.security.access.hierarchicalroles.NullRoleHierarchy; import org.springframework.security.access.hierarchicalroles.RoleHierarchy; import org.springframework.security.acls.model.Sid; import org.springframework.security.acls.model.SidRetrievalStrategy; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.util.Assert; /** * Basic implementation of {@link SidRetrievalStrategy} that creates a {@link Sid} for the * principal, as well as every granted authority the principal holds. Can optionally have * a <tt>RoleHierarchy</tt> injected in order to determine the extended list of * authorities that the principal is assigned. * <p> * The returned array will always contain the {@link PrincipalSid} before any * {@link GrantedAuthoritySid} elements. * * @author Ben Alex */ public class SidRetrievalStrategyImpl implements SidRetrievalStrategy { private RoleHierarchy roleHierarchy = new NullRoleHierarchy(); public SidRetrievalStrategyImpl() { } public SidRetrievalStrategyImpl(RoleHierarchy roleHierarchy) { Assert.notNull(roleHierarchy, "RoleHierarchy must not be null"); this.roleHierarchy = roleHierarchy; } @Override public List<Sid> getSids(Authentication authentication) { Collection<? extends GrantedAuthority> authorities = this.roleHierarchy .getReachableGrantedAuthorities(authentication.getAuthorities()); List<Sid> sids = new ArrayList<>(authorities.size() + 1); sids.add(new PrincipalSid(authentication)); for (GrantedAuthority authority : authorities) { sids.add(new GrantedAuthoritySid(authority)); } return sids; } }
2,455
35.656716
90
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/AccessControlEntryImpl.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.io.Serializable; import org.springframework.security.acls.model.AccessControlEntry; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AuditableAccessControlEntry; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.Sid; import org.springframework.util.Assert; /** * An immutable default implementation of <code>AccessControlEntry</code>. * * @author Ben Alex */ public class AccessControlEntryImpl implements AccessControlEntry, AuditableAccessControlEntry { private final Acl acl; private Permission permission; private final Serializable id; private final Sid sid; private boolean auditFailure = false; private boolean auditSuccess = false; private final boolean granting; public AccessControlEntryImpl(Serializable id, Acl acl, Sid sid, Permission permission, boolean granting, boolean auditSuccess, boolean auditFailure) { Assert.notNull(acl, "Acl required"); Assert.notNull(sid, "Sid required"); Assert.notNull(permission, "Permission required"); this.id = id; this.acl = acl; // can be null this.sid = sid; this.permission = permission; this.granting = granting; this.auditSuccess = auditSuccess; this.auditFailure = auditFailure; } @Override public boolean equals(Object arg0) { if (!(arg0 instanceof AccessControlEntryImpl)) { return false; } AccessControlEntryImpl other = (AccessControlEntryImpl) arg0; if (this.acl == null) { if (other.getAcl() != null) { return false; } // Both this.acl and rhs.acl are null and thus equal } else { // this.acl is non-null if (other.getAcl() == null) { return false; } // Both this.acl and rhs.acl are non-null, so do a comparison if (this.acl.getObjectIdentity() == null) { if (other.acl.getObjectIdentity() != null) { return false; } // Both this.acl and rhs.acl are null and thus equal } else { // Both this.acl.objectIdentity and rhs.acl.objectIdentity are non-null if (!this.acl.getObjectIdentity().equals(other.getAcl().getObjectIdentity())) { return false; } } } if (this.id == null) { if (other.id != null) { return false; } // Both this.id and rhs.id are null and thus equal } else { // this.id is non-null if (other.id == null) { return false; } // Both this.id and rhs.id are non-null if (!this.id.equals(other.id)) { return false; } } if ((this.auditFailure != other.isAuditFailure()) || (this.auditSuccess != other.isAuditSuccess()) || (this.granting != other.isGranting()) || !this.permission.equals(other.getPermission()) || !this.sid.equals(other.getSid())) { return false; } return true; } @Override public int hashCode() { int result = this.permission.hashCode(); result = 31 * result + ((this.id != null) ? this.id.hashCode() : 0); result = 31 * result + (this.sid.hashCode()); result = 31 * result + (this.auditFailure ? 1 : 0); result = 31 * result + (this.auditSuccess ? 1 : 0); result = 31 * result + (this.granting ? 1 : 0); return result; } @Override public Acl getAcl() { return this.acl; } @Override public Serializable getId() { return this.id; } @Override public Permission getPermission() { return this.permission; } @Override public Sid getSid() { return this.sid; } @Override public boolean isAuditFailure() { return this.auditFailure; } @Override public boolean isAuditSuccess() { return this.auditSuccess; } @Override public boolean isGranting() { return this.granting; } void setAuditFailure(boolean auditFailure) { this.auditFailure = auditFailure; } void setAuditSuccess(boolean auditSuccess) { this.auditSuccess = auditSuccess; } void setPermission(Permission permission) { Assert.notNull(permission, "Permission required"); this.permission = permission; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("AccessControlEntryImpl["); sb.append("id: ").append(this.id).append("; "); sb.append("granting: ").append(this.granting).append("; "); sb.append("sid: ").append(this.sid).append("; "); sb.append("permission: ").append(this.permission).append("; "); sb.append("auditSuccess: ").append(this.auditSuccess).append("; "); sb.append("auditFailure: ").append(this.auditFailure); sb.append("]"); return sb.toString(); } }
5,141
25.642487
106
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/PermissionFactory.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.util.List; import org.springframework.security.acls.model.Permission; /** * Provides a simple mechanism to retrieve {@link Permission} instances from integer * masks. * * @author Ben Alex * @since 2.0.3 */ public interface PermissionFactory { /** * Dynamically creates a <code>CumulativePermission</code> or * <code>BasePermission</code> representing the active bits in the passed mask. * @param mask to build * @return a Permission representing the requested object */ Permission buildFromMask(int mask); Permission buildFromName(String name); List<Permission> buildFromNames(List<String> names); }
1,312
28.177778
84
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/AclImpl.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.springframework.security.acls.model.AccessControlEntry; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AuditableAcl; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.OwnershipAcl; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.PermissionGrantingStrategy; import org.springframework.security.acls.model.Sid; import org.springframework.security.acls.model.UnloadedSidException; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; /** * Base implementation of <code>Acl</code>. * * @author Ben Alex */ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl { private Acl parentAcl; private transient AclAuthorizationStrategy aclAuthorizationStrategy; private transient PermissionGrantingStrategy permissionGrantingStrategy; private final List<AccessControlEntry> aces = new ArrayList<>(); private ObjectIdentity objectIdentity; private Serializable id; // OwnershipAcl private Sid owner; // includes all SIDs the WHERE clause covered, even if there was no ACE for a SID private List<Sid> loadedSids = null; private boolean entriesInheriting = true; /** * Minimal constructor, which should be used * {@link org.springframework.security.acls.model.MutableAclService#createAcl(ObjectIdentity)} * . * @param objectIdentity the object identity this ACL relates to (required) * @param id the primary key assigned to this ACL (required) * @param aclAuthorizationStrategy authorization strategy (required) * @param auditLogger audit logger (required) */ public AclImpl(ObjectIdentity objectIdentity, Serializable id, AclAuthorizationStrategy aclAuthorizationStrategy, AuditLogger auditLogger) { Assert.notNull(objectIdentity, "Object Identity required"); Assert.notNull(id, "Id required"); Assert.notNull(aclAuthorizationStrategy, "AclAuthorizationStrategy required"); Assert.notNull(auditLogger, "AuditLogger required"); this.objectIdentity = objectIdentity; this.id = id; this.aclAuthorizationStrategy = aclAuthorizationStrategy; this.permissionGrantingStrategy = new DefaultPermissionGrantingStrategy(auditLogger); } /** * Full constructor, which should be used by persistence tools that do not provide * field-level access features. * @param objectIdentity the object identity this ACL relates to * @param id the primary key assigned to this ACL * @param aclAuthorizationStrategy authorization strategy * @param grantingStrategy the {@code PermissionGrantingStrategy} which will be used * by the {@code isGranted()} method * @param parentAcl the parent (may be may be {@code null}) * @param loadedSids the loaded SIDs if only a subset were loaded (may be {@code null} * ) * @param entriesInheriting if ACEs from the parent should inherit into this ACL * @param owner the owner (required) */ public AclImpl(ObjectIdentity objectIdentity, Serializable id, AclAuthorizationStrategy aclAuthorizationStrategy, PermissionGrantingStrategy grantingStrategy, Acl parentAcl, List<Sid> loadedSids, boolean entriesInheriting, Sid owner) { Assert.notNull(objectIdentity, "Object Identity required"); Assert.notNull(id, "Id required"); Assert.notNull(aclAuthorizationStrategy, "AclAuthorizationStrategy required"); Assert.notNull(owner, "Owner required"); this.objectIdentity = objectIdentity; this.id = id; this.aclAuthorizationStrategy = aclAuthorizationStrategy; this.parentAcl = parentAcl; // may be null this.loadedSids = loadedSids; // may be null this.entriesInheriting = entriesInheriting; this.owner = owner; this.permissionGrantingStrategy = grantingStrategy; } /** * Private no-argument constructor for use by reflection-based persistence tools along * with field-level access. */ @SuppressWarnings("unused") private AclImpl() { } @Override public void deleteAce(int aceIndex) throws NotFoundException { this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL); verifyAceIndexExists(aceIndex); synchronized (this.aces) { this.aces.remove(aceIndex); } } private void verifyAceIndexExists(int aceIndex) { if (aceIndex < 0) { throw new NotFoundException("aceIndex must be greater than or equal to zero"); } if (aceIndex >= this.aces.size()) { throw new NotFoundException("aceIndex must refer to an index of the AccessControlEntry list. " + "List size is " + this.aces.size() + ", index was " + aceIndex); } } @Override public void insertAce(int atIndexLocation, Permission permission, Sid sid, boolean granting) throws NotFoundException { this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL); Assert.notNull(permission, "Permission required"); Assert.notNull(sid, "Sid required"); if (atIndexLocation < 0) { throw new NotFoundException("atIndexLocation must be greater than or equal to zero"); } if (atIndexLocation > this.aces.size()) { throw new NotFoundException( "atIndexLocation must be less than or equal to the size of the AccessControlEntry collection"); } AccessControlEntryImpl ace = new AccessControlEntryImpl(null, this, sid, permission, granting, false, false); synchronized (this.aces) { this.aces.add(atIndexLocation, ace); } } @Override public List<AccessControlEntry> getEntries() { // Can safely return AccessControlEntry directly, as they're immutable outside the // ACL package return new ArrayList<>(this.aces); } @Override public Serializable getId() { return this.id; } @Override public ObjectIdentity getObjectIdentity() { return this.objectIdentity; } @Override public boolean isEntriesInheriting() { return this.entriesInheriting; } /** * Delegates to the {@link PermissionGrantingStrategy}. * @throws UnloadedSidException if the passed SIDs are unknown to this ACL because the * ACL was only loaded for a subset of SIDs * @see DefaultPermissionGrantingStrategy */ @Override public boolean isGranted(List<Permission> permission, List<Sid> sids, boolean administrativeMode) throws NotFoundException, UnloadedSidException { Assert.notEmpty(permission, "Permissions required"); Assert.notEmpty(sids, "SIDs required"); if (!this.isSidLoaded(sids)) { throw new UnloadedSidException("ACL was not loaded for one or more SID"); } return this.permissionGrantingStrategy.isGranted(this, permission, sids, administrativeMode); } @Override public boolean isSidLoaded(List<Sid> sids) { // If loadedSides is null, this indicates all SIDs were loaded // Also return true if the caller didn't specify a SID to find if ((this.loadedSids == null) || (sids == null) || (sids.size() == 0)) { return true; } // This ACL applies to a SID subset only. Iterate to check it applies. for (Sid sid : sids) { boolean found = false; for (Sid loadedSid : this.loadedSids) { if (sid.equals(loadedSid)) { // this SID is OK found = true; break; // out of loadedSids for loop } } if (!found) { return false; } } return true; } @Override public void setEntriesInheriting(boolean entriesInheriting) { this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL); this.entriesInheriting = entriesInheriting; } @Override public void setOwner(Sid newOwner) { this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_OWNERSHIP); Assert.notNull(newOwner, "Owner required"); this.owner = newOwner; } @Override public Sid getOwner() { return this.owner; } @Override public void setParent(Acl newParent) { this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL); Assert.isTrue(newParent == null || !newParent.equals(this), "Cannot be the parent of yourself"); this.parentAcl = newParent; } @Override public Acl getParentAcl() { return this.parentAcl; } @Override public void updateAce(int aceIndex, Permission permission) throws NotFoundException { this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL); verifyAceIndexExists(aceIndex); synchronized (this.aces) { AccessControlEntryImpl ace = (AccessControlEntryImpl) this.aces.get(aceIndex); ace.setPermission(permission); } } @Override public void updateAuditing(int aceIndex, boolean auditSuccess, boolean auditFailure) { this.aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_AUDITING); verifyAceIndexExists(aceIndex); synchronized (this.aces) { AccessControlEntryImpl ace = (AccessControlEntryImpl) this.aces.get(aceIndex); ace.setAuditSuccess(auditSuccess); ace.setAuditFailure(auditFailure); } } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || !(obj instanceof AclImpl)) { return false; } AclImpl other = (AclImpl) obj; boolean result = true; result = result && this.aces.equals(other.aces); result = result && ObjectUtils.nullSafeEquals(this.parentAcl, other.parentAcl); result = result && ObjectUtils.nullSafeEquals(this.objectIdentity, other.objectIdentity); result = result && ObjectUtils.nullSafeEquals(this.id, other.id); result = result && ObjectUtils.nullSafeEquals(this.owner, other.owner); result = result && this.entriesInheriting == other.entriesInheriting; result = result && ObjectUtils.nullSafeEquals(this.loadedSids, other.loadedSids); return result; } @Override public int hashCode() { int result = (this.parentAcl != null) ? this.parentAcl.hashCode() : 0; result = 31 * result + this.aclAuthorizationStrategy.hashCode(); result = 31 * result + ((this.permissionGrantingStrategy != null) ? this.permissionGrantingStrategy.hashCode() : 0); result = 31 * result + ((this.aces != null) ? this.aces.hashCode() : 0); result = 31 * result + this.objectIdentity.hashCode(); result = 31 * result + this.id.hashCode(); result = 31 * result + ((this.owner != null) ? this.owner.hashCode() : 0); result = 31 * result + ((this.loadedSids != null) ? this.loadedSids.hashCode() : 0); result = 31 * result + (this.entriesInheriting ? 1 : 0); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("AclImpl["); sb.append("id: ").append(this.id).append("; "); sb.append("objectIdentity: ").append(this.objectIdentity).append("; "); sb.append("owner: ").append(this.owner).append("; "); int count = 0; for (AccessControlEntry ace : this.aces) { count++; if (count == 1) { sb.append("\n"); } sb.append(ace).append("\n"); } if (count == 0) { sb.append("no ACEs; "); } sb.append("inheriting: ").append(this.entriesInheriting).append("; "); sb.append("parent: ").append((this.parentAcl == null) ? "Null" : this.parentAcl.getObjectIdentity().toString()); sb.append("; "); sb.append("aclAuthorizationStrategy: ").append(this.aclAuthorizationStrategy).append("; "); sb.append("permissionGrantingStrategy: ").append(this.permissionGrantingStrategy); sb.append("]"); return sb.toString(); } }
12,197
34.771261
114
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/AclFormattingUtils.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.springframework.security.acls.model.Permission; import org.springframework.util.Assert; /** * Utility methods for displaying ACL information. * * @author Ben Alex */ public abstract class AclFormattingUtils { public static String demergePatterns(String original, String removeBits) { Assert.notNull(original, "Original string required"); Assert.notNull(removeBits, "Bits To Remove string required"); Assert.isTrue(original.length() == removeBits.length(), "Original and Bits To Remove strings must be identical length"); char[] replacement = new char[original.length()]; for (int i = 0; i < original.length(); i++) { if (removeBits.charAt(i) == Permission.RESERVED_OFF) { replacement[i] = original.charAt(i); } else { replacement[i] = Permission.RESERVED_OFF; } } return new String(replacement); } public static String mergePatterns(String original, String extraBits) { Assert.notNull(original, "Original string required"); Assert.notNull(extraBits, "Extra Bits string required"); Assert.isTrue(original.length() == extraBits.length(), "Original and Extra Bits strings must be identical length"); char[] replacement = new char[extraBits.length()]; for (int i = 0; i < extraBits.length(); i++) { if (extraBits.charAt(i) == Permission.RESERVED_OFF) { replacement[i] = original.charAt(i); } else { replacement[i] = extraBits.charAt(i); } } return new String(replacement); } /** * Returns a representation of the active bits in the presented mask, with each active * bit being denoted by character '*'. * <p> * Inactive bits will be denoted by character {@link Permission#RESERVED_OFF}. * @param i the integer bit mask to print the active bits for * @return a 32-character representation of the bit mask */ public static String printBinary(int i) { return printBinary(i, '*', Permission.RESERVED_OFF); } /** * Returns a representation of the active bits in the presented mask, with each active * bit being denoted by the passed character. * <p> * Inactive bits will be denoted by character {@link Permission#RESERVED_OFF}. * @param mask the integer bit mask to print the active bits for * @param code the character to print when an active bit is detected * @return a 32-character representation of the bit mask */ public static String printBinary(int mask, char code) { Assert.doesNotContain(Character.toString(code), Character.toString(Permission.RESERVED_ON), () -> Permission.RESERVED_ON + " is a reserved character code"); Assert.doesNotContain(Character.toString(code), Character.toString(Permission.RESERVED_OFF), () -> Permission.RESERVED_OFF + " is a reserved character code"); return printBinary(mask, Permission.RESERVED_ON, Permission.RESERVED_OFF).replace(Permission.RESERVED_ON, code); } private static String printBinary(int i, char on, char off) { String s = Integer.toBinaryString(i); String pattern = Permission.THIRTY_TWO_RESERVED_OFF; String temp2 = pattern.substring(0, pattern.length() - s.length()) + s; return temp2.replace('0', off).replace('1', on); } }
3,817
37.18
114
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/CumulativePermission.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.springframework.security.acls.model.Permission; /** * Represents a <code>Permission</code> that is constructed at runtime from other * permissions. * * <p> * Methods return <code>this</code>, in order to facilitate method chaining. * </p> * * @author Ben Alex */ public class CumulativePermission extends AbstractPermission { private String pattern = THIRTY_TWO_RESERVED_OFF; public CumulativePermission() { super(0, ' '); } public CumulativePermission clear(Permission permission) { this.mask &= ~permission.getMask(); this.pattern = AclFormattingUtils.demergePatterns(this.pattern, permission.getPattern()); return this; } public CumulativePermission clear() { this.mask = 0; this.pattern = THIRTY_TWO_RESERVED_OFF; return this; } public CumulativePermission set(Permission permission) { this.mask |= permission.getMask(); this.pattern = AclFormattingUtils.mergePatterns(this.pattern, permission.getPattern()); return this; } @Override public String getPattern() { return this.pattern; } }
1,732
26.507937
91
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/GrantedAuthoritySid.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.springframework.security.acls.model.Sid; import org.springframework.security.core.GrantedAuthority; import org.springframework.util.Assert; /** * Represents a <code>GrantedAuthority</code> as a <code>Sid</code>. * <p> * This is a basic implementation that simply uses the <code>String</code>-based principal * for <code>Sid</code> comparison. More complex principal objects may wish to provide an * alternative <code>Sid</code> implementation that uses some other identifier. * </p> * * @author Ben Alex */ public class GrantedAuthoritySid implements Sid { private final String grantedAuthority; public GrantedAuthoritySid(String grantedAuthority) { Assert.hasText(grantedAuthority, "GrantedAuthority required"); this.grantedAuthority = grantedAuthority; } public GrantedAuthoritySid(GrantedAuthority grantedAuthority) { Assert.notNull(grantedAuthority, "GrantedAuthority required"); Assert.notNull(grantedAuthority.getAuthority(), "This Sid is only compatible with GrantedAuthoritys that provide a non-null getAuthority()"); this.grantedAuthority = grantedAuthority.getAuthority(); } @Override public boolean equals(Object object) { if ((object == null) || !(object instanceof GrantedAuthoritySid)) { return false; } // Delegate to getGrantedAuthority() to perform actual comparison (both should be // identical) return ((GrantedAuthoritySid) object).getGrantedAuthority().equals(this.getGrantedAuthority()); } @Override public int hashCode() { return this.getGrantedAuthority().hashCode(); } public String getGrantedAuthority() { return this.grantedAuthority; } @Override public String toString() { return "GrantedAuthoritySid[" + this.grantedAuthority + "]"; } }
2,422
31.743243
97
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/ObjectIdentityRetrievalStrategyImpl.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.io.Serializable; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentityGenerator; import org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy; /** * Basic implementation of {@link ObjectIdentityRetrievalStrategy} and * <tt>ObjectIdentityGenerator</tt> that uses the constructors of * {@link ObjectIdentityImpl} to create the {@link ObjectIdentity}. * * @author Ben Alex */ public class ObjectIdentityRetrievalStrategyImpl implements ObjectIdentityRetrievalStrategy, ObjectIdentityGenerator { @Override public ObjectIdentity getObjectIdentity(Object domainObject) { return new ObjectIdentityImpl(domainObject); } @Override public ObjectIdentity createObjectIdentity(Serializable id, String type) { return new ObjectIdentityImpl(type, id); } }
1,542
33.288889
118
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/PrincipalSid.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.springframework.security.acls.model.Sid; import org.springframework.security.core.Authentication; import org.springframework.util.Assert; /** * Represents an <code>Authentication.getPrincipal()</code> as a <code>Sid</code>. * <p> * This is a basic implementation that simply uses the <code>String</code>-based principal * for <code>Sid</code> comparison. More complex principal objects may wish to provide an * alternative <code>Sid</code> implementation that uses some other identifier. * </p> * * @author Ben Alex */ public class PrincipalSid implements Sid { private final String principal; public PrincipalSid(String principal) { Assert.hasText(principal, "Principal required"); this.principal = principal; } public PrincipalSid(Authentication authentication) { Assert.notNull(authentication, "Authentication required"); Assert.notNull(authentication.getPrincipal(), "Principal required"); this.principal = authentication.getName(); } @Override public boolean equals(Object object) { if ((object == null) || !(object instanceof PrincipalSid)) { return false; } // Delegate to getPrincipal() to perform actual comparison (both should be // identical) return ((PrincipalSid) object).getPrincipal().equals(this.getPrincipal()); } @Override public int hashCode() { return this.getPrincipal().hashCode(); } public String getPrincipal() { return this.principal; } @Override public String toString() { return "PrincipalSid[" + this.principal + "]"; } }
2,202
29.178082
90
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/ObjectIdentityImpl.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.io.Serializable; import java.lang.reflect.Method; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * Simple implementation of {@link ObjectIdentity}. * <p> * Uses <code>String</code>s to store the identity of the domain object instance. Also * offers a constructor that uses reflection to build the identity information. * * @author Ben Alex */ public class ObjectIdentityImpl implements ObjectIdentity { private final String type; private Serializable identifier; public ObjectIdentityImpl(String type, Serializable identifier) { Assert.hasText(type, "Type required"); Assert.notNull(identifier, "identifier required"); this.identifier = identifier; this.type = type; } /** * Constructor which uses the name of the supplied class as the <tt>type</tt> * property. */ public ObjectIdentityImpl(Class<?> javaType, Serializable identifier) { Assert.notNull(javaType, "Java Type required"); Assert.notNull(identifier, "identifier required"); this.type = javaType.getName(); this.identifier = identifier; } /** * Creates the <code>ObjectIdentityImpl</code> based on the passed object instance. * The passed object must provide a <code>getId()</code> method, otherwise an * exception will be thrown. * <p> * The class name of the object passed will be considered the {@link #type}, so if * more control is required, a different constructor should be used. * @param object the domain object instance to create an identity for. * @throws IdentityUnavailableException if identity could not be extracted */ public ObjectIdentityImpl(Object object) throws IdentityUnavailableException { Assert.notNull(object, "object cannot be null"); Class<?> typeClass = ClassUtils.getUserClass(object.getClass()); this.type = typeClass.getName(); Object result = invokeGetIdMethod(object, typeClass); Assert.notNull(result, "getId() is required to return a non-null value"); Assert.isInstanceOf(Serializable.class, result, "Getter must provide a return value of type Serializable"); this.identifier = (Serializable) result; } private Object invokeGetIdMethod(Object object, Class<?> typeClass) { try { Method method = typeClass.getMethod("getId", new Class[] {}); return method.invoke(object); } catch (Exception ex) { throw new IdentityUnavailableException("Could not extract identity from object " + object, ex); } } /** * Important so caching operates properly. * <p> * Considers an object of the same class equal if it has the same * <code>classname</code> and <code>id</code> properties. * <p> * Numeric identities (Integer and Long values) are considered equal if they are * numerically equal. Other serializable types are evaluated using a simple equality. * @param obj object to compare * @return <code>true</code> if the presented object matches this object */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof ObjectIdentityImpl)) { return false; } ObjectIdentityImpl other = (ObjectIdentityImpl) obj; if (this.identifier instanceof Number && other.identifier instanceof Number) { // Integers and Longs with same value should be considered equal if (((Number) this.identifier).longValue() != ((Number) other.identifier).longValue()) { return false; } } else { // Use plain equality for other serializable types if (!this.identifier.equals(other.identifier)) { return false; } } return this.type.equals(other.type); } @Override public Serializable getIdentifier() { return this.identifier; } @Override public String getType() { return this.type; } /** * Important so caching operates properly. * @return the hash */ @Override public int hashCode() { int result = this.type.hashCode(); result = 31 * result + this.identifier.hashCode(); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getName()).append("["); sb.append("Type: ").append(this.type); sb.append("; Identifier: ").append(this.identifier).append("]"); return sb.toString(); } }
4,931
31.662252
109
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/DefaultPermissionGrantingStrategy.java
/* * Copyright 2002-2018 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.util.List; import org.springframework.security.acls.model.AccessControlEntry; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.PermissionGrantingStrategy; import org.springframework.security.acls.model.Sid; import org.springframework.util.Assert; public class DefaultPermissionGrantingStrategy implements PermissionGrantingStrategy { private final transient AuditLogger auditLogger; /** * Creates an instance with the logger which will be used to record granting and * denial of requested permissions. */ public DefaultPermissionGrantingStrategy(AuditLogger auditLogger) { Assert.notNull(auditLogger, "auditLogger cannot be null"); this.auditLogger = auditLogger; } /** * Determines authorization. The order of the <code>permission</code> and * <code>sid</code> arguments is <em>extremely important</em>! The method will iterate * through each of the <code>permission</code>s in the order specified. For each * iteration, all of the <code>sid</code>s will be considered, again in the order they * are presented. A search will then be performed for the first * {@link AccessControlEntry} object that directly matches that * <code>permission:sid</code> combination. When the <em>first full match</em> is * found (ie an ACE that has the SID currently being searched for and the exact * permission bit mask being search for), the grant or deny flag for that ACE will * prevail. If the ACE specifies to grant access, the method will return * <code>true</code>. If the ACE specifies to deny access, the loop will stop and the * next <code>permission</code> iteration will be performed. If each permission * indicates to deny access, the first deny ACE found will be considered the reason * for the failure (as it was the first match found, and is therefore the one most * logically requiring changes - although not always). If absolutely no matching ACE * was found at all for any permission, the parent ACL will be tried (provided that * there is a parent and {@link Acl#isEntriesInheriting()} is <code>true</code>. The * parent ACL will also scan its parent and so on. If ultimately no matching ACE is * found, a <code>NotFoundException</code> will be thrown and the caller will need to * decide how to handle the permission check. Similarly, if any of the SID arguments * presented to the method were not loaded by the ACL, * <code>UnloadedSidException</code> will be thrown. * @param permission the exact permissions to scan for (order is important) * @param sids the exact SIDs to scan for (order is important) * @param administrativeMode if <code>true</code> denotes the query is for * administrative purposes and no auditing will be undertaken * @return <code>true</code> if one of the permissions has been granted, * <code>false</code> if one of the permissions has been specifically revoked * @throws NotFoundException if an exact ACE for one of the permission bit masks and * SID combination could not be found */ @Override public boolean isGranted(Acl acl, List<Permission> permission, List<Sid> sids, boolean administrativeMode) throws NotFoundException { List<AccessControlEntry> aces = acl.getEntries(); AccessControlEntry firstRejection = null; for (Permission p : permission) { for (Sid sid : sids) { // Attempt to find exact match for this permission mask and SID boolean scanNextSid = true; for (AccessControlEntry ace : aces) { if (isGranted(ace, p) && ace.getSid().equals(sid)) { // Found a matching ACE, so its authorization decision will // prevail if (ace.isGranting()) { // Success if (!administrativeMode) { this.auditLogger.logIfNeeded(true, ace); } return true; } // Failure for this permission, so stop search // We will see if they have a different permission // (this permission is 100% rejected for this SID) if (firstRejection == null) { // Store first rejection for auditing reasons firstRejection = ace; } scanNextSid = false; // helps break the loop break; // exit aces loop } } if (!scanNextSid) { break; // exit SID for loop (now try next permission) } } } if (firstRejection != null) { // We found an ACE to reject the request at this point, as no // other ACEs were found that granted a different permission if (!administrativeMode) { this.auditLogger.logIfNeeded(false, firstRejection); } return false; } // No matches have been found so far if (acl.isEntriesInheriting() && (acl.getParentAcl() != null)) { // We have a parent, so let them try to find a matching ACE return acl.getParentAcl().isGranted(permission, sids, false); } // We either have no parent, or we're the uppermost parent throw new NotFoundException("Unable to locate a matching ACE for passed permissions and SIDs"); } /** * Compares an ACE Permission to the given Permission. By default, we compare the * Permission masks for exact match. Subclasses of this strategy can override this * behavior and implement more sophisticated comparisons, e.g. a bitwise comparison * for ACEs that grant access. <pre>{@code * if (ace.isGranting() && p.getMask() != 0) { * return (ace.getPermission().getMask() & p.getMask()) != 0; * } else { * return ace.getPermission().getMask() == p.getMask(); * } * }</pre> * @param ace the ACE from the Acl holding the mask. * @param p the Permission we are checking against. * @return true, if the respective masks are considered to be equal. */ protected boolean isGranted(AccessControlEntry ace, Permission p) { return ace.getPermission().getMask() == p.getMask(); } }
6,603
42.447368
107
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/IdentityUnavailableException.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; /** * Thrown if an ACL identity could not be extracted from an object. * * @author Ben Alex */ public class IdentityUnavailableException extends RuntimeException { /** * Constructs an <code>IdentityUnavailableException</code> with the specified message. * @param msg the detail message */ public IdentityUnavailableException(String msg) { super(msg); } /** * Constructs an <code>IdentityUnavailableException</code> with the specified message * and root cause. * @param msg the detail message * @param cause root cause */ public IdentityUnavailableException(String msg, Throwable cause) { super(msg, cause); } }
1,322
28.4
87
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/DefaultPermissionFactory.java
/* * Copyright 2002-2018 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.security.acls.model.Permission; import org.springframework.util.Assert; /** * Default implementation of {@link PermissionFactory}. * <p> * Used as a strategy by classes which wish to map integer masks and permission names to * <tt>Permission</tt> instances for use with the ACL implementation. * <p> * Maintains a registry of permission names and masks to <tt>Permission</tt> instances. * * @author Ben Alex * @author Luke Taylor * @since 2.0.3 */ public class DefaultPermissionFactory implements PermissionFactory { private final Map<Integer, Permission> registeredPermissionsByInteger = new HashMap<>(); private final Map<String, Permission> registeredPermissionsByName = new HashMap<>(); /** * Registers the <tt>Permission</tt> fields from the <tt>BasePermission</tt> class. */ public DefaultPermissionFactory() { registerPublicPermissions(BasePermission.class); } /** * Registers the <tt>Permission</tt> fields from the supplied class. */ public DefaultPermissionFactory(Class<? extends Permission> permissionClass) { registerPublicPermissions(permissionClass); } /** * Registers a map of named <tt>Permission</tt> instances. * @param namedPermissions the map of <tt>Permission</tt>s, keyed by name. */ public DefaultPermissionFactory(Map<String, ? extends Permission> namedPermissions) { for (String name : namedPermissions.keySet()) { registerPermission(namedPermissions.get(name), name); } } /** * Registers the public static fields of type {@link Permission} for a give class. * <p> * These permissions will be registered under the name of the field. See * {@link BasePermission} for an example. * @param clazz a {@link Permission} class with public static fields to register */ protected void registerPublicPermissions(Class<? extends Permission> clazz) { Assert.notNull(clazz, "Class required"); Field[] fields = clazz.getFields(); for (Field field : fields) { try { Object fieldValue = field.get(null); if (Permission.class.isAssignableFrom(fieldValue.getClass())) { // Found a Permission static field Permission perm = (Permission) fieldValue; String permissionName = field.getName(); registerPermission(perm, permissionName); } } catch (Exception ex) { } } } protected void registerPermission(Permission perm, String permissionName) { Assert.notNull(perm, "Permission required"); Assert.hasText(permissionName, "Permission name required"); Integer mask = perm.getMask(); // Ensure no existing Permission uses this integer or code Assert.isTrue(!this.registeredPermissionsByInteger.containsKey(mask), () -> "An existing Permission already provides mask " + mask); Assert.isTrue(!this.registeredPermissionsByName.containsKey(permissionName), () -> "An existing Permission already provides name '" + permissionName + "'"); // Register the new Permission this.registeredPermissionsByInteger.put(mask, perm); this.registeredPermissionsByName.put(permissionName, perm); } @Override public Permission buildFromMask(int mask) { if (this.registeredPermissionsByInteger.containsKey(mask)) { // The requested mask has an exact match against a statically-defined // Permission, so return it return this.registeredPermissionsByInteger.get(mask); } // To get this far, we have to use a CumulativePermission CumulativePermission permission = new CumulativePermission(); for (int i = 0; i < 32; i++) { int permissionToCheck = 1 << i; if ((mask & permissionToCheck) == permissionToCheck) { Permission p = this.registeredPermissionsByInteger.get(permissionToCheck); Assert.state(p != null, () -> "Mask '" + permissionToCheck + "' does not have a corresponding static Permission"); permission.set(p); } } return permission; } @Override public Permission buildFromName(String name) { Permission p = this.registeredPermissionsByName.get(name); Assert.notNull(p, "Unknown permission '" + name + "'"); return p; } @Override public List<Permission> buildFromNames(List<String> names) { if ((names == null) || (names.size() == 0)) { return Collections.emptyList(); } List<Permission> permissions = new ArrayList<>(names.size()); for (String name : names) { permissions.add(buildFromName(name)); } return permissions; } }
5,212
32.850649
96
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/AbstractPermission.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.springframework.security.acls.model.Permission; /** * Provides an abstract superclass for {@link Permission} implementations. * * @author Ben Alex * @since 2.0.3 */ public abstract class AbstractPermission implements Permission { protected final char code; protected int mask; /** * Sets the permission mask and uses the '*' character to represent active bits when * represented as a bit pattern string. * @param mask the integer bit mask for the permission */ protected AbstractPermission(int mask) { this.mask = mask; this.code = '*'; } /** * Sets the permission mask and uses the specified character for active bits. * @param mask the integer bit mask for the permission * @param code the character to print for each active bit in the mask (see * {@link Permission#getPattern()}) */ protected AbstractPermission(int mask, char code) { this.mask = mask; this.code = code; } @Override public final boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof Permission other)) { return false; } return (this.mask == other.getMask()); } @Override public final int hashCode() { return this.mask; } @Override public final String toString() { return this.getClass().getSimpleName() + "[" + getPattern() + "=" + this.mask + "]"; } @Override public final int getMask() { return this.mask; } @Override public String getPattern() { return AclFormattingUtils.printBinary(this.mask, this.code); } }
2,189
24.465116
86
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/AclAuthorizationStrategy.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.springframework.security.acls.model.Acl; /** * Strategy used by {@link AclImpl} to determine whether a principal is permitted to call * adminstrative methods on the <code>AclImpl</code>. * * @author Ben Alex */ public interface AclAuthorizationStrategy { int CHANGE_OWNERSHIP = 0; int CHANGE_AUDITING = 1; int CHANGE_GENERAL = 2; void securityCheck(Acl acl, int changeType); }
1,081
27.473684
89
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/domain/ConsoleAuditLogger.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.domain; import org.springframework.security.acls.model.AccessControlEntry; import org.springframework.security.acls.model.AuditableAccessControlEntry; import org.springframework.util.Assert; /** * A basic implementation of {@link AuditLogger}. * * @author Ben Alex */ public class ConsoleAuditLogger implements AuditLogger { @Override public void logIfNeeded(boolean granted, AccessControlEntry ace) { Assert.notNull(ace, "AccessControlEntry required"); if (ace instanceof AuditableAccessControlEntry) { AuditableAccessControlEntry auditableAce = (AuditableAccessControlEntry) ace; if (granted && auditableAce.isAuditSuccess()) { System.out.println("GRANTED due to ACE: " + ace); } else if (!granted && auditableAce.isAuditFailure()) { System.out.println("DENIED due to ACE: " + ace); } } } }
1,502
32.4
80
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/package-info.java
/* * Copyright 2002-2016 the original author or 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 * * https://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. */ /** * Interfaces and shared classes to manage access control lists (ACLs) for domain object * instances. */ package org.springframework.security.acls.model;
783
34.636364
88
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/ObjectIdentityGenerator.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; import java.io.Serializable; /** * Strategy which creates an {@link ObjectIdentity} from an object identifier (such as a * primary key) and type information. * <p> * Differs from {@link ObjectIdentityRetrievalStrategy} in that it is used in situations * when the actual object instance isn't available. * * @author Luke Taylor * @since 3.0 */ public interface ObjectIdentityGenerator { /** * @param id the identifier of the domain object, not null * @param type the type of the object (often a class name), not null * @return the identity constructed using the supplied identifier and type * information. */ ObjectIdentity createObjectIdentity(Serializable id, String type); }
1,374
31.738095
88
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/ObjectIdentityRetrievalStrategy.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; /** * Strategy interface that provides the ability to determine which {@link ObjectIdentity} * will be returned for a particular domain object * * @author Ben Alex */ public interface ObjectIdentityRetrievalStrategy { ObjectIdentity getObjectIdentity(Object domainObject); }
960
31.033333
89
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/AclCache.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; import java.io.Serializable; import org.springframework.security.acls.jdbc.JdbcAclService; /** * A caching layer for {@link JdbcAclService}. * * @author Ben Alex */ public interface AclCache { void evictFromCache(Serializable pk); void evictFromCache(ObjectIdentity objectIdentity); MutableAcl getFromCache(ObjectIdentity objectIdentity); MutableAcl getFromCache(Serializable pk); void putInCache(MutableAcl acl); void clearCache(); }
1,131
25.325581
75
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/AuditableAcl.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; /** * A mutable ACL that provides audit capabilities. * * @author Ben Alex */ public interface AuditableAcl extends MutableAcl { void updateAuditing(int aceIndex, boolean auditSuccess, boolean auditFailure); }
894
29.862069
79
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/SidRetrievalStrategy.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; import java.util.List; import org.springframework.security.core.Authentication; /** * Strategy interface that provides an ability to determine the {@link Sid} instances * applicable for an {@link Authentication}. * * @author Ben Alex */ public interface SidRetrievalStrategy { List<Sid> getSids(Authentication authentication); }
1,016
28.911765
85
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/MutableAclService.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; /** * Provides support for creating and storing <code>Acl</code> instances. * * @author Ben Alex */ public interface MutableAclService extends AclService { /** * Creates an empty <code>Acl</code> object in the database. It will have no entries. * The returned object will then be used to add entries. * @param objectIdentity the object identity to create * @return an ACL object with its ID set * @throws AlreadyExistsException if the passed object identity already has a record */ MutableAcl createAcl(ObjectIdentity objectIdentity) throws AlreadyExistsException; /** * Removes the specified entry from the database. * @param objectIdentity the object identity to remove * @param deleteChildren whether to cascade the delete to children * @throws ChildrenExistException if the deleteChildren argument was * <code>false</code> but children exist */ void deleteAcl(ObjectIdentity objectIdentity, boolean deleteChildren) throws ChildrenExistException; /** * Changes an existing <code>Acl</code> in the database. * @param acl to modify * @throws NotFoundException if the relevant record could not be found (did you * remember to use {@link #createAcl(ObjectIdentity)} to create the object, rather * than creating it with the <code>new</code> keyword?) */ MutableAcl updateAcl(MutableAcl acl) throws NotFoundException; }
2,044
36.87037
101
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/ChildrenExistException.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; /** * Thrown if an {@link Acl} cannot be deleted because children <code>Acl</code>s exist. * * @author Ben Alex */ public class ChildrenExistException extends AclDataAccessException { /** * Constructs an <code>ChildrenExistException</code> with the specified message. * @param msg the detail message */ public ChildrenExistException(String msg) { super(msg); } /** * Constructs an <code>ChildrenExistException</code> with the specified message and * root cause. * @param msg the detail message * @param cause root cause */ public ChildrenExistException(String msg, Throwable cause) { super(msg, cause); } }
1,317
28.288889
87
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/AclDataAccessException.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; /** * Abstract base class for Acl data operations. * * @author Luke Taylor * @since 3.0 */ public abstract class AclDataAccessException extends RuntimeException { /** * Constructs an <code>AclDataAccessException</code> with the specified message and * root cause. * @param msg the detail message * @param cause the root cause */ public AclDataAccessException(String msg, Throwable cause) { super(msg, cause); } /** * Constructs an <code>AclDataAccessException</code> with the specified message and no * root cause. * @param msg the detail message */ public AclDataAccessException(String msg) { super(msg); } }
1,319
27.085106
87
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/ObjectIdentity.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; import java.io.Serializable; /** * Represents the identity of an individual domain object instance. * * <p> * As implementations of <tt>ObjectIdentity</tt> are used as the key to represent domain * objects in the ACL subsystem, it is essential that implementations provide methods so * that object-equality rather than reference-equality can be relied upon reliably. In * other words, the ACL subsystem can consider two <tt>ObjectIdentity</tt>s equal if * <tt>identity1.equals(identity2)</tt>, rather than reference-equality of * <tt>identity1==identity2</tt>. * </p> * * @author Ben Alex */ public interface ObjectIdentity extends Serializable { /** * @param obj to be compared * @return <tt>true</tt> if the objects are equal, <tt>false</tt> otherwise * @see Object#equals(Object) */ @Override boolean equals(Object obj); /** * Obtains the actual identifier. This identifier must not be reused to represent * other domain objects with the same <tt>javaType</tt>. * * <p> * Because ACLs are largely immutable, it is strongly recommended to use a synthetic * identifier (such as a database sequence number for the primary key). Do not use an * identifier with business meaning, as that business meaning may change in the future * such change will cascade to the ACL subsystem data. * </p> * @return the identifier (unique within this <tt>type</tt>; never <tt>null</tt>) */ Serializable getIdentifier(); /** * Obtains the "type" metadata for the domain object. This will often be a Java type * name (an interface or a class) &ndash; traditionally it is the name of the domain * object implementation class. * @return the "type" of the domain object (never <tt>null</tt>). */ String getType(); /** * @return a hash code representation of the <tt>ObjectIdentity</tt> * @see Object#hashCode() */ @Override int hashCode(); }
2,572
33.306667
88
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/PermissionGrantingStrategy.java
/* * Copyright 2002-2016 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; import java.util.List; /** * Allow customization of the logic for determining whether a permission or permissions * are granted to a particular sid or sids by an {@link Acl}. * * @author Luke Taylor * @since 3.0.2 */ public interface PermissionGrantingStrategy { /** * Returns true if the supplied strategy decides that the supplied {@code Acl} grants * access based on the supplied list of permissions and sids. */ boolean isGranted(Acl acl, List<Permission> permission, List<Sid> sids, boolean administrativeMode); }
1,209
31.702703
101
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/Permission.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; import java.io.Serializable; /** * Represents a permission granted to a <tt>Sid</tt> for a given domain object. * * @author Ben Alex */ public interface Permission extends Serializable { char RESERVED_ON = '~'; char RESERVED_OFF = '.'; String THIRTY_TWO_RESERVED_OFF = "................................"; /** * Returns the bits that represents the permission. * @return the bits that represent the permission */ int getMask(); /** * Returns a 32-character long bit pattern <code>String</code> representing this * permission. * <p> * Implementations are free to format the pattern as they see fit, although under no * circumstances may {@link #RESERVED_OFF} or {@link #RESERVED_ON} be used within the * pattern. An exemption is in the case of {@link #RESERVED_OFF} which is used to * denote a bit that is off (clear). Implementations may also elect to use * {@link #RESERVED_ON} internally for computation purposes, although this method may * not return any <code>String</code> containing {@link #RESERVED_ON}. * <p> * The returned String must be 32 characters in length. * <p> * This method is only used for user interface and logging purposes. It is not used in * any permission calculations. Therefore, duplication of characters within the output * is permitted. * @return a 32-character bit pattern */ String getPattern(); }
2,063
32.836066
87
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/UnloadedSidException.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; /** * Thrown if an {@link Acl} cannot perform an operation because it only loaded a subset of * <code>Sid</code>s and the caller has requested details for an unloaded <code>Sid</code> * . * * @author Ben Alex */ public class UnloadedSidException extends AclDataAccessException { /** * Constructs an <code>NotFoundException</code> with the specified message. * @param msg the detail message */ public UnloadedSidException(String msg) { super(msg); } /** * Constructs an <code>NotFoundException</code> with the specified message and root * cause. * @param msg the detail message * @param cause root cause */ public UnloadedSidException(String msg, Throwable cause) { super(msg, cause); } }
1,400
28.808511
90
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/Acl.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; import java.io.Serializable; import java.util.List; /** * Represents an access control list (ACL) for a domain object. * * <p> * An <tt>Acl</tt> represents all ACL entries for a given domain object. In order to avoid * needing references to the domain object itself, this interface handles indirection * between a domain object and an ACL object identity via the * {@link org.springframework.security.acls.model.ObjectIdentity} interface. * </p> * * <p> * Implementing classes may elect to return instances that represent * {@link org.springframework.security.acls.model.Permission} information for either some * OR all {@link org.springframework.security.acls.model.Sid} instances. Therefore, an * instance may NOT necessarily contain ALL <tt>Sid</tt>s for a given domain object. * </p> * * @author Ben Alex */ public interface Acl extends Serializable { /** * Returns all of the entries represented by the present <tt>Acl</tt>. Entries * associated with the <tt>Acl</tt> parents are not returned. * * <p> * This method is typically used for administrative purposes. * </p> * * <p> * The order that entries appear in the array is important for methods declared in the * {@link MutableAcl} interface. Furthermore, some implementations MAY use ordering as * part of advanced permission checking. * </p> * * <p> * Do <em>NOT</em> use this method for making authorization decisions. Instead use * {@link #isGranted(List, List, boolean)}. * </p> * * <p> * This method must operate correctly even if the <tt>Acl</tt> only represents a * subset of <tt>Sid</tt>s. The caller is responsible for correctly handling the * result if only a subset of <tt>Sid</tt>s is represented. * </p> * @return the list of entries represented by the <tt>Acl</tt>, or <tt>null</tt> if * there are no entries presently associated with this <tt>Acl</tt>. */ List<AccessControlEntry> getEntries(); /** * Obtains the domain object this <tt>Acl</tt> provides entries for. This is immutable * once an <tt>Acl</tt> is created. * @return the object identity (never <tt>null</tt>) */ ObjectIdentity getObjectIdentity(); /** * Determines the owner of the <tt>Acl</tt>. The meaning of ownership varies by * implementation and is unspecified. * @return the owner (may be <tt>null</tt> if the implementation does not use * ownership concepts) */ Sid getOwner(); /** * A domain object may have a parent for the purpose of ACL inheritance. If there is a * parent, its ACL can be accessed via this method. In turn, the parent's parent * (grandparent) can be accessed and so on. * * <p> * This method solely represents the presence of a navigation hierarchy between the * parent <tt>Acl</tt> and this <tt>Acl</tt>. For actual inheritance to take place, * the {@link #isEntriesInheriting()} must also be <tt>true</tt>. * </p> * * <p> * This method must operate correctly even if the <tt>Acl</tt> only represents a * subset of <tt>Sid</tt>s. The caller is responsible for correctly handling the * result if only a subset of <tt>Sid</tt>s is represented. * </p> * @return the parent <tt>Acl</tt> (may be <tt>null</tt> if this <tt>Acl</tt> does not * have a parent) */ Acl getParentAcl(); /** * Indicates whether the ACL entries from the {@link #getParentAcl()} should flow down * into the current <tt>Acl</tt>. * <p> * The mere link between an <tt>Acl</tt> and a parent <tt>Acl</tt> on its own is * insufficient to cause ACL entries to inherit down. This is because a domain object * may wish to have entirely independent entries, but maintain the link with the * parent for navigation purposes. Thus, this method denotes whether or not the * navigation relationship also extends to the actual inheritance of entries. * </p> * @return <tt>true</tt> if parent ACL entries inherit into the current <tt>Acl</tt> */ boolean isEntriesInheriting(); /** * This is the actual authorization logic method, and must be used whenever ACL * authorization decisions are required. * * <p> * An array of <tt>Sid</tt>s are presented, representing security identifies of the * current principal. In addition, an array of <tt>Permission</tt>s is presented which * will have one or more bits set in order to indicate the permissions needed for an * affirmative authorization decision. An array is presented because holding * <em>any</em> of the <tt>Permission</tt>s inside the array will be sufficient for an * affirmative authorization. * </p> * * <p> * The actual approach used to make authorization decisions is left to the * implementation and is not specified by this interface. For example, an * implementation <em>MAY</em> search the current ACL in the order the ACL entries * have been stored. If a single entry is found that has the same active bits as are * shown in a passed <tt>Permission</tt>, that entry's grant or deny state may * determine the authorization decision. If the case of a deny state, the deny * decision will only be relevant if all other <tt>Permission</tt>s passed in the * array have also been unsuccessfully searched. If no entry is found that match the * bits in the current ACL, provided that {@link #isEntriesInheriting()} is * <tt>true</tt>, the authorization decision may be passed to the parent ACL. If there * is no matching entry, the implementation MAY throw an exception, or make a * predefined authorization decision. * </p> * * <p> * This method must operate correctly even if the <tt>Acl</tt> only represents a * subset of <tt>Sid</tt>s, although the implementation is permitted to throw one of * the signature-defined exceptions if the method is called requesting an * authorization decision for a {@link Sid} that was never loaded in this <tt>Acl</tt> * . * </p> * @param permission the permission or permissions required (at least one entry * required) * @param sids the security identities held by the principal (at least one entry * required) * @param administrativeMode if <tt>true</tt> denotes the query is for administrative * purposes and no logging or auditing (if supported by the implementation) should be * undertaken * @return <tt>true</tt> if authorization is granted * @throws NotFoundException MUST be thrown if an implementation cannot make an * authoritative authorization decision, usually because there is no ACL information * for this particular permission and/or SID * @throws UnloadedSidException thrown if the <tt>Acl</tt> does not have details for * one or more of the <tt>Sid</tt>s passed as arguments */ boolean isGranted(List<Permission> permission, List<Sid> sids, boolean administrativeMode) throws NotFoundException, UnloadedSidException; /** * For efficiency reasons an <tt>Acl</tt> may be loaded and <em>not</em> contain * entries for every <tt>Sid</tt> in the system. If an <tt>Acl</tt> has been loaded * and does not represent every <tt>Sid</tt>, all methods of the <tt>Acl</tt> can only * be used within the limited scope of the <tt>Sid</tt> instances it actually * represents. * <p> * It is normal to load an <tt>Acl</tt> for only particular <tt>Sid</tt>s if read-only * authorization decisions are being made. However, if user interface reporting or * modification of <tt>Acl</tt>s are desired, an <tt>Acl</tt> should be loaded with * all <tt>Sid</tt>s. This method denotes whether or not the specified <tt>Sid</tt>s * have been loaded or not. * </p> * @param sids one or more security identities the caller is interest in knowing * whether this <tt>Sid</tt> supports * @return <tt>true</tt> if every passed <tt>Sid</tt> is represented by this * <tt>Acl</tt> instance */ boolean isSidLoaded(List<Sid> sids); }
8,508
42.635897
91
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/OwnershipAcl.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; /** * A mutable ACL that provides ownership capabilities. * * <p> * Generally the owner of an ACL is able to call any ACL mutator method, as well as assign * a new owner. * * @author Ben Alex */ public interface OwnershipAcl extends MutableAcl { @Override void setOwner(Sid newOwner); }
976
27.735294
90
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/NotFoundException.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; /** * Thrown if an ACL-related object cannot be found. * * @author Ben Alex */ public class NotFoundException extends AclDataAccessException { /** * Constructs an <code>NotFoundException</code> with the specified message. * @param msg the detail message */ public NotFoundException(String msg) { super(msg); } /** * Constructs an <code>NotFoundException</code> with the specified message and root * cause. * @param msg the detail message * @param cause root cause */ public NotFoundException(String msg, Throwable cause) { super(msg, cause); } }
1,256
26.933333
84
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/AccessControlEntry.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; import java.io.Serializable; /** * Represents an individual permission assignment within an {@link Acl}. * * <p> * Instances MUST be immutable, as they are returned by <code>Acl</code> and should not * allow client modification. * </p> * * @author Ben Alex */ public interface AccessControlEntry extends Serializable { Acl getAcl(); /** * Obtains an identifier that represents this ACE. * @return the identifier, or <code>null</code> if unsaved */ Serializable getId(); Permission getPermission(); Sid getSid(); /** * Indicates the permission is being granted to the relevant Sid. If false, indicates * the permission is being revoked/blocked. * @return true if being granted, false otherwise */ boolean isGranting(); }
1,434
26.075472
87
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/AclService.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; import java.util.List; import java.util.Map; /** * Provides retrieval of {@link Acl} instances. * * @author Ben Alex */ public interface AclService { /** * Locates all object identities that use the specified parent. This is useful for * administration tools. * @param parentIdentity to locate children of * @return the children (or <tt>null</tt> if none were found) */ List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity); /** * Same as {@link #readAclsById(List)} except it returns only a single Acl. * <p> * This method should not be called as it does not leverage the underlying * implementation's potential ability to filter <tt>Acl</tt> entries based on a * {@link Sid} parameter. * </p> * @param object to locate an {@link Acl} for * @return the {@link Acl} for the requested {@link ObjectIdentity} (never * <tt>null</tt>) * @throws NotFoundException if an {@link Acl} was not found for the requested * {@link ObjectIdentity} */ Acl readAclById(ObjectIdentity object) throws NotFoundException; /** * Same as {@link #readAclsById(List, List)} except it returns only a single Acl. * @param object to locate an {@link Acl} for * @param sids the security identities for which {@link Acl} information is required * (may be <tt>null</tt> to denote all entries) * @return the {@link Acl} for the requested {@link ObjectIdentity} (never * <tt>null</tt>) * @throws NotFoundException if an {@link Acl} was not found for the requested * {@link ObjectIdentity} */ Acl readAclById(ObjectIdentity object, List<Sid> sids) throws NotFoundException; /** * Obtains all the <tt>Acl</tt>s that apply for the passed <tt>Object</tt>s. * <p> * The returned map is keyed on the passed objects, with the values being the * <tt>Acl</tt> instances. Any unknown objects will not have a map key. * </p> * @param objects the objects to find {@link Acl} information for * @return a map with exactly one element for each {@link ObjectIdentity} passed as an * argument (never <tt>null</tt>) * @throws NotFoundException if an {@link Acl} was not found for each requested * {@link ObjectIdentity} */ Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects) throws NotFoundException; /** * Obtains all the <tt>Acl</tt>s that apply for the passed <tt>Object</tt>s, but only * for the security identifies passed. * <p> * Implementations <em>MAY</em> provide a subset of the ACLs via this method although * this is NOT a requirement. This is intended to allow performance optimisations * within implementations. Callers should therefore use this method in preference to * the alternative overloaded version which does not have performance optimisation * opportunities. * </p> * <p> * The returned map is keyed on the passed objects, with the values being the * <tt>Acl</tt> instances. Any unknown objects (or objects for which the interested * <tt>Sid</tt>s do not have entries) will not have a map key. * </p> * @param objects the objects to find {@link Acl} information for * @param sids the security identities for which {@link Acl} information is required * (may be <tt>null</tt> to denote all entries) * @return a map with exactly one element for each {@link ObjectIdentity} passed as an * argument (never <tt>null</tt>) * @throws NotFoundException if an {@link Acl} was not found for each requested * {@link ObjectIdentity} */ Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) throws NotFoundException; }
4,252
39.894231
110
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/MutableAcl.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; import java.io.Serializable; /** * A mutable <tt>Acl</tt>. * <p> * A mutable ACL must ensure that appropriate security checks are performed before * allowing access to its methods. * * @author Ben Alex */ public interface MutableAcl extends Acl { void deleteAce(int aceIndex) throws NotFoundException; /** * Obtains an identifier that represents this <tt>MutableAcl</tt>. * @return the identifier, or <tt>null</tt> if unsaved */ Serializable getId(); void insertAce(int atIndexLocation, Permission permission, Sid sid, boolean granting) throws NotFoundException; /** * Changes the present owner to a different owner. * @param newOwner the new owner (mandatory; cannot be null) */ void setOwner(Sid newOwner); /** * Change the value returned by {@link Acl#isEntriesInheriting()}. * @param entriesInheriting the new value */ void setEntriesInheriting(boolean entriesInheriting); /** * Changes the parent of this ACL. * @param newParent the new parent */ void setParent(Acl newParent); void updateAce(int aceIndex, Permission permission) throws NotFoundException; }
1,791
27.903226
112
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/AlreadyExistsException.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; /** * Thrown if an <code>Acl</code> entry already exists for the object. * * @author Ben Alex */ public class AlreadyExistsException extends AclDataAccessException { /** * Constructs an <code>AlreadyExistsException</code> with the specified message. * @param msg the detail message */ public AlreadyExistsException(String msg) { super(msg); } /** * Constructs an <code>AlreadyExistsException</code> with the specified message and * root cause. * @param msg the detail message * @param cause root cause */ public AlreadyExistsException(String msg, Throwable cause) { super(msg, cause); } }
1,299
27.888889
84
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/Sid.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; import java.io.Serializable; /** * A security identity recognised by the ACL system. * * <p> * This interface provides indirection between actual security objects (eg principals, * roles, groups etc) and what is stored inside an <code>Acl</code>. This is because an * <code>Acl</code> will not store an entire security object, but only an abstraction of * it. This interface therefore provides a simple way to compare these abstracted security * identities with other security identities and actual security objects. * </p> * * @author Ben Alex */ public interface Sid extends Serializable { /** * Refer to the <code>java.lang.Object</code> documentation for the interface * contract. * @param obj to be compared * @return <code>true</code> if the objects are equal, <code>false</code> otherwise */ @Override boolean equals(Object obj); /** * Refer to the <code>java.lang.Object</code> documentation for the interface * contract. * @return a hash code representation of this object */ @Override int hashCode(); }
1,730
31.055556
90
java
null
spring-security-main/acl/src/main/java/org/springframework/security/acls/model/AuditableAccessControlEntry.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.model; /** * Represents an ACE that provides auditing information. * * @author Ben Alex */ public interface AuditableAccessControlEntry extends AccessControlEntry { boolean isAuditFailure(); boolean isAuditSuccess(); }
898
28
75
java
null
OPAM-main/PriorityAssignment/src/test/java/lu/uni/svv/PriorityAssignment/CoEvolveStarterTest.java
package lu.uni.svv.PriorityAssignment; import junit.framework.TestCase; import lu.uni.svv.PriorityAssignment.task.TaskDescriptor; import lu.uni.svv.PriorityAssignment.utils.Settings; import org.uma.jmetal.util.JMetalLogger; public class CoEvolveStarterTest extends TestCase { public void testGetPrioritiesFromInput() throws Exception { // Environment Settings Initializer.initLogger(); String[] args = new String[0]; Settings.update(args); // load input TaskDescriptor[] input = TaskDescriptor.loadFromCSV(Settings.INPUT_FILE, Settings.TIME_MAX, Settings.TIME_QUANTA); // update dynamic settings Initializer.updateSettings(input); // convert settings' time unit Initializer.convertTimeUnit(Settings.TIME_QUANTA); // create engineer's priority assignment Integer[] prioritiy = null; if (!Settings.RANDOM_PRIORITY) { prioritiy = CoEvolveStarter.getPrioritiesFromInput(input); } JMetalLogger.logger.info("Initialized program"); } }
980
28.727273
116
java
null
OPAM-main/PriorityAssignment/src/test/java/lu/uni/svv/PriorityAssignment/scheduler/RTSchedulerTest.java
package lu.uni.svv.PriorityAssignment.scheduler; import junit.framework.TestCase; import lu.uni.svv.PriorityAssignment.CoEvolveStarter; import lu.uni.svv.PriorityAssignment.Initializer; import lu.uni.svv.PriorityAssignment.task.Task; import lu.uni.svv.PriorityAssignment.task.TaskDescriptor; import lu.uni.svv.PriorityAssignment.task.TaskState; import lu.uni.svv.PriorityAssignment.utils.GAWriter; import lu.uni.svv.PriorityAssignment.utils.Settings; import java.util.PriorityQueue; import java.util.Random; public class RTSchedulerTest extends TestCase { /** * Test with Periodic tasks * No deadline misses */ public void testSchedulePriority() throws Exception { Random rand = new Random(); // Environment Settings Initializer.initLogger(); TaskDescriptor[] tasks = TaskDescriptor.loadFromCSV("../res/industrial/CCS.csv", 0, 1); Integer[] priorities = CoEvolveStarter.getPrioritiesFromInput(tasks); // prepare ready queue RTScheduler scheduler = new RTScheduler(tasks, 250); PriorityQueue<Task> readyQueue = new PriorityQueue<Task>(60000, scheduler.queueComparator); int[] executionIndex = new int[tasks.length]; int currentTime=0; for (int x=0; x<10; x++){ int taskIdx = rand.nextInt(tasks.length); TaskDescriptor taskDesc = tasks[taskIdx]; int priority = priorities[taskIdx]; Task t = new Task(taskDesc.ID, executionIndex[taskIdx], taskDesc.WCET, currentTime, currentTime + taskDesc.Deadline, priority, taskDesc.Severity); t.updateTaskState(TaskState.Ready, currentTime); readyQueue.add(t); executionIndex[taskIdx]++; } while (!readyQueue.isEmpty()) { Task t = readyQueue.poll(); System.out.println(String.format("ID: %d, priority: %d, exID: %d", t.ID, t.Priority, t.ExecutionID)); } } }
1,789
30.403509
149
java
null
OPAM-main/PriorityAssignment/src/test/java/lu/uni/svv/PriorityAssignment/scheduler/ScheduleTest.java
package lu.uni.svv.PriorityAssignment.scheduler; import junit.framework.TestCase; import lu.uni.svv.PriorityAssignment.arrivals.ArrivalProblem; import lu.uni.svv.PriorityAssignment.arrivals.Arrivals; import lu.uni.svv.PriorityAssignment.arrivals.ArrivalsSolution; import lu.uni.svv.PriorityAssignment.task.TaskDescriptor; import lu.uni.svv.PriorityAssignment.utils.GAWriter; import lu.uni.svv.PriorityAssignment.utils.RandomGenerator; import lu.uni.svv.PriorityAssignment.utils.Settings; import org.json.simple.JSONArray; import org.json.simple.parser.JSONParser; import java.io.FileReader; import java.util.ArrayList; import java.util.List; public class ScheduleTest extends TestCase { /** * Test with Periodic tasks * No deadline misses */ public void testScheduleLoad() throws Exception { // Environment Settings GAWriter.setBasePath("../results/TEST_T"); Schedule[][] schedules = Schedule.loadSchedules("../results/TEST_T/_schedules/phase2_sol1_arr0.json"); Schedule.printSchedules("_schedules/phase2_sol1_arr0_copy.json", schedules); } public void testScheduleVerify() throws Exception { // Environment Settings String path = "../results/TestScheduler7"; GAWriter.setBasePath(path); // variables int solID = 11; int priorityID = 3; // load task descriptions TaskDescriptor[] Tasks = TaskDescriptor.loadFromCSV(path+"/input.csv", 3600000,1); // load schedules Schedule[][] schedules = Schedule.loadSchedules(String.format("%s/_schedules2/phase1_sol%d_prio%d.json", path, solID, priorityID)); // load task priorities Integer[] priorities = loadPriority(String.format("%s/_priorities2/phase1_sol%d_prio%d.json", path, solID, priorityID)); new ScheduleVerify(schedules, Tasks, priorities).verify(); } public void testScheduler() throws Exception { // Environment Settings String path = "../results/TestSchedulerTest"; // GAWriter.setBasePath(path); // variables int solID = 18; int priorityID = 0; // load task descriptions TaskDescriptor[] Tasks = TaskDescriptor.loadFromCSV(path+"/input.csv", 3600000,1); int simulationTime = getSimulationTime(Tasks); // load task priorities String filename = String.format("%s/_arrivals2/phase1_sol%d_prio%d.json", path, solID, priorityID); ArrivalProblem problemA = new ArrivalProblem(Tasks, null, simulationTime, "SQMScheduler"); ArrivalsSolution solution = ArrivalsSolution.loadFromJSON(problemA, filename); Arrivals[] arrivals = solution.toArray(); // load task priorities Integer[] priorities = loadPriority(String.format("%s/_priorities2/phase1_sol%d_prio%d.json", path, solID, priorityID)); // scheduling SQMScheduler scheduler = new SQMScheduler(Tasks, simulationTime); scheduler.run(arrivals, priorities); // load arrivals Schedule[][] schedules = scheduler.getResult(); filename = String.format("%s/_schedules3/phase1_sol%d_prio%d.json", path, solID, priorityID); Schedule.printSchedules(filename, schedules); new ScheduleVerify(schedules, Tasks, priorities, arrivals).verify(); } /** * * @param _filename * @return * @throws Exception */ public Integer[] loadPriority(String _filename) throws Exception { Integer[] priorities = null; // load task priorities FileReader reader = new FileReader(_filename); JSONParser parser = new JSONParser(); JSONArray json = (JSONArray) parser.parse(reader); priorities = new Integer[json.size()]; for (int t = 0; t < json.size(); t++) { priorities[t] = ((Long) json.get(t)).intValue(); } return priorities; } /** * * @param input * @return */ public int getSimulationTime(TaskDescriptor[] input){ long[] periodArray = new long[input.length]; for(int x=0; x<input.length; x++){ periodArray[x] = input[x].Period; } int time = (int) RTScheduler.lcm(periodArray); return time; } }
3,864
30.169355
133
java
null
OPAM-main/PriorityAssignment/src/test/java/lu/uni/svv/PriorityAssignment/priority/ConstrantsEvaluatorTest.java
package lu.uni.svv.PriorityAssignment.priority; import junit.framework.TestCase; import lu.uni.svv.PriorityAssignment.arrivals.ArrivalsSolution; import lu.uni.svv.PriorityAssignment.scheduler.RTScheduler; import lu.uni.svv.PriorityAssignment.task.TaskDescriptor; import lu.uni.svv.PriorityAssignment.utils.Settings; import org.uma.jmetal.util.JMetalLogger; public class ConstrantsEvaluatorTest extends TestCase { public PriorityProblem problem; public void init() throws Exception { // Environment Settings Settings.update(new String[] {}); Settings.INPUT_FILE = "res/industrial/CCS.csv"; Settings.BASE_PATH = "results/TEST/CCS"; Settings.TIME_MAX = 0; Settings.TIME_QUANTA = 1; Settings.CYCLE_NUM = 2; Settings.P1_ITERATION = 10; Settings.P2_GROUP_FITNESS = "average"; // load input TaskDescriptor[] input = TaskDescriptor.loadFromCSV(Settings.INPUT_FILE, Settings.TIME_MAX, Settings.TIME_QUANTA); // Set SIMULATION_TIME int simulationTime = 0; if (Settings.TIME_MAX == 0) { long[] periodArray = new long[input.length]; for(int x=0; x<input.length; x++){ periodArray[x] = input[x].Period; } simulationTime = (int) RTScheduler.lcm(periodArray); if (simulationTime<0) { System.out.println("Cannot calculate simulation time"); return; } } else{ simulationTime = (int) (Settings.TIME_MAX * (1/Settings.TIME_QUANTA)); if (Settings.EXTEND_SIMULATION_TIME) { long max_deadline = TaskDescriptor.findMaximumDeadline(input); simulationTime += max_deadline; } } Settings.TIME_MAX = simulationTime; // update specifit options if (Settings.P2_MUTATION_PROB==0) Settings.P2_MUTATION_PROB = 1.0/input.length; // initialze static objects ArrivalsSolution.initUUID(); PrioritySolution.initUUID(); this.problem = new PriorityProblem(input, simulationTime, Settings.SCHEDULER); JMetalLogger.logger.info("Initialized program"); } public void testCalculate() throws Exception { init(); // test for the worst case PrioritySolution solution = new PrioritySolution(problem, new Integer[]{10,9,8,7,6,5,4,3,2,1,0}); double value = ConstrantsEvaluator.calculate(solution, problem.Tasks); System.out.printf("priorities: %s, calculate value: %.4f\n", solution.getVariablesString(), value); // test for the best case solution = new PrioritySolution(problem, new Integer[]{0,1,2,3,4,5,6,7,8,9,10}); value = ConstrantsEvaluator.calculate(solution, problem.Tasks); System.out.printf("priorities: %s, calculate value: %.4f\n", solution.getVariablesString(), value); // test for the near best case solution = new PrioritySolution(problem, new Integer[]{0,1,4,3,2,5,6,7,8,9,10}); value = ConstrantsEvaluator.calculate(solution, problem.Tasks); System.out.printf("priorities: %s, calculate value: %.4f\n", solution.getVariablesString(), value); // test for the middle cases for (int i=0; i<10; i++){ solution = problem.createSolution(); value = ConstrantsEvaluator.calculate(solution, problem.Tasks); System.out.printf("priorities: %s, calculate value: %.4f\n", solution.getVariablesString(), value); } } }
3,569
39.11236
122
java
null
OPAM-main/PriorityAssignment/src/test/java/lu/uni/svv/PriorityAssignment/priority/PrioritySolutionEvaluatorTest.java
package lu.uni.svv.PriorityAssignment.priority; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; import lu.uni.svv.PriorityAssignment.arrivals.ArrivalProblem; import lu.uni.svv.PriorityAssignment.arrivals.Arrivals; import lu.uni.svv.PriorityAssignment.arrivals.ArrivalsSolution; import lu.uni.svv.PriorityAssignment.scheduler.RTScheduler; import lu.uni.svv.PriorityAssignment.task.TaskDescriptor; import lu.uni.svv.PriorityAssignment.utils.Settings; import org.uma.jmetal.util.JMetalLogger; public class PrioritySolutionEvaluatorTest extends TestCase { TaskDescriptor[] input; int simulationTime = 0; public void init() throws Exception{ // Environment Settings Settings.update(new String[] {}); Settings.INPUT_FILE = "res/industrial/GAP.csv"; Settings.BASE_PATH = "results/TEST/GAP"; Settings.TIME_MAX = 0; Settings.TIME_QUANTA = 1; Settings.CYCLE_NUM = 3; Settings.P1_ITERATION = 10; Settings.P2_GROUP_FITNESS = "average"; // load input input = TaskDescriptor.loadFromCSV(Settings.INPUT_FILE, Settings.TIME_MAX, Settings.TIME_QUANTA); // Set SIMULATION_TIME simulationTime = 0; if (Settings.TIME_MAX == 0) { long[] periodArray = new long[input.length]; for(int x=0; x<input.length; x++){ periodArray[x] = input[x].Period; } simulationTime = (int) RTScheduler.lcm(periodArray); if (simulationTime<0) { System.out.println("Cannot calculate simulation time"); return; } } else{ simulationTime = (int) (Settings.TIME_MAX * (1/Settings.TIME_QUANTA)); if (Settings.EXTEND_SIMULATION_TIME) { long max_deadline = TaskDescriptor.findMaximumDeadline(input); simulationTime += max_deadline; } } Settings.TIME_MAX = simulationTime; // update specifit options if (Settings.P2_MUTATION_PROB==0) Settings.P2_MUTATION_PROB = 1.0/input.length; // initialze static objects ArrivalsSolution.initUUID(); PrioritySolution.initUUID(); JMetalLogger.logger.info("Initialized program"); } public void testEvaluateSolution() throws Exception{ init(); PriorityProblem problemP = new PriorityProblem(input, simulationTime, Settings.SCHEDULER); List<PrioritySolution> P = createInitialPriorities(Settings.P2_POPULATION, null, problemP); List<Integer[]> priorities = PrioritySolution.toArrays(P); ArrivalProblem problemA = new ArrivalProblem(input, priorities, simulationTime, Settings.SCHEDULER); List<ArrivalsSolution> A = createInitialArrivals(problemA, Settings.P1_POPULATION); List<Arrivals[]> arrivals = ArrivalsSolution.toArrays(A); PrioritySolutionEvaluator evaluator = new PrioritySolutionEvaluator(arrivals, arrivals); evaluator.evaluateSolution(problemP, P.get(0), arrivals, false, false,0); } public List<PrioritySolution> createInitialPriorities(int maxPopulation, Integer[] priorityEngineer, PriorityProblem problem) { List<PrioritySolution> population = new ArrayList<>(maxPopulation); PrioritySolution individual; for (int i = 0; i < maxPopulation; i++) { if (i==0 && priorityEngineer!=null){ individual = new PrioritySolution(problem, priorityEngineer); } else { individual = new PrioritySolution(problem); } population.add(individual); } return population; } public List<ArrivalsSolution> createInitialArrivals(ArrivalProblem _problem, int n){ List<ArrivalsSolution> A = new ArrayList<>(); for (int i=0; i<n; i++){ A.add(new ArrivalsSolution(_problem)); } return A; } }
3,516
30.972727
128
java
null
OPAM-main/PriorityAssignment/src/test/java/lu/uni/svv/PriorityAssignment/task/TaskDescriptorTest.java
package lu.uni.svv.PriorityAssignment.task; import junit.framework.TestCase; import lu.uni.svv.PriorityAssignment.priority.PriorityProblem; import lu.uni.svv.PriorityAssignment.scheduler.RTScheduler; import lu.uni.svv.PriorityAssignment.utils.GAWriter; import lu.uni.svv.PriorityAssignment.utils.Settings; public class TaskDescriptorTest extends TestCase { /** * Test with Periodic tasks * No deadline misses */ public void testMinMaxFitness() throws Exception { System.out.println("Working Directory = " + System.getProperty("user.dir")); // Environment Settings Settings.update(new String[]{}); // load input TaskDescriptor[] input = TaskDescriptor.loadFromCSV(Settings.INPUT_FILE, Settings.TIME_MAX, Settings.TIME_QUANTA); // Set SIMULATION_TIME int simulationTime = 0; if (Settings.TIME_MAX == 0) { long[] periodArray = new long[input.length]; for(int x=0; x<input.length; x++){ periodArray[x] = input[x].Period; } simulationTime = (int) RTScheduler.lcm(periodArray); if (simulationTime<0) { System.out.println("Cannot calculate simulation time"); return; } } else{ simulationTime = (int) (Settings.TIME_MAX * (1/Settings.TIME_QUANTA)); if (Settings.EXTEND_SIMULATION_TIME) { long max_deadline = TaskDescriptor.findMaximumDeadline(input); simulationTime += max_deadline; } } Settings.TIME_MAX = simulationTime; // update specifit options if (Settings.P2_MUTATION_PROB==0) Settings.P2_MUTATION_PROB = 1.0/input.length; PriorityProblem p = new PriorityProblem(input, simulationTime, Settings.SCHEDULER); Double[] range1 = p.getFitnessRange(0); Double[] range2 = p.getFitnessRange(1); System.out.println(String.format("[1] min fitness: %e, max fitness: %e", range1[0], range1[1])); System.out.println(String.format("[2] min fitness: %f, max fitness: %f", range2[0], range2[1])); } }
1,897
32.892857
116
java
null
OPAM-main/PriorityAssignment/src/test/java/lu/uni/svv/PriorityAssignment/analysis/IndicatorsTest.java
package lu.uni.svv.PriorityAssignment.analysis; import junit.framework.TestCase; import org.uma.jmetal.qualityindicator.impl.GenerationalDistance; import org.uma.jmetal.util.front.imp.ArrayFront; import org.uma.jmetal.util.point.PointSolution; import java.util.ArrayList; import java.util.List; public class IndicatorsTest extends TestCase { public PointSolution makePointSolution(int a, int b){ // put point info PointSolution sol = new PointSolution(2); sol.setObjective(0, a); sol.setObjective(1, b); return sol; } public void testEvaluateGDP() { List<PointSolution> A = new ArrayList<PointSolution>(); A.add(makePointSolution(2,5)); List<PointSolution> B = new ArrayList<PointSolution>(); B.add(makePointSolution(3,9)); //reference pareto front List<PointSolution> ref = new ArrayList<PointSolution>(); ref.add(makePointSolution(1,0)); ref.add(makePointSolution(0,10)); ArrayFront refFront = new ArrayFront(ref); //calculate GD+ GenerationalDistance<PointSolution> gd = new GenerationalDistance<>(refFront); double dist = gd.evaluate(A); System.out.printf("%s for A: %.5f\n", gd.getName(), dist*dist); dist = gd.evaluate(B); System.out.printf("%s for B: %.5f\n\n", gd.getName(), dist*dist); //calculate GD+ GenerationalDistancePlus<PointSolution> gdp = new GenerationalDistancePlus<>(refFront); dist = gdp.evaluate(A); System.out.printf("%s for A: %.5f\n", gdp.getName(), dist*dist); dist = gdp.evaluate(B); System.out.printf("%s for B: %.5f\n", gdp.getName(), dist*dist); } public void testEvaluateCI() { List<PointSolution> A = new ArrayList<PointSolution>(); A.add(makePointSolution(4,2)); A.add(makePointSolution(3,3)); A.add(makePointSolution(4,2)); A.add(makePointSolution(3,3)); List<PointSolution> B = new ArrayList<PointSolution>(); B.add(makePointSolution(5,1)); B.add(makePointSolution(4,2)); B.add(makePointSolution(3,3)); B.add(makePointSolution(2,4)); B.add(makePointSolution(1,5)); List<PointSolution> C = new ArrayList<PointSolution>(); C.add(makePointSolution(4,3)); C.add(makePointSolution(2,5)); List<PointSolution> D = new ArrayList<PointSolution>(); D.add(makePointSolution(3,3)); D.add(makePointSolution(3,3)); D.add(makePointSolution(3,3)); List<PointSolution> E = new ArrayList<PointSolution>(); E.add(makePointSolution(4,4)); E.add(makePointSolution(4,4)); E.add(makePointSolution(4,4)); List<PointSolution> F = new ArrayList<PointSolution>(); F.add(makePointSolution(6,2)); F.add(makePointSolution(5,3)); F.add(makePointSolution(4,4)); //reference pareto front List<PointSolution> ref = new ArrayList<PointSolution>(); ref.add(makePointSolution(5,1)); ref.add(makePointSolution(4,2)); ref.add(makePointSolution(3,3)); ref.add(makePointSolution(2,4)); ref.add(makePointSolution(1,5)); ArrayFront refFront = new ArrayFront(ref); //calculate CI ContributionIndicator<PointSolution> contributionIndicator = new ContributionIndicator<>(refFront); System.out.printf("%s for A: %.5f\n", contributionIndicator.getName(), contributionIndicator.evaluate(A)); System.out.printf("%s for B: %.5f\n", contributionIndicator.getName(), contributionIndicator.evaluate(B)); System.out.printf("%s for C: %.5f\n", contributionIndicator.getName(), contributionIndicator.evaluate(C)); System.out.printf("%s for D: %.5f\n", contributionIndicator.getName(), contributionIndicator.evaluate(D)); System.out.printf("%s for E: %.5f\n", contributionIndicator.getName(), contributionIndicator.evaluate(E)); System.out.printf("%s for F: %.5f\n", contributionIndicator.getName(), contributionIndicator.evaluate(F)); //calculate CI ArrayFront test = new ArrayFront(C); contributionIndicator = new ContributionIndicator<>(test); System.out.printf("\n%s for ref/C: %.5f\n", contributionIndicator.getName(), contributionIndicator.evaluate(ref)); } public void testEvaluateC() { List<PointSolution> A = new ArrayList<PointSolution>(); A.add(makePointSolution(4,2)); A.add(makePointSolution(3,3)); A.add(makePointSolution(4,2)); A.add(makePointSolution(3,3)); List<PointSolution> B = new ArrayList<PointSolution>(); B.add(makePointSolution(5,1)); B.add(makePointSolution(4,2)); B.add(makePointSolution(3,3)); B.add(makePointSolution(2,4)); B.add(makePointSolution(1,5)); List<PointSolution> C = new ArrayList<PointSolution>(); C.add(makePointSolution(4,3)); C.add(makePointSolution(2,5)); List<PointSolution> D = new ArrayList<PointSolution>(); D.add(makePointSolution(3,3)); D.add(makePointSolution(3,3)); D.add(makePointSolution(3,3)); List<PointSolution> E = new ArrayList<PointSolution>(); E.add(makePointSolution(4,4)); E.add(makePointSolution(4,4)); E.add(makePointSolution(4,4)); List<PointSolution> F = new ArrayList<PointSolution>(); F.add(makePointSolution(6,2)); F.add(makePointSolution(5,3)); F.add(makePointSolution(4,4)); //reference pareto front List<PointSolution> ref = new ArrayList<PointSolution>(); ref.add(makePointSolution(5,1)); ref.add(makePointSolution(4,2)); ref.add(makePointSolution(3,3)); ref.add(makePointSolution(3,3)); ref.add(makePointSolution(2,4)); ref.add(makePointSolution(1,5)); ArrayFront refFront = new ArrayFront(ref); //calculate CS CoverageIndicator<PointSolution> qi = new CoverageIndicator<>(refFront, false); System.out.printf("%s for A: %.5f\n", qi.getName(), qi.evaluate(A)); System.out.printf("%s for B: %.5f\n", qi.getName(), qi.evaluate(B)); System.out.printf("%s for C: %.5f\n", qi.getName(), qi.evaluate(C)); System.out.printf("%s for D: %.5f\n", qi.getName(), qi.evaluate(D)); System.out.printf("%s for E: %.5f\n", qi.getName(), qi.evaluate(E)); System.out.printf("%s for F: %.5f\n", qi.getName(), qi.evaluate(F)); //calculate CS reverse ArrayFront test = new ArrayFront(C); qi = new CoverageIndicator<>(test, false); System.out.printf("\n%s for ref/C: %.5f\n", qi.getName(), qi.evaluate(ref)); } public void testEvaluateUNFS() { List<PointSolution> A = new ArrayList<PointSolution>(); A.add(makePointSolution(4,2)); A.add(makePointSolution(3,3)); A.add(makePointSolution(4,2)); A.add(makePointSolution(3,3)); List<PointSolution> B = new ArrayList<PointSolution>(); B.add(makePointSolution(5,1)); B.add(makePointSolution(4,2)); B.add(makePointSolution(3,3)); B.add(makePointSolution(2,4)); B.add(makePointSolution(1,5)); List<PointSolution> C = new ArrayList<PointSolution>(); C.add(makePointSolution(4,3)); C.add(makePointSolution(2,5)); List<PointSolution> D = new ArrayList<PointSolution>(); D.add(makePointSolution(3,3)); D.add(makePointSolution(3,3)); D.add(makePointSolution(3,3)); List<PointSolution> E = new ArrayList<PointSolution>(); E.add(makePointSolution(4,4)); E.add(makePointSolution(4,4)); E.add(makePointSolution(4,4)); List<PointSolution> F = new ArrayList<PointSolution>(); F.add(makePointSolution(6,2)); F.add(makePointSolution(5,3)); F.add(makePointSolution(4,4)); //reference pareto front List<PointSolution> ref = new ArrayList<PointSolution>(); ref.add(makePointSolution(5,1)); ref.add(makePointSolution(4,2)); ref.add(makePointSolution(3,3)); ref.add(makePointSolution(2,4)); ref.add(makePointSolution(1,5)); ArrayFront refFront = new ArrayFront(ref); UniqueNondominatedFrontRatio<PointSolution> unfr = new UniqueNondominatedFrontRatio<>(refFront); System.out.printf("%s for A: %.5f\n", unfr.getName(), unfr.evaluate(A)); System.out.printf("%s for B: %.5f\n", unfr.getName(), unfr.evaluate(B)); System.out.printf("%s for C: %.5f\n", unfr.getName(), unfr.evaluate(C)); System.out.printf("%s for D: %.5f\n", unfr.getName(), unfr.evaluate(D)); System.out.printf("%s for E: %.5f\n", unfr.getName(), unfr.evaluate(E)); System.out.printf("%s for F: %.5f\n", unfr.getName(), unfr.evaluate(F)); } public void testEvaluateSpacing() { List<PointSolution> A = new ArrayList<PointSolution>(); A.add(makePointSolution(3,3)); A.add(makePointSolution(3,3)); A.add(makePointSolution(3,3)); A.add(makePointSolution(3,3)); List<PointSolution> B = new ArrayList<PointSolution>(); B.add(makePointSolution(5,1)); B.add(makePointSolution(4,2)); B.add(makePointSolution(3,3)); B.add(makePointSolution(2,4)); B.add(makePointSolution(1,5)); List<PointSolution> C = new ArrayList<PointSolution>(); C.add(makePointSolution(1,10)); C.add(makePointSolution(2,9)); C.add(makePointSolution(7,7)); C.add(makePointSolution(8,8)); C.add(makePointSolution(10,3)); List<PointSolution> D = new ArrayList<PointSolution>(); D.add(makePointSolution(1,10)); D.add(makePointSolution(2,9)); D.add(makePointSolution(7,7)); D.add(makePointSolution(8,8)); D.add(makePointSolution(10,3)); Spacing<PointSolution> sp = new Spacing<>(); System.out.printf("%s for A: %.5f\n", sp.getName(), sp.evaluate(A)); System.out.printf("%s for B: %.5f\n", sp.getName(), sp.evaluate(B)); System.out.printf("%s for C: %.5f\n", sp.getName(), sp.evaluate(C)); } public void testDominate() { List<PointSolution> D = new ArrayList<PointSolution>(); D.add(makePointSolution(3,3)); D.add(makePointSolution(3,3)); D.add(makePointSolution(3,3)); List<PointSolution> E = new ArrayList<PointSolution>(); E.add(makePointSolution(4,4)); E.add(makePointSolution(4,4)); E.add(makePointSolution(4,4)); //reference pareto front List<PointSolution> ref = new ArrayList<PointSolution>(); ref.add(makePointSolution(5,1)); ref.add(makePointSolution(4,2)); ref.add(makePointSolution(3,3)); ref.add(makePointSolution(2,4)); ref.add(makePointSolution(1,5)); ArrayFront refFront = new ArrayFront(ref); //convert to ArrayFront from the List of PointSolutions ArrayFront dFront = new ArrayFront(D); ArrayFront eFront = new ArrayFront(E); System.out.printf("a, b in ref isDominent: %s\n", DominateUtils.isDominate(refFront.getPoint(0), refFront.getPoint(1))?"true":"false"); System.out.printf("D-E isDominent : %s\n", DominateUtils.isDominate(dFront.getPoint(0), eFront.getPoint(0))?"true":"false"); System.out.printf("D-D isDominent : %s\n", DominateUtils.isDominate(dFront.getPoint(0), dFront.getPoint(0))?"true":"false"); System.out.printf("D-D isWeaklyDominent : %s\n", DominateUtils.isWeaklyDominate(dFront.getPoint(0), dFront.getPoint(0))?"true":"false"); } }
11,750
39.944251
145
java
null
OPAM-main/PriorityAssignment/src/test/java/lu/uni/svv/PriorityAssignment/utils/MonitorTest.java
package lu.uni.svv.PriorityAssignment.utils; import junit.framework.TestCase; public class MonitorTest extends TestCase { public void testClass() throws Exception{ Monitor.init(); Monitor.updateMemory(); System.out.println(String.format("InitHeap: %.1fM (%.1fG)", Monitor.heapInit/Monitor.MB, Monitor.heapInit/Monitor.GB)); System.out.println(String.format("usedHeap: %.1fM (%.1fG)", Monitor.heapUsed/Monitor.MB, Monitor.heapUsed/Monitor.GB)); System.out.println(String.format("commitHeap: %.1fM (%.1fG)", Monitor.heapCommit/Monitor.MB, Monitor.heapCommit/Monitor.GB)); System.out.println(String.format("MaxHeap: %.1fM (%.1fG)", Monitor.heapMax/Monitor.MB, Monitor.heapMax/Monitor.GB)); System.out.println(String.format("MaxNonHeap: %.1fM (%.1fG)", Monitor.nonheapUsed/Monitor.MB, Monitor.nonheapUsed/Monitor.GB)); for (int i=0; i<10; i++){ System.out.println("working..."); Monitor.start("test", true); Thread.sleep(500); Monitor.end("test", true); } Monitor.updateMemory(); Monitor.finish(); System.out.println(String.format("test: %.3f", Monitor.times.get("test")/1000.0)); System.out.println(String.format("all: %.3f", Monitor.times.get("all")/1000.0)); System.out.println(String.format("InitHeap: %.1fM (%.1fG)", Monitor.heapInit/Monitor.MB, Monitor.heapInit/Monitor.GB)); System.out.println(String.format("usedHeap: %.1fM (%.1fG)", Monitor.heapUsed/Monitor.MB, Monitor.heapUsed/Monitor.GB)); System.out.println(String.format("commitHeap: %.1fM (%.1fG)", Monitor.heapCommit/Monitor.MB, Monitor.heapCommit/Monitor.GB)); System.out.println(String.format("MaxHeap: %.1fM (%.1fG)", Monitor.heapMax/Monitor.MB, Monitor.heapMax/Monitor.GB)); System.out.println(String.format("MaxNonHeap: %.1fM (%.1fG)", Monitor.nonheapUsed/Monitor.MB, Monitor.nonheapUsed/Monitor.GB)); } }
1,826
57.935484
129
java
null
OPAM-main/PriorityAssignment/src/test/java/lu/uni/svv/PriorityAssignment/utils/UniqueListTest.java
package lu.uni.svv.PriorityAssignment.utils; import junit.framework.TestCase; import java.util.Iterator; import java.util.List; public class UniqueListTest extends TestCase { public void testClass() throws Exception{ UniqueList list = new UniqueList(); int added = 0; int exists = 0; long now = System.currentTimeMillis(); for(int i=0; i<100000; i++){ Integer[] priorities = generateList(33); if (list.add(priorities)) added++; else exists++; } long fin = System.currentTimeMillis(); System.out.println("size:"+list.size()); System.out.println("added:"+added); System.out.println("exists:"+exists); System.out.println("workingTime:"+((fin-now)/1000.0)); print(list); } public static String toString(Integer[] list){ StringBuilder sb = new StringBuilder(list.length*3); sb.append("["); for(int i=0; i<list.length; i++){ sb.append(list[i]); sb.append(","); } sb.append("]"); return sb.toString(); } public static Integer[] generateList(int size){ RandomGenerator rand = new RandomGenerator(); Integer[] item = new Integer[size]; for(int i=0; i<size; i++){ item[i] = i; } for(int i=0; i<size; i++){ int idx1 = rand.nextInt(0, size-1); int idx2 = rand.nextInt(0, size-1); int temp = item[idx1]; item[idx1] = item[idx2]; item[idx2] = temp; } return item; } public void print(UniqueList unique){ Iterator<Integer> it = unique.getIteratorKeys(); int cnt = 0; while (it.hasNext()) { int key = it.next(); List<Integer[]> list = unique.getSlot(key); if (list.size()>1){ cnt++; System.out.println(String.format("%15d (%d): ", key, list.size())); // for(int x=0; x<list.size(); x++){ // System.out.print(toString(list.get(x))+", "); // } // System.out.println(""); } } System.out.println("Collision: "+cnt); } }
1,887
20.701149
71
java
null
OPAM-main/PriorityAssignment/src/test/java/lu/uni/svv/PriorityAssignment/generator/TaskSetSynthesizerTest.java
package lu.uni.svv.PriorityAssignment.generator; import junit.framework.TestCase; import lu.uni.svv.PriorityAssignment.task.TaskDescriptor; import lu.uni.svv.PriorityAssignment.task.TaskType; import lu.uni.svv.PriorityAssignment.utils.ArgumentParser; import java.io.*; import java.util.Random; public class TaskSetSynthesizerTest extends TestCase { /** * test generating tasks // old version * * @throws FileNotFoundException */ public void testGenerateTaskSet() throws FileNotFoundException { int MAX_SIM_TIME = 10000; double TIMEUNIT = 0.1; double targetU = 0.675; double delta = 0.05; int nTasks = 10; String NAME = "utilization"; String fname = String.format("../R/priorities/utilizationDist/%s.csv", NAME); PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(fname, false)), true); ps.println("nTasks,LCM"); TaskSetSynthesizer syn = new TaskSetSynthesizer((int)(MAX_SIM_TIME/TIMEUNIT), true, 10); for (nTasks = 10; nTasks <= 50; nTasks += 5) { System.out.print(String.format("Working with nTask=%d", nTasks)); for (int x = 0; x < 10000; x++) { while (true) { OPAMTaskSet taskset = syn.generatePeriodicTaskSet(nTasks, targetU, (int) (10 / TIMEUNIT), (int) (1000 / TIMEUNIT), (int) (10 / TIMEUNIT), true); if (!taskset.isValidWCET()) taskset = null; else if (!taskset.isValidUtilization(targetU, delta)) taskset = null; else if (!taskset.isValidSimulationTime((int)(MAX_SIM_TIME/TIMEUNIT))) taskset = null; if (taskset == null) continue; double lcm = taskset.calculateLCM() * TIMEUNIT; ps.println(String.format("%d, %d", nTasks, (int) lcm)); // ps.println(taskset.getString(TIMEUNIT)); break; } if (x % 20 == 0) { System.out.print("."); } } // for number of tast set System.out.println("Done"); } ps.close(); } /** * test generating task set with double data type * * @throws FileNotFoundException */ public void testGenerateTaskSetDouble() throws FileNotFoundException { int MAX_SIM_TIME = 10000; double TIMEUNIT = 1; double targetU = 0.7; double delta = 0.3; int nTasks = 10; String NAME = "utilization_double"; String fname = String.format("../R/priorities/utilizationDist/%s.csv", NAME); PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(fname, false)), true); ps.println("nTasks,Utilization"); TaskSetSynthesizer syn = new TaskSetSynthesizer((int)(MAX_SIM_TIME/TIMEUNIT), true, 10); for (nTasks = 10; nTasks <= 50; nTasks += 5) { System.out.print(String.format("Working with nTask=%d", nTasks)); for (int x = 0; x < 10000; x++) { while (true) { double[] utilizations = syn.UUniFast(nTasks, targetU); int[] periods = syn.generatePeriods(nTasks, (int) (10 / TIMEUNIT), (int) (1000 / TIMEUNIT), (int) (10 / TIMEUNIT), true); double[] WCETs = syn.generateWCETsDouble(periods, utilizations); double actualU = syn.getUtilization(periods, WCETs); if (actualU < targetU - delta || actualU > targetU + delta) continue; ps.println(String.format("%d, %.4f", nTasks, actualU)); break; } if (x % 200 == 0) { System.out.print("."); } } // for number of tast set System.out.println("Done"); } ps.close(); } /** * test generating task set with double data type * * @throws FileNotFoundException */ public void testGenerateRandom() throws FileNotFoundException { int MAX_SIM_TIME = 10000; double TIMEUNIT = 0.01; double targetU = 0.7; double delta = 0.05; int nTasks = 10; String NAME = "utilization_random3"; String fname = String.format("../R/priorities/utilizationDist/%s.csv", NAME); PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(fname, false)), true); ps.println("Type,Values"); Random rand = new Random(); for (int x = 0; x < 100000; x++) { double value = rand.nextDouble() * (delta * 2) + (targetU - delta); ps.println(String.format("Rand, %.5f", value)); ps.println(String.format("Prec1, %.5f", Math.round(value / 0.1) * 0.1)); ps.println(String.format("Prec2, %.5f", Math.round(value / 0.01) * 0.01)); ps.println(String.format("Prec3, %.5f", Math.round(value / 0.001) * 0.001)); ps.println(String.format("Prec4, %.5f", Math.round(value / 0.0001) * 0.0001)); ps.println(String.format("Prec5, %.5f", Math.round(value / 0.00001) * 0.00001)); if (x % 200 == 0) { System.out.print("."); } } // for number of tast set ps.close(); } /** * test generating tasks // by discarding when WCET condition is not acceptable * * @throws FileNotFoundException */ public void testGenerateTaskSet1() throws FileNotFoundException { // parsing args int MAX_SIM_TIME = 10000; double TIMEUNIT = 0.1; double targetU = 0.7; String NAME = "utilization"; String fname = String.format("../R/priorities/utilizationDist/%s.csv", NAME); PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(fname, false)), true); ps.println("nTasks,Utilization"); TaskSetSynthesizer syn = new TaskSetSynthesizer((int)(MAX_SIM_TIME/TIMEUNIT), true, 10); for (int nTasks = 10; nTasks <= 50; nTasks += 5) { System.out.print(String.format("Working with nTask=%d", nTasks)); for (int x = 0; x < 10000; x++) { double[] utilizations; int[] periods; int[] WCETs; while (true) { utilizations = syn.UUniFast(nTasks, targetU); periods = syn.generatePeriods(nTasks, (int) (10 / TIMEUNIT), (int) (1000 / TIMEUNIT), (int) (10 / TIMEUNIT), true); WCETs = syn.generateWCETs(periods, utilizations); boolean flag = true; for (int k = 0; k < WCETs.length; k++) { if (WCETs[k] == 0) { flag = false; break; } } if (flag) break; } double actualU = syn.getUtilization(periods, WCETs); ps.println(String.format("%d, %.4f", nTasks, actualU)); if (x % 200 == 0) { System.out.print("."); } } // for number of tast set System.out.println("Done"); } } /** * test generating tasks // by discarding taskset when the conditions are not acceptable ( with class functions) * * @throws FileNotFoundException */ public void testGenerateTaskSet2() throws FileNotFoundException { // parsing args int MAX_SIM_TIME = 10000; double TIMEUNIT = 0.1; double targetU = 0.7; double delta = 0.02; String NAME = String.format("utilization_period_T1_vWCET_vUtil%.2f", delta); String fname = String.format("../R/priorities/utilizationDist/%s.csv", NAME); PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(fname, false)), true); ps.println("nTasks,Utilization"); TaskSetSynthesizer syn = new TaskSetSynthesizer((int)(MAX_SIM_TIME/TIMEUNIT), true, 10); for (int nTasks = 10; nTasks <= 50; nTasks += 5) { System.out.print(String.format("Working with nTask=%d", nTasks)); for (int x = 0; x < 10000; x++) { OPAMTaskSet taskset = null; while (taskset == null) { taskset = syn.generatePeriodicTaskSet(nTasks, targetU, (int) (10 / TIMEUNIT), (int) (1000 / TIMEUNIT), (int) (10 / TIMEUNIT), true); // if(!taskset.isValidWCET()) taskset = null; if (!taskset.isValidWCET() || !taskset.isValidUtilization(targetU, delta)) taskset = null; } double actualU = taskset.getUtilization(); ps.println(String.format("%d, %.4f", nTasks, actualU)); // ps.println(String.format("%d, %.4f, %s", nTasks, actualU, taskset.getString(TIMEUNIT))); if (x % 200 == 0) { System.out.print("."); } } // for number of tast set System.out.println("Done"); } } /** * test generating tasks // by discarding taskset when the conditions are not acceptable ( with class functions) * * @throws FileNotFoundException */ public void testGenerateTaskSet3() throws FileNotFoundException { // parsing args int MAX_SIM_TIME = 10000; double TIMEUNIT = 0.1; double delta = 0.01; double targetU = 0.7; String NAME = String.format("utilization_mix_vWCET_vUtil%.3f", delta); String fname = String.format("../R/priorities/utilizationDist/%s.csv", NAME); PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(fname, false)), true); // PrintStream ps = System.out; ps.println("nTasks,Utilization"); TaskSetSynthesizer syn = new TaskSetSynthesizer((int)(MAX_SIM_TIME/TIMEUNIT), true, 10); for (int nTasks = 10; nTasks <= 50; nTasks += 5) { System.out.print(String.format("Working with nTask=%d", nTasks)); for (int x = 0; x < 100; x++) { OPAMTaskSet taskset = syn.generateMultiTaskset(nTasks, targetU, delta, (int) (10 / TIMEUNIT), (int) (1000 / TIMEUNIT), (int) (10 / TIMEUNIT), true, 0.4, 2); double actualU = taskset.getUtilization(); ps.println(String.format("%d, %.4f", nTasks, actualU)); // System.out.println(String.format("%d, %.4f, %s", nTasks, actualU, taskset.getString(TIMEUNIT))); // taskset.print(null, TIMEUNIT); if (x % 2 == 0) { System.out.print("."); } } // for number of tast set System.out.println("Done"); } ps.close(); } public void testUUniFast() throws IOException { // parsing args int MAX_SIM_TIME = 10000; double TIMEUNIT = 1; double targetU = 0.7; String NAME = "utilization_uunifast"; String fname = String.format("../R/priorities/utilizationDist/%s.csv", NAME); PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(fname, false)), true); ps.println("nTasks,Utilization,UtilizationP"); TaskSetSynthesizer syn = new TaskSetSynthesizer((int)(MAX_SIM_TIME/TIMEUNIT), true, 10); for (int nTasks = 10; nTasks <= 50; nTasks += 5) { System.out.print(String.format("Working with nTask=%d", nTasks)); for (int x = 0; x < 100000; x++) { double[] utilizations = syn.UUniFast(nTasks, targetU); double util = syn.getUtilization(utilizations); for (int t = 0; t < utilizations.length; t++) { utilizations[t] = Math.round(utilizations[t] * 100) / 100.0; } double utilp = syn.getUtilization(utilizations); ps.println(String.format("%d, %.4f, %.4f", nTasks, util, utilp)); if (x % 200 == 0) { System.out.print("."); } } // for number of tast set System.out.println("Done"); } } /** * Test code for a generateDivisors function */ public void testGenerateDivisors() { int inc = 1000; double TIMEUNIT = 1; for (int sim = 1 * inc; sim <= 10 * inc; sim += inc) { TaskSetSynthesizer syn = new TaskSetSynthesizer((int)(sim/TIMEUNIT), true, 10); int[] divisors = syn.generateDivisors((int)(sim/TIMEUNIT), (int)(sim/TIMEUNIT), (int)(sim/TIMEUNIT)); StringBuilder sb = new StringBuilder(); sb.append(sim); sb.append(": ["); for (int t = 0; t < divisors.length; t++) { sb.append(divisors[t]); sb.append(", "); } sb.append("]"); System.out.println(sb.toString()); } } /*** * Test for distribution of periods * @throws FileNotFoundException */ public void testPeriodSelector1() throws FileNotFoundException { String NAME = "period_dist_discarding"; String fname = String.format("../R/priorities/utilizationDist/divisor/%s.csv", NAME); PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(fname, false)), true); ps.println("Period"); int tMin = 10; int tMax = 1000; long sim = 10000; int granulrity = 10; int nTasks = 10; double targetU=0.7; double TIMEUNIT = 0.1; TaskSetSynthesizer syn = new TaskSetSynthesizer((int)(sim/TIMEUNIT), true, 10); for (int q = 0; q < 1000000; q+=nTasks) { OPAMTaskSet taskset = null; while(taskset==null) { taskset = syn.generateMultiTaskset(nTasks, targetU, 0.01, (int)(tMin/TIMEUNIT), (int)(tMax/TIMEUNIT), (int)(granulrity/TIMEUNIT), true, 0.37, 2); // taskset = syn.generatePeriodicTaskSet(nTasks, targetU, (int)(tMin/TIMEUNIT), // (int)(tMax/TIMEUNIT), (int)(granulrity/TIMEUNIT), true); // if (!taskset.isValidWCET() || !taskset.isValidUtilization(targetU, 0.01)) { // taskset = null; // continue; // } } for(int t=0; t<taskset.tasks.length; t++){ ps.println(taskset.tasks[t].Period); } // // int[] periods = syn.generatePeriods(nTasks, tMin, tMax, granulrity, true); // for(int t=0; t<periods.length; t++){ // ps.println(periods[t]); // } if (q%50000==0) { System.out.println("."); } } ps.close(); } public void testPeriodSelector2() throws FileNotFoundException { String NAME = "period_dist_index"; String fname = String.format("../R/priorities/utilizationDist/divisor/%s.csv", NAME); PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(fname, false)), true); ps.println("Period"); int tMin = 10; int tMax = 1000; long sim = 10000; int granularity=10; int nTasks = 10; double TIMEUNIT = 0.1; TaskSetSynthesizer syn = new TaskSetSynthesizer((int)(sim/TIMEUNIT),true, granularity); for (int q = 0; q < 1000000; q+=nTasks) { int[] periods = syn.generatePeriodsDivisors(nTasks, (int)(tMin/TIMEUNIT), (int)(tMax/TIMEUNIT), (int)(granularity/TIMEUNIT), true); for(int t=0; t<periods.length; t++){ ps.println(periods[t]); } if (q%50000==0) { System.out.println("."); } } } public void testPeriodSelector2_raw() throws FileNotFoundException { String NAME = "period_dist_index"; String fname = String.format("../R/priorities/utilizationDist/divisor/%s.csv", NAME); PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(fname, false)), true); ps.println("Period"); int tMin = 10; int tMax = 1000; long sim = 10000; int granularity=10; int nTasks = 10; double TIMEUNIT = 0.1; Random rand = new Random(); TaskSetSynthesizer syn = new TaskSetSynthesizer((int)(sim/TIMEUNIT), true, granularity); int[] divisors = syn.generateDivisors(sim, tMin, tMax); for (int q = 0; q < 1000000; q+=nTasks) { // get random value of log-uniform in range of indexes of divisors double min = Math.log(1); double max = Math.log(divisors.length + 1); //Math.log(tMax); // log distribution in range [log(min), log(max)) <- log(max) exclusive double randVal = rand.nextDouble() * (max - min) + min; // generate random value in [log(tMin), log(tMax+granularity)) int val = (int) Math.floor(Math.exp(randVal)); ps.println(divisors[val-1]); // divisors[val-1] if (q%50000==0) { System.out.println("."); } } } public void testPeriodSelector3() throws FileNotFoundException { String NAME = "period_dist_cdf"; String fname = String.format("../R/priorities/utilizationDist/divisor/%s.csv", NAME); PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(fname, false)), true); ps.println("Period"); int tMin = 10; int tMax = 1000; long sim = 10000; int granularity = 10; double TIMEUNIT = 0.1; int nTasks = 10; TaskSetSynthesizer syn = new TaskSetSynthesizer((int)(sim/TIMEUNIT), true, 10); for (int q = 0; q < 1000000; q++) { int[] periods = syn.generatePeriodsDivisorsCDF(nTasks,(int)(tMin/TIMEUNIT), (int)(tMax/TIMEUNIT), (int)(granularity/TIMEUNIT), true); for(int t=0; t<periods.length; t++){ ps.println(periods[t]); } if (q%50000==0) { System.out.println("."); } } } /** * Test aperiodic tasks * @throws FileNotFoundException */ public void testGenerateAperiodicTask() throws FileNotFoundException { int MAX_SIM_TIME = 0; double TIMEUNIT = 0.1; double targetU = 0.7; double delta = 0.01; int nTasks = 15; String NAME = "aperiodic"; // // String fname = String.format("../R/priorities/utilizationDist/%s.csv", NAME); // PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(fname, false)), true); // ps.println("nTasks,LCM"); int cntAll =0; int cntMin = 0; int cntMax = 0; int cntErr = 0; int granularity = 10; TaskSetSynthesizer syn = new TaskSetSynthesizer((int)(MAX_SIM_TIME/TIMEUNIT), true, granularity); for (nTasks = 10; nTasks <= 30; nTasks += 5) { System.out.print(String.format("Working with nTask=%d", nTasks)); for (int x = 0; x < 10000; x++) { while (true) { OPAMTaskSet taskset = syn.generatePeriodicTaskSet(nTasks, targetU, (int) (10 / TIMEUNIT), (int) (100 / TIMEUNIT), (int) (granularity / TIMEUNIT), true); if (!taskset.isValidWCET()) taskset = null; else if (!taskset.isValidUtilization(targetU, delta)) taskset = null; // else if (!taskset.isValidSimulationTime(MAX_SIM_TIME)) taskset = null; if (taskset == null) continue; taskset = syn.selectAperiodicTasks(taskset, 0.4, 3, 0, 0, (int) (granularity / TIMEUNIT)); if (taskset == null) continue; for(int k=0; k<nTasks; k++){ if (taskset.tasks[k].Type == TaskType.Periodic) continue; if (taskset.tasks[k].MinIA > taskset.tasks[k].MaxIA) { cntErr ++; // System.out.println(String.format("inter: [%d, %d]", taskset.tasks[k].MinIA, taskset.tasks[k].MaxIA)); } if (taskset.tasks[k].MinIA*3 == taskset.tasks[k].MaxIA) { cntMax ++; // System.out.println(String.format("inter2: [%d, %d]", taskset.tasks[k].MinIA, taskset.tasks[k].MaxIA)); } if (taskset.tasks[k].MinIA == taskset.tasks[k].MaxIA) { cntMin ++; // System.out.println(String.format("inter3: [%d, %d]", taskset.tasks[k].MinIA, taskset.tasks[k].MaxIA)); } // System.out.println(String.format("inter: [%d, %d]", taskset.tasks[k].MinIA, taskset.tasks[k].MaxIA)); cntAll++; } System.out.print("."); // double lcm = taskset.calculateLCM() * TIMEUNIT; // ps.println(String.format("%d, %d", nTasks, (int) lcm)); // ps.println(taskset.getString(TIMEUNIT)); break; } if (x % 20 == 0) { System.out.print("."); } } // for number of tast set System.out.println("Done"); System.out.println(String.format("cntAll: %d", cntAll)); System.out.println(String.format("cntError: %d", cntErr)); System.out.println(String.format("cntMin: %d", cntMin)); System.out.println(String.format("cntMax: %d", cntMax)); } // ps.close(); } public void testGenerateMultiTask() throws FileNotFoundException { int MAX_SIM_TIME = 0; double TIMEUNIT = 0.1; double targetU = 0.7; double delta = 0.01; int nTasks = 15; String NAME = "aperiodic"; int cntAll =0; int cntMin = 0; int cntMax = 0; int cntErr = 0; int granularity = 10; TaskSetSynthesizer syn = new TaskSetSynthesizer((int)(MAX_SIM_TIME/TIMEUNIT), false, granularity); for (nTasks = 10; nTasks <= 30; nTasks += 5) { System.out.print(String.format("Working with nTask=%d", nTasks)); for (int x = 0; x < 100; x++) { OPAMTaskSet taskset = syn.generateMultiTaskset(nTasks, targetU, delta, (int) (10 / TIMEUNIT), (int) (100 / TIMEUNIT), (int) (granularity / TIMEUNIT), true, 0.4, 3); for(int k=0; k<nTasks; k++){ if (taskset.tasks[k].Type == TaskType.Periodic) continue; if (taskset.tasks[k].MinIA > taskset.tasks[k].MaxIA) { cntErr ++; } if (taskset.tasks[k].MinIA*3 == taskset.tasks[k].MaxIA) { cntMax ++; } if (taskset.tasks[k].MinIA == taskset.tasks[k].MaxIA) { cntMin ++; } cntAll++; } System.out.print("."); if (x % 20 == 0) { System.out.print("."); } } // for number of tast set System.out.println("Done"); System.out.println(String.format("cntAll: %d", cntAll)); System.out.println(String.format("cntError: %d", cntErr)); System.out.println(String.format("cntMin: %d", cntMin)); System.out.println(String.format("cntMax: %d", cntMax)); } // ps.close(); } }
19,904
33.73822
157
java
null
OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/Initializer.java
package lu.uni.svv.PriorityAssignment; import lu.uni.svv.PriorityAssignment.scheduler.RTScheduler; import lu.uni.svv.PriorityAssignment.task.TaskDescriptor; import lu.uni.svv.PriorityAssignment.task.TaskType; import lu.uni.svv.PriorityAssignment.utils.Settings; import org.uma.jmetal.util.JMetalLogger; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.ConsoleHandler; import java.util.logging.LogRecord; import java.util.logging.SimpleFormatter; public class Initializer { /** * log formatter for jMetal */ public static SimpleFormatter formatter = new SimpleFormatter(){ private static final String format = "[%1$tF %1$tT] %2$s: %3$s %n"; @Override public synchronized String format(LogRecord lr) { return String.format(format, new Date(lr.getMillis()), lr.getLevel().getLocalizedName(), lr.getMessage() ); } }; /** * initLogger: basic setting for jMetal */ public static void initLogger(){ JMetalLogger.logger.setUseParentHandlers(false); ConsoleHandler handler = new ConsoleHandler(); handler.setFormatter(formatter); JMetalLogger.logger.addHandler(handler); } /** * Return simulation time based on TIME_QUANTA unit * @param input * @return */ public static int calculateSimulationTime(TaskDescriptor[] input){ int simulationTime = 0; if (Settings.TIME_MAX == 0) { // calculate simulation time for all task period (no matter the task type) // long[] array = new long[input.length]; // for(int x=0; x<input.length; x++){ // array[x] = input[x].Period; // } // simulationTime = (int) RTScheduler.lcm(array); // Too large simulation time :: calculate different way. // if (simulationTime > 100000){ // by considering time unit // Those task time information appplied TIME_QUANTA to make int type // calculate LCM for periodic tasks only List<Long> periodArray = new ArrayList<>(); for(int x=0; x<input.length; x++){ if (input[x].Type != TaskType.Periodic) continue; periodArray.add((long)(input[x].Period)); } long[] array = new long[periodArray.size()]; for(int x=0; x<periodArray.size(); x++) { array[x] = periodArray.get(x); } int periodicLCM = (int) RTScheduler.lcm(array); // get maximum inter arrival time among non-periodic tasks int maxInterArrivalTime = 0; for(int x=0; x<input.length; x++){ if (input[x].Type == TaskType.Periodic) continue; maxInterArrivalTime = Math.max(maxInterArrivalTime, input[x].MaxIA); } // select max value among two simulation time simulationTime = Math.max(periodicLCM, maxInterArrivalTime); } else{ simulationTime = (int) (Settings.TIME_MAX * (1/Settings.TIME_QUANTA)); } return simulationTime; } public static void updateSettings(TaskDescriptor[] input) throws Exception{ // update specific options if (Settings.P1_MUTATION_PROB==0) Settings.P1_MUTATION_PROB = 1.0/input.length; if (Settings.P2_MUTATION_PROB==0) Settings.P2_MUTATION_PROB = 1.0/input.length; // Set SIMULATION_TIME int simulationTime = Initializer.calculateSimulationTime(input); if (simulationTime<0) { System.out.println("Cannot calculate simulation time"); throw new Exception("Cannot calculate simulation time"); } Settings.TIME_MAX = (simulationTime * Settings.TIME_QUANTA); // to change to ms unit } public static void convertTimeUnit(double _quanta){ Settings.ADDITIONAL_SIMULATION_TIME = (int)(Settings.ADDITIONAL_SIMULATION_TIME * (1/_quanta)); Settings.MAX_OVER_DEADLINE = (int)(Settings.MAX_OVER_DEADLINE * (1/_quanta)); Settings.TIME_MAX = (int)(Settings.TIME_MAX * (1/_quanta)); } }
3,730
30.091667
97
java