src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
OptionalConfig { public Map<String, String> getItems() { return items; } OptionalConfig(); Map<String, String> getItems(); void setItems(Map<String, String> items); @Override String toString(); }
@Test public void testAddingAndFetchingOptionalConfigItems() throws Exception { final OptionalConfig strategyConfig = new OptionalConfig(); strategyConfig.getItems().put(BUY_FEE_CONFIG_ITEM_KEY, BUY_FEE_CONFIG_ITEM_VALUE); strategyConfig.getItems().put(SELL_FEE_CONFIG_ITEM_KEY, SELL_FEE_CONFIG_ITEM_VALUE); assertEquals(2, strategyConfig.getItems().size()); assertEquals(BUY_FEE_CONFIG_ITEM_VALUE, strategyConfig.getItems().get(BUY_FEE_CONFIG_ITEM_KEY)); assertEquals(SELL_FEE_CONFIG_ITEM_VALUE, strategyConfig.getItems().get(SELL_FEE_CONFIG_ITEM_KEY)); }
JwtUtils { Date getIssuedAtDateFromTokenClaims(Claims claims) throws JwtAuthenticationException { try { return claims.getIssuedAt(); } catch (Exception e) { final String errorMsg = "Failed to extract iat claim from token!"; LOG.error(errorMsg, e); throw new JwtAuthenticationException(errorMsg, e); } } Claims validateTokenAndGetClaims(String token); String generateToken(JwtUser userDetails); boolean canTokenBeRefreshed(Claims claims, Date lastPasswordReset); String refreshToken(String token); String getUsernameFromTokenClaims(Claims claims); List<GrantedAuthority> getRolesFromTokenClaims(Claims claims); }
@Test public void testIssuedAtDateCanBeExtractedFromTokenClaims() throws Exception { when(claims.getIssuedAt()).thenReturn(ISSUED_AT_DATE); assertThat(jwtUtils.getIssuedAtDateFromTokenClaims(claims)) .isCloseTo(ISSUED_AT_DATE, GRADLE_FRIENDLY_TIME_TOLERANCE_IN_MILLIS); verify(claims, times(1)).getIssuedAt(); }
JwtUtils { Date getExpirationDateFromTokenClaims(Claims claims) throws JwtAuthenticationException { try { return claims.getExpiration(); } catch (Exception e) { final String errorMsg = "Failed to extract expiration claim from token!"; LOG.error(errorMsg, e); throw new JwtAuthenticationException(errorMsg, e); } } Claims validateTokenAndGetClaims(String token); String generateToken(JwtUser userDetails); boolean canTokenBeRefreshed(Claims claims, Date lastPasswordReset); String refreshToken(String token); String getUsernameFromTokenClaims(Claims claims); List<GrantedAuthority> getRolesFromTokenClaims(Claims claims); }
@Test public void testExpirationDateCanBeExtractedFromTokenClaims() throws Exception { when(claims.getExpiration()).thenReturn(EXPIRATION_DATE); assertThat(jwtUtils.getExpirationDateFromTokenClaims(claims)) .isCloseTo(EXPIRATION_DATE, GRADLE_FRIENDLY_TIME_TOLERANCE_IN_MILLIS); verify(claims, times(1)).getExpiration(); }
JwtUtils { public List<GrantedAuthority> getRolesFromTokenClaims(Claims claims) throws JwtAuthenticationException { final List<GrantedAuthority> roles = new ArrayList<>(); try { @SuppressWarnings("unchecked") final List<String> rolesFromClaim = (List<String>) claims.get(CLAIM_KEY_ROLES); for (final String roleFromClaim : rolesFromClaim) { roles.add(new SimpleGrantedAuthority(roleFromClaim)); } return roles; } catch (Exception e) { final String errorMsg = "Failed to extract roles claim from token!"; LOG.error(errorMsg, e); throw new JwtAuthenticationException(errorMsg, e); } } Claims validateTokenAndGetClaims(String token); String generateToken(JwtUser userDetails); boolean canTokenBeRefreshed(Claims claims, Date lastPasswordReset); String refreshToken(String token); String getUsernameFromTokenClaims(Claims claims); List<GrantedAuthority> getRolesFromTokenClaims(Claims claims); }
@Test public void testRolesCanBeExtractedFromTokenClaims() throws Exception { when(claims.get(JwtUtils.CLAIM_KEY_ROLES)).thenReturn(ROLES); final List<GrantedAuthority> roles = jwtUtils.getRolesFromTokenClaims(claims); assertThat(roles.size()).isEqualTo(2); assertThat(roles.get(0).getAuthority()).isEqualTo(RoleName.ROLE_ADMIN.name()); assertThat(roles.get(1).getAuthority()).isEqualTo(RoleName.ROLE_USER.name()); verify(claims, times(1)).get(JwtUtils.CLAIM_KEY_ROLES); }
JwtUtils { Date getLastPasswordResetDateFromTokenClaims(Claims claims) { Date lastPasswordResetDate; try { lastPasswordResetDate = new Date((Long) claims.get(CLAIM_KEY_LAST_PASSWORD_CHANGE_DATE)); } catch (Exception e) { LOG.error("Failed to extract lastPasswordResetDate claim from token!", e); lastPasswordResetDate = null; } return lastPasswordResetDate; } Claims validateTokenAndGetClaims(String token); String generateToken(JwtUser userDetails); boolean canTokenBeRefreshed(Claims claims, Date lastPasswordReset); String refreshToken(String token); String getUsernameFromTokenClaims(Claims claims); List<GrantedAuthority> getRolesFromTokenClaims(Claims claims); }
@Test public void testLastPasswordResetDateCanBeExtractedFromTokenClaims() throws Exception { when(claims.get(JwtUtils.CLAIM_KEY_LAST_PASSWORD_CHANGE_DATE)) .thenReturn(LAST_PASSWORD_RESET_DATE.getTime()); assertThat(jwtUtils.getLastPasswordResetDateFromTokenClaims(claims)) .isCloseTo(LAST_PASSWORD_RESET_DATE, GRADLE_FRIENDLY_TIME_TOLERANCE_IN_MILLIS); }
JwtUtils { public Claims validateTokenAndGetClaims(String token) { try { final Claims claims = getClaimsFromToken(token); final Date created = getIssuedAtDateFromTokenClaims(claims); final Date lastPasswordResetDate = getLastPasswordResetDateFromTokenClaims(claims); if (isCreatedBeforeLastPasswordReset(created, lastPasswordResetDate)) { final String errorMsg = "Invalid token! Created date claim is before last password reset date." + " Created date: " + created + " Password reset date: " + lastPasswordResetDate; LOG.error(errorMsg); throw new JwtAuthenticationException(errorMsg); } return claims; } catch (Exception e) { final String errorMsg = "Invalid token! Details: " + e.getMessage(); LOG.error(errorMsg, e); throw new JwtAuthenticationException(errorMsg, e); } } Claims validateTokenAndGetClaims(String token); String generateToken(JwtUser userDetails); boolean canTokenBeRefreshed(Claims claims, Date lastPasswordReset); String refreshToken(String token); String getUsernameFromTokenClaims(Claims claims); List<GrantedAuthority> getRolesFromTokenClaims(Claims claims); }
@Test public void whenValidateTokenCalledWithNonExpiredTokenThenExpectSuccess() throws Exception { final String token = createToken(); assertThat(jwtUtils.validateTokenAndGetClaims(token)).isNotNull(); } @Test(expected = JwtAuthenticationException.class) public void whenValidateTokenCalledWithExpiredTokenThenExpectFailure() throws Exception { ReflectionTestUtils.setField(jwtUtils, "allowedClockSkewInSecs", 0L); ReflectionTestUtils.setField(jwtUtils, "expirationInSecs", 0L); final String token = createToken(); jwtUtils.validateTokenAndGetClaims(token); } @Test(expected = JwtAuthenticationException.class) public void whenValidateTokenCalledWithCreatedDateEarlierThanLastPasswordResetDateThenExpectFailure() throws Exception { final String token = createTokenWithInvalidCreationDate(); jwtUtils.validateTokenAndGetClaims(token); }
Properlty { public Optional<String> get(String key) { if (!caseSensitive) { key = key.toLowerCase(); } final PropertyValue value = properties.get(key); if (value != null) { return Optional.ofNullable(value.getValue()); } return Optional.empty(); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); }
@Test public void shouldReturnEmptyOptionalString() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "value.one"); properties.put("key.two", "value.two"); final Properlty prop = buildProperlty(properties); assertFalse(prop.get("key.three").isPresent()); } @Test public void shouldReturnOptionalString() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "value.one"); properties.put("key.two", "value.two"); final Properlty prop = buildProperlty(properties); assertEquals("value.one", prop.get("key.one").get()); assertEquals("value.two", prop.get("key.two").get()); assertFalse(prop.get("key.ONE").isPresent()); } @Test public void shouldReturntheKeyApplyingTheMapFunction() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "111"); final Properlty prop = buildProperlty(properties); assertEquals(111, prop.get("key.one", Integer::valueOf).get().intValue()); assertEquals(222, prop.get("key.two", 222, Integer::valueOf).intValue()); assertFalse(prop.get("key.three", Integer::valueOf).isPresent()); } @Test public void shouldMatchPlaceholdersNotSensitiveCase() { final Map<String, String> properties = new HashMap<>(); properties.put("key.ONE", "${value1:defaultValue1}"); properties.put("keY.TWO", "${KEY.one:defaultValue2}"); properties.put("key.three", "${KEY.one:defaultValue3}"); final boolean caseSensitive = false; final Properlty prop = buildProperlty(properties, caseSensitive); assertEquals("defaultValue1", prop.get("key.one").get()); assertEquals("defaultValue1", prop.get("key.two").get()); assertEquals("defaultValue1", prop.get("key.THREE").get()); } @Test public void shouldMatchPlaceholdersSensitiveCase() { final Map<String, String> properties = new HashMap<>(); properties.put("key.ONE", "${value1:defaultValue1}"); properties.put("keY.TWO", "${KEY.one:defaultValue2}"); properties.put("key.three", "${KEY.one:defaultValue3}"); final boolean caseSensitive = true; final Properlty prop = buildProperlty(properties, caseSensitive); assertEquals("defaultValue1", prop.get("key.ONE").get()); assertEquals("defaultValue2", prop.get("keY.TWO").get()); assertEquals("defaultValue3", prop.get("key.three").get()); } @Test public void shouldReturnCaseInsensitive() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "value.one"); properties.put("KEy.tWo", "value.two"); final boolean caseSensitive = false; final Properlty prop = buildProperlty(properties, caseSensitive); assertEquals("value.one", prop.get("key.one").get()); assertEquals("value.two", prop.get("key.two").get()); assertEquals("value.one", prop.get("key.ONE").get()); assertEquals("value.two", prop.get("KEY.TWo").get()); } @Test public void shouldReturnDefaultString() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "value.one"); final Properlty prop = buildProperlty(properties); assertEquals("value.one", prop.get("key.one", "default")); assertEquals("default", prop.get("key.two", "default")); }
Properlty { public Optional<Double> getDouble(String key) { return get(key).map(Double::parseDouble); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); }
@Test public void shouldReturnEmptyOptionalDouble() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "value.one"); properties.put("key.two", "value.two"); final Properlty prop = buildProperlty(properties); assertFalse(prop.getDouble("key.three").isPresent()); } @Test public void shouldReturnDefaultDouble() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "1"); final Properlty prop = buildProperlty(properties); assertEquals(1d, prop.getDouble("key.one", 1.1111d), 0.1d); assertEquals(10d, prop.getDouble("key.two", 10d), 0.1d); } @Test(expected=NumberFormatException.class) public void shouldThrowExceptionParsingWrongDouble() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "not a number"); final Properlty prop = buildProperlty(properties); prop.getDouble("key.one"); }
Properlty { public Optional<Float> getFloat(String key) { return get(key).map(Float::parseFloat); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); }
@Test public void shouldReturnEmptyOptionalFloat() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "value.one"); properties.put("key.two", "value.two"); final Properlty prop = buildProperlty(properties); assertFalse(prop.getFloat("key.three").isPresent()); } @Test public void shouldReturnDefaultFloat() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "1"); final Properlty prop = buildProperlty(properties); assertEquals(1f, prop.getFloat("key.one", 10), 0.1f); assertEquals(10f, prop.getFloat("key.two", 10), 0.1f); } @Test(expected=NumberFormatException.class) public void shouldThrowExceptionParsingWrongFloat() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "not a number"); final Properlty prop = buildProperlty(properties); prop.getFloat("key.one"); }
Properlty { public Optional<Long> getLong(String key) { return get(key).map(Long::parseLong); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); }
@Test public void shouldReturnEmptyOptionalLong() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "value.one"); properties.put("key.two", "value.two"); final Properlty prop = buildProperlty(properties); assertFalse(prop.getLong("key.three").isPresent()); } @Test public void shouldReturnDefaultLong() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "1"); final Properlty prop = buildProperlty(properties); assertEquals(1l, prop.getLong("key.one", 10l)); assertEquals(10l, prop.getLong("key.two", 10l)); } @Test(expected=NumberFormatException.class) public void shouldThrowExceptionParsingWrongLong() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "not a number"); final Properlty prop = buildProperlty(properties); prop.getLong("key.one"); }
Properlty { public Optional<BigDecimal> getBigDecimal(String key) { return get(key).map((val) -> new BigDecimal(val)); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); }
@Test public void shouldReturnDefaultBigDecimal() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "1"); final Properlty prop = buildProperlty(properties); assertEquals(1, prop.getBigDecimal("key.one", new BigDecimal(10)).intValue()); assertEquals(10, prop.getBigDecimal("key.two", new BigDecimal(10)).intValue()); }
Properlty { public Optional<BigInteger> getBigInteger(String key) { return get(key).map((val) -> new BigInteger(val)); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); }
@Test public void shouldReturnDefaultBigInteger() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "1"); final Properlty prop = buildProperlty(properties); assertEquals(1, prop.getBigInteger("key.one", new BigInteger("10")).intValue()); assertEquals(10, prop.getBigInteger("key.two", new BigInteger("10")).intValue()); }
Properlty { public <T extends Enum<T>> Optional<T> getEnum(String key, Class<T> type) { return get(key).map(value -> Enum.valueOf(type, value)); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); }
@Test public void shouldReturnEmptyOptionalEnum() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "value.one"); properties.put("key.two", "value.two"); final Properlty prop = buildProperlty(properties); assertFalse(prop.getEnum("key.three", NeedSomebodyToLove.class).isPresent()); } @Test public void shouldReturnDefaultEnum() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "ME"); final Properlty prop = buildProperlty(properties); assertEquals(NeedSomebodyToLove.ME, prop.getEnum("key.one", NeedSomebodyToLove.THEM)); assertEquals(NeedSomebodyToLove.THEM, prop.getEnum("key.two", NeedSomebodyToLove.THEM)); } @Test(expected=IllegalArgumentException.class) public void shouldThrowExceptionParsingWrongEnumLong() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "not an enum"); final Properlty prop = buildProperlty(properties); prop.getEnum("key.one", NeedSomebodyToLove.class); }
Properlty { public String[] getArray(String key) { return getArray(key, Default.LIST_SEPARATOR); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); }
@Test public void shouldReturnValueToArray() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "111,AAAAA,BBB"); final Properlty prop = buildProperlty(properties); final String[] values = prop.getArray("key.one"); assertEquals(3, values.length); assertEquals("111", values[0]); assertEquals("AAAAA", values[1]); assertEquals("BBB", values[2]); assertEquals(0, prop.getArray("key.three").length); }
StringUtils { public static List<String> allTokens(String input, String startDelimiter, String endDelimiter) { final List<String> tokens = new ArrayList<>(); Optional<String> token = firstToken(input, startDelimiter, endDelimiter); while(token.isPresent()) { final String tokenValue = token.get(); tokens.add(tokenValue); input = input.substring(input.indexOf(tokenValue) + tokenValue.length() + endDelimiter.length()); token = firstToken(input, startDelimiter, endDelimiter); } return tokens; } private StringUtils(); static boolean hasTokens(String input, String startDelimiter, String endDelimiter); static Optional<String> firstToken(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter); static List<String> allTokens(String input, String startDelimiter, String endDelimiter, boolean distinct); }
@Test public void shouldReturnEmpty() { final String input = ""; assertTrue(StringUtils.allTokens(input, startDelimiter, endDelimiter).isEmpty()); } @Test public void shouldReturnEmpty2() { final String input = "asfasdfasfdasfdasf_${_asdasd"; assertTrue(StringUtils.allTokens(input, startDelimiter, endDelimiter).isEmpty()); } @Test public void shouldReturnEmpty3() { final String input = "asfasdfasfdasfdasf_}_asdasd"; assertTrue(StringUtils.allTokens(input, startDelimiter, endDelimiter).isEmpty()); } @Test public void shouldReturnSimpleToken() { final String input = "${TOKEN}"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(1, tokens.size()); assertEquals("TOKEN", tokens.get(0)); } @Test public void shouldReturnTokenAtTheEnd() { final String input = "asfasdfasfdasfdasf_${TOKEN}"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(1, tokens.size()); assertEquals("TOKEN", tokens.get(0)); } @Test public void shouldReturnTokenAtTheBeginning() { final String input = "${TOKEN}asfasdfasfd_${_asfdasf"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(1, tokens.size()); assertEquals("TOKEN", tokens.get(0)); } @Test public void shouldReturnTokenInTheMiddle() { final String input = "asfasdfasf${TOKEN}dasfdasf"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(1, tokens.size()); assertEquals("TOKEN", tokens.get(0)); } @Test public void shouldReturnTokenInTheMiddle2() { final String input = "asfas}dfasf${TOKEN}dasfdasf"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(1, tokens.size()); assertEquals("TOKEN", tokens.get(0)); } @Test public void shouldReturnTokenInTheMiddle3() { final String input = "asfas${dfasf${TOKEN}dasfdasf"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(1, tokens.size()); assertEquals("TOKEN", tokens.get(0)); } @Test public void shouldReturnTokenInTheMiddle4() { final String input = "asfas${dfasf${TOKEN}dasfd${asf"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(1, tokens.size()); assertEquals("TOKEN", tokens.get(0)); } @Test public void shouldReturnTokenInTheMiddle5() { final String input = "asfas${dfasf${TOKEN}dasfd}asf"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(1, tokens.size()); assertEquals("TOKEN", tokens.get(0)); } @Test public void shouldReturnInnerToken() { final String input = "asfas${dfasf${TOKEN}dasf}dasf"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(1, tokens.size()); assertEquals("TOKEN", tokens.get(0)); } @Test public void shouldReturnNestedToken() { final String input = "${${${TOKEN}}}"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(1, tokens.size()); assertEquals("TOKEN", tokens.get(0)); } @Test public void shouldReturnAllTokens1() { final String input = "___${____${TOKEN_1}__}___${TOKEN_2}__"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(2, tokens.size()); assertEquals("TOKEN_1", tokens.get(0)); assertEquals("TOKEN_2", tokens.get(1)); } @Test public void shouldReturnAllTokens2() { final String input = "___${____${TOKEN_1__}___${TOKEN_2}__"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(2, tokens.size()); assertEquals("TOKEN_1__", tokens.get(0)); assertEquals("TOKEN_2", tokens.get(1)); } @Test public void shouldReturnAllTokens3() { final String input = "___${____${TOKEN_2}_}___${TOKEN_2}__"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter); assertEquals(2, tokens.size()); assertEquals("TOKEN_2", tokens.get(0)); assertEquals("TOKEN_2", tokens.get(1)); } @Test public void shouldReturnAllTokens4() { final String input = "___${____${TOKEN_1}_${TOKEN_2}_}___${TOKEN_2}_${${TOKEN_3}}_"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter, false); assertEquals(4, tokens.size()); assertEquals("TOKEN_1", tokens.get(0)); assertEquals("TOKEN_2", tokens.get(1)); assertEquals("TOKEN_2", tokens.get(2)); assertEquals("TOKEN_3", tokens.get(3)); } @Test public void shouldReturnUniqueTokens1() { final String input = "___${____${TOKEN_2}_}___${TOKEN_2}__"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter, true); assertEquals(1, tokens.size()); assertEquals("TOKEN_2", tokens.get(0)); } @Test public void shouldReturnUniqueTokens2() { final String input = "___${____${TOKEN_1}_${TOKEN_2}_}___${TOKEN_2}_${${TOKEN_3}}_"; final List<String> tokens = StringUtils.allTokens(input, startDelimiter, endDelimiter, true); assertEquals(3, tokens.size()); assertEquals("TOKEN_1", tokens.get(0)); assertEquals("TOKEN_2", tokens.get(1)); assertEquals("TOKEN_3", tokens.get(2)); }
FileUtils { public static InputStream getStream(String resourcePath) throws FileNotFoundException { if (resourcePath.startsWith(CLASSPATH_PREFIX)) { final String resourceName = resourcePath.substring(CLASSPATH_PREFIX.length()); final InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Cannot retrieve classpath resource [" + resourceName + "]"); } return is; } if (resourcePath.startsWith(FILE_PATH_PREFIX)) { return new FileInputStream(resourcePath.substring(FILE_PATH_PREFIX.length())); } return new FileInputStream(resourcePath); } private FileUtils(); static InputStream getStream(String resourcePath); static final String FILE_PATH_PREFIX; static final String CLASSPATH_PREFIX; }
@Test public void shouldReadFileFromRelativePath() throws IOException { try (InputStream is = FileUtils.getStream("./src/test/files/test1.properties")) { final String content = toString(is); assertNotNull(content); assertTrue(content.contains("keyOne")); } } @Test public void shouldReadFileFromRelativePathWithPrefix() throws IOException { try (InputStream is = FileUtils.getStream("file:src/test/files/test1.properties")) { final String content = toString(is); assertNotNull(content); assertTrue(content.contains("keyOne")); } } @Test public void shouldReadFileFromAbsolutePath() throws IOException { final String absolutePath = new File("src/test/files/test1.properties").getAbsolutePath(); try (InputStream is = FileUtils.getStream(absolutePath)) { final String content = toString(is); assertNotNull(content); assertTrue(content.contains("keyOne")); } } @Test public void shouldReadFileFromAbsolutePathWithPrefix() throws IOException { final String absolutePath = new File("src/test/files/test1.properties").getAbsolutePath(); try (InputStream is = FileUtils.getStream("file:" + absolutePath)) { final String content = toString(is); assertNotNull(content); assertTrue(content.contains("keyOne")); } } @Test public void shouldReadFileFromClasspath() throws IOException { try (InputStream is = FileUtils.getStream("classpath:resource1.properties")) { final String content = toString(is); assertNotNull(content); assertTrue(content.contains("name=resource1")); } } @Test public void shouldReadFileFromClasspathFolder() throws IOException { try (InputStream is = FileUtils.getStream("classpath:./inner/resource2.properties")) { final String content = toString(is); assertNotNull(content); assertTrue(content.contains("name=resource2")); } } @Test public void shouldThrowFileNotFoundExceptionForMissingFileFromClasspath() throws IOException { try { FileUtils.getStream("classpath:NOT_EXISTING_FILE"); fail("Should have thrown a FileNotFoundException"); } catch (final FileNotFoundException e) { assertTrue(e.getMessage().contains("NOT_EXISTING_FILE")); } } @Test public void shouldThrowFileNotFoundExceptionForMissingFile() throws IOException { try { FileUtils.getStream("file:NOT_EXISTING_FILE"); fail("Should have thrown a FileNotFoundException"); } catch (final FileNotFoundException e) { assertTrue(e.getMessage().contains("NOT_EXISTING_FILE")); } }
Properlty { public Optional<Integer> getInt(String key) { return get(key).map(Integer::parseInt); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); }
@Test public void shouldReturnEmptyOptionalInteger() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "value.one"); properties.put("key.two", "value.two"); final Properlty prop = buildProperlty(properties); assertFalse(prop.getInt("key.three").isPresent()); } @Test public void shouldReturnDefaultInteger() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "1"); final Properlty prop = buildProperlty(properties); assertEquals(1, prop.getInt("key.one", 10)); assertEquals(10, prop.getInt("key.two", 10)); } @Test(expected=NumberFormatException.class) public void shouldThrowExceptionParsingWrongInteger() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "not a number"); final Properlty prop = buildProperlty(properties); prop.getInt("key.one"); }
SystemPropertiesReader implements Reader { @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> properties = new HashMap<>(); final Properties systemProperties = System.getProperties(); for(final Entry<Object, Object> x : systemProperties.entrySet()) { properties.put((String)x.getKey(), PropertyValue.of((String)x.getValue())); } return properties; } @Override Map<String, PropertyValue> read(); }
@Test public void shouldReadSystemProperties() { final String key = UUID.randomUUID().toString(); final String value = UUID.randomUUID().toString(); System.setProperty(key, value); final Map<String, PropertyValue> systemProperties = new SystemPropertiesReader().read(); assertNotNull(systemProperties); assertTrue(systemProperties.containsKey(key)); assertEquals(value, systemProperties.get(key).getValue()); }
EnvironmentVariablesReader implements Reader { @Override public Map<String, PropertyValue> read() { return envSupplier.get().entrySet().stream() .collect(Collectors.toMap( e -> getKey(e.getKey()), e -> PropertyValue.of(e.getValue()).resolvable(false) )); } EnvironmentVariablesReader(); EnvironmentVariablesReader(Supplier<Map<String, String>> envSupplier); @Override Map<String, PropertyValue> read(); EnvironmentVariablesReader replace(String from, String to); }
@Test public void shouldReturnUnresolvableEnvironmentVariables() { final Map<String, PropertyValue> var = new EnvironmentVariablesReader().read(); assertNotNull(var); assertFalse(var.isEmpty()); var.forEach((key, value) -> { assertFalse(value.isResolvable()); }); }
PriorityQueueDecoratorReader implements Reader { @Override public Map<String, PropertyValue> read() { final Map<String, PropertyValue> result = new LinkedHashMap<>(); readersMap.forEach((priority, readers) -> { readers.forEach(reader -> { final Map<String, PropertyValue> entries = reader.read(); result.putAll(entries); }); }) ; return result; } @Override Map<String, PropertyValue> read(); void add(Reader reader, int priority); }
@Test public void shouldReturnEmptyMapIfEmpty() { final PriorityQueueDecoratorReader queue = new PriorityQueueDecoratorReader(); final Map<String, PropertyValue> prop = queue.read(); assertNotNull(prop); assertTrue(prop.isEmpty()); }
Properlty { public Optional<Boolean> getBoolean(String key) { return get(key).map(value -> { if ( "true".equalsIgnoreCase(value) ) return true; else if ( "false".equalsIgnoreCase(value) ) return false; else throw new RuntimeException("Cannot parse boolean value: [" + value+ "]"); }); } Properlty(boolean caseSensitive, Map<String, PropertyValue> properties); static ProperltyBuilder builder(); Optional<String> get(String key); String get(String key, String defaultValue); Optional<T> get(String key, Function<String, T> map); T get(String key, T defaultValue, Function<String, T> map); Optional<Integer> getInt(String key); int getInt(String key, int defaultValue); Optional<Boolean> getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Optional<Double> getDouble(String key); double getDouble(String key, double defaultValue); Optional<Float> getFloat(String key); float getFloat(String key, float defaultValue); Optional<Long> getLong(String key); long getLong(String key, long defaultValue); Optional<BigDecimal> getBigDecimal(String key); BigDecimal getBigDecimal(String key, BigDecimal defaultValue); Optional<BigInteger> getBigInteger(String key); BigInteger getBigInteger(String key, BigInteger defaultValue); Optional<T> getEnum(String key, Class<T> type); T getEnum(String key, T defaultValue); String[] getArray(String key); String[] getArray(String key, String separator); List<String> getList(String key); List<String> getList(String key, String separator); List<T> getList(String key, Function<String, T> map); List<T> getList(String key, String separator, Function<String, T> map); }
@Test public void shouldReturnEmptyOptionalBoolean() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "value.one"); properties.put("key.two", "value.two"); final Properlty prop = buildProperlty(properties); assertFalse(prop.getBoolean("key.three").isPresent()); } @Test public void shouldReturnDefaultBoolean() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "true"); final Properlty prop = buildProperlty(properties); assertTrue(prop.getBoolean("key.one", false)); assertFalse(prop.getBoolean("key.two", false)); assertTrue(prop.getBoolean("key.two", true)); } @Test(expected=RuntimeException.class) public void shouldThrowExceptionParsingWrongBoolean() { final Map<String, String> properties = new HashMap<>(); properties.put("key.one", "not a bool"); final Properlty prop = buildProperlty(properties); prop.getBoolean("key.one"); }
MinikubeDockerEnvParser { public static Map<String, String> parse(List<String> keyValueStrings) { Map<String, String> environmentMap = new HashMap<>(); for (String keyValueString : keyValueStrings) { String[] keyValuePair = keyValueString.split("=", 2); if (keyValuePair.length < 2) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format"); } if (keyValuePair[0].length() == 0) { throw new IllegalArgumentException( "Error while parsing minikube's Docker environment: encountered empty environment variable name"); } environmentMap.put(keyValuePair[0], keyValuePair[1]); } return environmentMap; } private MinikubeDockerEnvParser(); static Map<String, String> parse(List<String> keyValueStrings); }
@Test public void testParse_success() { List<String> keyValueStrings = Arrays.asList( "SOME_VARIABLE_1=SOME_VALUE_1", "SOME_VARIABLE_2=SOME_VALUE_2", "SOME_VARIABLE_3="); Map<String, String> expectedEnvironment = new HashMap<>(); expectedEnvironment.put("SOME_VARIABLE_1", "SOME_VALUE_1"); expectedEnvironment.put("SOME_VARIABLE_2", "SOME_VALUE_2"); expectedEnvironment.put("SOME_VARIABLE_3", ""); Map<String, String> environment = MinikubeDockerEnvParser.parse(keyValueStrings); Assert.assertEquals(expectedEnvironment, environment); } @Test public void testParse_variableNameEmpty() { List<String> keyValueStrings = Arrays.asList("SOME_VARIABLE_1=SOME_VALUE_1", "=SOME_VALUE_2", "SOME_VARIABLE_3="); try { MinikubeDockerEnvParser.parse(keyValueStrings); Assert.fail("Expected an IllegalArgumentException to be thrown"); } catch (IllegalArgumentException ex) { Assert.assertEquals( "Error while parsing minikube's Docker environment: encountered empty environment variable name", ex.getMessage()); } } @Test public void testParse_invalidFormat() { List<String> keyValueStrings = Arrays.asList("SOME_VARIABLE_1=SOME_VALUE_1", "SOME_VARIABLE_2", "SOME_VARIABLE_3="); try { MinikubeDockerEnvParser.parse(keyValueStrings); Assert.fail("Expected an IllegalArgumentException to be thrown"); } catch (IllegalArgumentException ex) { Assert.assertEquals( "Error while parsing minikube's Docker environment: environment variable string not in KEY=VALUE format", ex.getMessage()); } }
AbstractMinikubeMojo extends AbstractMojo { @VisibleForTesting List<String> buildMinikubeCommand() { List<String> execString = new ArrayList<>(); execString.add(minikube); execString.add(getCommand()); if (flags != null) { execString.addAll(flags); } execString.addAll(getMoreFlags()); return execString; } @Override void execute(); }
@Test public void testBuildMinikubeCommand() { spyAbstractMinikubeMojo.setMinikube("path/to/minikube"); spyAbstractMinikubeMojo.setFlags(ImmutableList.of("someFlag1", "someFlag2")); Mockito.when(spyAbstractMinikubeMojo.getCommand()).thenReturn("somecommand"); Mockito.when(spyAbstractMinikubeMojo.getMoreFlags()) .thenReturn(ImmutableList.of("moreFlag1", "moreFlag2")); Assert.assertEquals( Arrays.asList( "path/to/minikube", "somecommand", "someFlag1", "someFlag2", "moreFlag1", "moreFlag2"), spyAbstractMinikubeMojo.buildMinikubeCommand()); }
AbstractMinikubeMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { List<String> minikubeCommand = buildMinikubeCommand(); try { commandExecutorSupplier.get().setLogger(mavenBuildLogger).run(minikubeCommand); } catch (InterruptedException | IOException ex) { throw new MojoExecutionException(getDescription() + " failed", ex); } } @Override void execute(); }
@Test public void testExecute() throws IOException, MojoExecutionException, InterruptedException { List<String> minikubeCommand = Arrays.asList("some", "command"); Mockito.doReturn(minikubeCommand).when(spyAbstractMinikubeMojo).buildMinikubeCommand(); spyAbstractMinikubeMojo.setCommandExecutorSupplier(() -> mockCommandExecutor); spyAbstractMinikubeMojo.setMavenBuildLogger(mockMavenBuildLogger); spyAbstractMinikubeMojo.execute(); Mockito.verify(mockCommandExecutor).setLogger(mockMavenBuildLogger); Mockito.verify(mockCommandExecutor).run(minikubeCommand); }
CommandExecutor { public List<String> run(String... command) throws IOException, InterruptedException { return run(Arrays.asList(command)); } CommandExecutor setLogger(BuildLogger logger); CommandExecutor setEnvironment(Map<String, String> environmentMap); List<String> run(String... command); List<String> run(List<String> command); }
@Test public void testRun_success() throws IOException, InterruptedException { setMockProcessOutput(expectedOutput); List<String> output = testCommandExecutor.run(command); verifyProcessBuilding(command); Assert.assertEquals(expectedOutput, output); Mockito.verifyZeroInteractions(mockBuildLogger); } @Test public void testRun_commandError() throws InterruptedException, IOException { setMockProcessOutput(expectedOutput); Mockito.when(mockProcess.waitFor()).thenReturn(1); try { testCommandExecutor.run(command); Assert.fail("Expected an IOException to be thrown"); } catch (IOException ex) { Assert.assertEquals("command exited with non-zero exit code : 1", ex.getMessage()); verifyProcessBuilding(command); Mockito.verifyZeroInteractions(mockBuildLogger); } }
MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactory); createMinikubeStartTask(); createMinikubeStopTask(); createMinikubeDeleteTask(); } @Override void apply(Project project); }
@Test public void testDefaultMinikubeTasks() { Project project = ProjectBuilder.builder().withProjectDir(tmp.getRoot()).build(); project.getPluginManager().apply(MinikubePlugin.class); ((ProjectInternal) project).evaluate(); TaskContainer t = project.getTasks(); TaskCollection<MinikubeTask> tc = t.withType(MinikubeTask.class); Assert.assertEquals(3, tc.size()); AssertMinikubeTaskConfig(tc, "minikubeStart", "start"); AssertMinikubeTaskConfig(tc, "minikubeStop", "stop"); AssertMinikubeTaskConfig(tc, "minikubeDelete", "delete"); } @Test public void testMinikubeExtensionSetProperties() { Project project = ProjectBuilder.builder().withProjectDir(tmp.getRoot()).build(); project.getPluginManager().apply(MinikubePlugin.class); MinikubeExtension ex = (MinikubeExtension) project.getExtensions().getByName("minikube"); ex.setMinikube("/custom/minikube/path"); TaskContainer t = project.getTasks(); TaskCollection<MinikubeTask> tc = t.withType(MinikubeTask.class); Assert.assertEquals(3, tc.size()); tc.forEach( minikubeTask -> { Assert.assertEquals(minikubeTask.getMinikube(), "/custom/minikube/path"); }); } @Test public void testUserAddedMinikubeTaskConfigured() { Project project = ProjectBuilder.builder().withProjectDir(tmp.getRoot()).build(); project.getPluginManager().apply(MinikubePlugin.class); MinikubeExtension ex = (MinikubeExtension) project.getExtensions().getByName("minikube"); ex.setMinikube("/custom/minikube/path"); MinikubeTask custom = project.getTasks().create("minikubeCustom", MinikubeTask.class); custom.setCommand("custom"); Assert.assertEquals(custom.getMinikube(), "/custom/minikube/path"); Assert.assertEquals(custom.getCommand(), "custom"); Assert.assertArrayEquals(custom.getFlags(), new String[] {}); }
MinikubeExtension { public Map<String, String> getDockerEnv() throws IOException, InterruptedException { return getDockerEnv(""); } MinikubeExtension(Project project, CommandExecutorFactory commandExecutorFactory); String getMinikube(); void setMinikube(String minikube); Property<String> getMinikubeProvider(); Map<String, String> getDockerEnv(); Map<String, String> getDockerEnv(String profile); }
@Test public void testGetDockerEnvWithDefaultProfile() throws IOException, InterruptedException { expectedCommand.add("--profile="); when(commandExecutorMock.run(expectedCommand)).thenReturn(dockerEnvOutput); Assert.assertEquals(expectedMap, minikube.getDockerEnv()); verify(commandExecutorMock).run(expectedCommand); } @Test public void testGetDockerEnvWithTestProfile() throws IOException, InterruptedException { String profile = "testProfile"; expectedCommand.add("--profile=".concat(profile)); when(commandExecutorMock.run(expectedCommand)).thenReturn(dockerEnvOutput); Assert.assertEquals(expectedMap, minikube.getDockerEnv(profile)); verify(commandExecutorMock).run(expectedCommand); } @Test public void testGetSameDockerEnvWithTwoDefaultProfiles() throws IOException, InterruptedException { String profile = ""; expectedCommand.add("--profile=".concat(profile)); when(commandExecutorMock.run(expectedCommand)).thenReturn(dockerEnvOutput); Assert.assertEquals(minikube.getDockerEnv(), minikube.getDockerEnv(profile)); verify(commandExecutorMock, times(2)).run(expectedCommand); } @Test public void testGetDockerEnvWithNullProfile() throws IOException, InterruptedException { try { minikube.getDockerEnv(null); Assert.fail("getDockerEnv() should not permit null values"); } catch (NullPointerException ex) { Assert.assertNotNull(ex.getMessage()); Assert.assertEquals("Minikube profile must not be null", ex.getMessage()); } }
DefaultedURL { @Override public boolean equals(Object o) { if (o instanceof DefaultedURL) { return url.equals(((DefaultedURL) o).getUrl()); } return false; } DefaultedURL(); boolean isDefault(); void setUrl(URL url); String getDomain(); URL getUrl(); @Override String toString(); @Override boolean equals(Object o); }
@Test public void testEquals_true() throws MalformedURLException { DefaultedURL defaultedURL = new DefaultedURL(); DefaultedURL customURL = new DefaultedURL(); assertTrue(defaultedURL.equals(customURL)); }
GatewaysManager { public Gateway select(int nClosest) { Connection.TransportType transportType = getUsePluggableTransports(context) ? OBFS4 : OPENVPN; if (presortedList.size() > 0) { return getGatewayFromPresortedList(nClosest, transportType); } return getGatewayFromTimezoneCalculation(nClosest, transportType); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); }
@Test public void TestSelectN_selectFirstObfs4Connection_returnThirdGateway() { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_two_openvpn_one_pt_gateways.json", null); MockHelper.mockProviderObserver(provider); mockStatic(PreferenceHelper.class); when(PreferenceHelper.getUsePluggableTransports(any(Context.class))).thenReturn(true); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("37.12.247.10", gatewaysManager.select(0).getRemoteIP()); } @Test public void testSelectN_selectFromPresortedGateways_returnsGatewaysInPresortedOrder() { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", "ptdemo_three_mixed_gateways.geoip.json"); MockHelper.mockProviderObserver(provider); mockStatic(PreferenceHelper.class); when(PreferenceHelper.getUsePluggableTransports(any(Context.class))).thenReturn(false); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("manila.bitmask.net", gatewaysManager.select(0).getHost()); assertEquals("moscow.bitmask.net", gatewaysManager.select(1).getHost()); assertEquals("pt.demo.bitmask.net", gatewaysManager.select(2).getHost()); } @Test public void testSelectN_selectObfs4FromPresortedGateways_returnsObfs4GatewaysInPresortedOrder() { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", "ptdemo_three_mixed_gateways.geoip.json"); MockHelper.mockProviderObserver(provider); mockStatic(PreferenceHelper.class); when(PreferenceHelper.getUsePluggableTransports(any(Context.class))).thenReturn(true); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals("moscow.bitmask.net", gatewaysManager.select(0).getHost()); assertEquals("pt.demo.bitmask.net", gatewaysManager.select(1).getHost()); assertNull(gatewaysManager.select(2)); }
VpnConfigGenerator { public HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles() throws ConfigParser.ConfigParseError, NumberFormatException, JSONException, IOException { HashMap<Connection.TransportType, VpnProfile> profiles = new HashMap<>(); profiles.put(OPENVPN, createProfile(OPENVPN)); if (supportsObfs4()) { profiles.put(OBFS4, createProfile(OBFS4)); } return profiles; } VpnConfigGenerator(JSONObject generalConfiguration, JSONObject secrets, JSONObject gateway, int apiVersion); void checkCapabilities(); HashMap<Connection.TransportType, VpnProfile> generateVpnProfiles(); final static String TAG; }
@Test public void testGenerateVpnProfile_v1_tcp_udp() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("gateway_tcp_udp.json"))); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 1); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertFalse(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.get(OPENVPN).getConfigFile(context, false).trim().equals(expectedVPNConfig_v1_tcp_udp.trim())); } @Test public void testGenerateVpnProfile_v1_udp_tcp() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("gateway_udp_tcp.json"))); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 1); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertFalse(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.get(OPENVPN).getConfigFile(context, false).trim().equals(expectedVPNConfig_v1_udp_tcp.trim())); } @Test public void testGenerateVpnProfile_v2_tcp_udp() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("gateway_tcp_udp.json"))); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 2); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertFalse(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.get(OPENVPN).getConfigFile(context, false).trim().equals(expectedVPNConfig_v1_tcp_udp.trim())); } @Test public void testGenerateVpnProfile_v2_udp_tcp() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("gateway_udp_tcp.json"))); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 2); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertFalse(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.get(OPENVPN).getConfigFile(context, false).trim().equals(expectedVPNConfig_v1_udp_tcp.trim())); } @Test public void testGenerateVpnProfile_v3_obfs4() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("ptdemo.bitmask.eip-service.json"))).getJSONArray("gateways").getJSONObject(0); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 3); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertTrue(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.containsKey(OPENVPN)); System.out.println(vpnProfiles.get(OBFS4).getConfigFile(context, false)); assertTrue(vpnProfiles.get(OBFS4).getConfigFile(context, false).trim().equals(expectedVPNConfig_v3_obfs4.trim())); } @Test public void testGenerateVpnProfile_v3_ovpn_tcp_udp() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("ptdemo_pt_tcp_udp.eip-service.json"))).getJSONArray("gateways").getJSONObject(0); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 3); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertTrue(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.containsKey(OPENVPN)); System.out.println(vpnProfiles.get(OPENVPN).getConfigFile(context, false)); assertTrue(vpnProfiles.get(OPENVPN).getConfigFile(context, false).trim().equals(expectedVPNConfig_v3_ovpn_tcp_udp.trim())); } @Test public void testGenerateVpnProfile_v3_ovpn_udp_tcp() throws Exception { gateway = new JSONObject(TestSetupHelper.getInputAsString(getClass().getClassLoader().getResourceAsStream("ptdemo_pt_udp_tcp.eip-service.json"))).getJSONArray("gateways").getJSONObject(0); vpnConfigGenerator = new VpnConfigGenerator(generalConfig, secrets, gateway, 3); HashMap<Connection.TransportType, VpnProfile> vpnProfiles = vpnConfigGenerator.generateVpnProfiles(); assertTrue(vpnProfiles.containsKey(OBFS4)); assertTrue(vpnProfiles.containsKey(OPENVPN)); System.out.println(vpnProfiles.get(OPENVPN).getConfigFile(context, false)); assertTrue(vpnProfiles.get(OPENVPN).getConfigFile(context, false).trim().equals(expectedVPNConfig_v3_ovpn_udp_tcp.trim())); }
GatewaysManager { public int size() { return gateways.size(); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); }
@Test public void testGatewayManagerFromCurrentProvider_noProvider_noGateways() { MockHelper.mockProviderObserver(null); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals(0, gatewaysManager.size()); } @Test public void testGatewayManagerFromCurrentProvider_misconfiguredProvider_noGateways() throws IOException, NullPointerException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_misconfigured_gateway.json", null); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals(0, gatewaysManager.size()); } @Test public void testGatewayManagerFromCurrentProvider_threeGateways() { Provider provider = getProvider(null, null, null, null,null, null, "ptdemo_three_mixed_gateways.json", null); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); assertEquals(3, gatewaysManager.size()); }
GatewaySelector { public Gateway select() { return closestGateway(); } GatewaySelector(List<Gateway> gateways); Gateway select(); Gateway select(int nClosest); }
@Test @UseDataProvider("dataProviderTimezones") public void testSelect(int timezone, String expected) { when(ConfigHelper.getCurrentTimezone()).thenReturn(timezone); gatewaySelector = new GatewaySelector(gatewayList); assertEquals(expected, gatewaySelector.select().getName()); } @Test @UseDataProvider("dataProviderSameDistanceTimezones") public void testSelectSameTimezoneDistance(int timezone, String expected1, String expected2) { when(ConfigHelper.getCurrentTimezone()).thenReturn(timezone); gatewaySelector = new GatewaySelector(gatewayList); assertTrue(gatewaySelector.select().getName().equals(expected1) || gatewaySelector.select().getName().equals(expected2)); } @Test @UseDataProvider("dataProviderSameDistanceTimezones") public void testNClostest_SameTimezoneDistance_chooseGatewayWithSameDistance(int timezone, String expected1, String expected2) { when(ConfigHelper.getCurrentTimezone()).thenReturn(timezone); gatewaySelector = new GatewaySelector(gatewayList); ArrayList<String> gateways = new ArrayList<>(); gateways.add(gatewaySelector.select(0).getName()); gateways.add(gatewaySelector.select(1).getName()); assertTrue(gateways.contains(expected1) && gateways.contains(expected2)); } @Test public void testNClostest_OneTimezonePerSet_choseSecondClosestTimezone() { when(ConfigHelper.getCurrentTimezone()).thenReturn(-4); gatewaySelector = new GatewaySelector(gatewayList); assertTrue("Frankfurt".equals(gatewaySelector.select(1).getName())); }
Provider implements Parcelable { @Override public boolean equals(Object o) { if (o instanceof Provider) { Provider p = (Provider) o; return p.getDomain().equals(getDomain()) && definition.toString().equals(p.getDefinition().toString()) && eipServiceJson.toString().equals(p.getEipServiceJsonString()) && geoIpJson.toString().equals(p.getGeoIpJsonString()) && providerIp.equals(p.getProviderIp()) && providerApiIp.equals(p.getProviderApiIp()) && apiUrl.equals(p.getApiUrl()) && geoipUrl.equals(p.getGeoipUrl()) && certificatePin.equals(p.getCertificatePin()) && certificatePinEncoding.equals(p.getCertificatePinEncoding()) && caCert.equals(p.getCaCert()) && apiVersion.equals(p.getApiVersion()) && privateKey.equals(p.getPrivateKey()) && vpnCertificate.equals(p.getVpnCertificate()) && allowAnonymous == p.allowsAnonymous() && allowRegistered == p.allowsRegistered(); } else return false; } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); boolean isConfigured(); boolean supportsPluggableTransports(); String getIpForHostname(String host); String getProviderApiIp(); void setProviderApiIp(String providerApiIp); void setProviderIp(String providerIp); String getProviderIp(); void setMainUrl(URL url); void setMainUrl(String url); boolean define(JSONObject providerJson); JSONObject getDefinition(); String getDefinitionString(); String getDomain(); String getMainUrlString(); DefaultedURL getMainUrl(); DefaultedURL getGeoipUrl(); void setGeoipUrl(String url); String getApiUrlString(); String getApiVersion(); boolean hasDefinition(); boolean hasGeoIpJson(); String getCaCert(); String getName(); @Override int describeContents(); @Override void writeToParcel(Parcel parcel, int i); @Override boolean equals(Object o); JSONObject toJson(); @Override int hashCode(); @Override String toString(); void setCaCert(String cert); boolean allowsAnonymous(); boolean allowsRegistered(); void setLastEipServiceUpdate(long timestamp); boolean shouldUpdateEipServiceJson(); void setLastGeoIpUpdate(long timestamp); boolean shouldUpdateGeoIpJson(); boolean setEipServiceJson(JSONObject eipServiceJson); boolean setGeoIpJson(JSONObject geoIpJson); JSONObject getEipServiceJson(); JSONObject getGeoIpJson(); String getGeoIpJsonString(); String getEipServiceJsonString(); boolean isDefault(); String getPrivateKey(); void setPrivateKey(String privateKey); boolean hasPrivateKey(); String getVpnCertificate(); void setVpnCertificate(String vpnCertificate); boolean hasVpnCertificate(); String getCertificatePin(); String getCertificatePinEncoding(); String getCaCertFingerprint(); void reset(); final static String API_URL; static final Parcelable.Creator<Provider> CREATOR; }
@Test public void testEquals_sameFields_returnsTrue() throws Exception { Provider p1 = TestSetupHelper.getConfiguredProvider(); Provider p2 = TestSetupHelper.getConfiguredProvider(); assertTrue("Providers should be same:", p1.equals(p2)); }
Provider implements Parcelable { public void setMainUrl(URL url) { mainUrl.setUrl(url); } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); boolean isConfigured(); boolean supportsPluggableTransports(); String getIpForHostname(String host); String getProviderApiIp(); void setProviderApiIp(String providerApiIp); void setProviderIp(String providerIp); String getProviderIp(); void setMainUrl(URL url); void setMainUrl(String url); boolean define(JSONObject providerJson); JSONObject getDefinition(); String getDefinitionString(); String getDomain(); String getMainUrlString(); DefaultedURL getMainUrl(); DefaultedURL getGeoipUrl(); void setGeoipUrl(String url); String getApiUrlString(); String getApiVersion(); boolean hasDefinition(); boolean hasGeoIpJson(); String getCaCert(); String getName(); @Override int describeContents(); @Override void writeToParcel(Parcel parcel, int i); @Override boolean equals(Object o); JSONObject toJson(); @Override int hashCode(); @Override String toString(); void setCaCert(String cert); boolean allowsAnonymous(); boolean allowsRegistered(); void setLastEipServiceUpdate(long timestamp); boolean shouldUpdateEipServiceJson(); void setLastGeoIpUpdate(long timestamp); boolean shouldUpdateGeoIpJson(); boolean setEipServiceJson(JSONObject eipServiceJson); boolean setGeoIpJson(JSONObject geoIpJson); JSONObject getEipServiceJson(); JSONObject getGeoIpJson(); String getGeoIpJsonString(); String getEipServiceJsonString(); boolean isDefault(); String getPrivateKey(); void setPrivateKey(String privateKey); boolean hasPrivateKey(); String getVpnCertificate(); void setVpnCertificate(String vpnCertificate); boolean hasVpnCertificate(); String getCertificatePin(); String getCertificatePinEncoding(); String getCaCertFingerprint(); void reset(); final static String API_URL; static final Parcelable.Creator<Provider> CREATOR; }
@Test public void testEqualsThroughSetContains_differentFields_returnsFalse() throws Exception { Provider p1 = TestSetupHelper.getConfiguredProvider(); Provider p2 = TestSetupHelper.getConfiguredProvider(); p2.setMainUrl("http: Provider p3 = new Provider("https: Set<Provider> defaultProviders = new HashSet<>(); defaultProviders.add(p1); defaultProviders.add(p2); assertTrue(defaultProviders.contains(p1)); assertTrue(defaultProviders.contains(p2)); assertFalse(defaultProviders.contains(p3)); }
Provider implements Parcelable { public boolean supportsPluggableTransports() { try { JSONArray gatewayJsons = eipServiceJson.getJSONArray(GATEWAYS); for (int i = 0; i < gatewayJsons.length(); i++) { JSONArray transports = gatewayJsons.getJSONObject(i). getJSONObject(CAPABILITIES). getJSONArray(TRANSPORT); for (int j = 0; j < transports.length(); j++) { if (OBFS4.toString().equals(transports.getJSONObject(j).getString(TYPE))) { return true; } } } } catch (Exception e) { } return false; } Provider(); Provider(String mainUrl); Provider(String mainUrl, String geoipUrl); Provider(String mainUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp); Provider(String mainUrl, String geoipUrl, String providerIp, String providerApiIp, String caCert, String definition); private Provider(Parcel in); boolean isConfigured(); boolean supportsPluggableTransports(); String getIpForHostname(String host); String getProviderApiIp(); void setProviderApiIp(String providerApiIp); void setProviderIp(String providerIp); String getProviderIp(); void setMainUrl(URL url); void setMainUrl(String url); boolean define(JSONObject providerJson); JSONObject getDefinition(); String getDefinitionString(); String getDomain(); String getMainUrlString(); DefaultedURL getMainUrl(); DefaultedURL getGeoipUrl(); void setGeoipUrl(String url); String getApiUrlString(); String getApiVersion(); boolean hasDefinition(); boolean hasGeoIpJson(); String getCaCert(); String getName(); @Override int describeContents(); @Override void writeToParcel(Parcel parcel, int i); @Override boolean equals(Object o); JSONObject toJson(); @Override int hashCode(); @Override String toString(); void setCaCert(String cert); boolean allowsAnonymous(); boolean allowsRegistered(); void setLastEipServiceUpdate(long timestamp); boolean shouldUpdateEipServiceJson(); void setLastGeoIpUpdate(long timestamp); boolean shouldUpdateGeoIpJson(); boolean setEipServiceJson(JSONObject eipServiceJson); boolean setGeoIpJson(JSONObject geoIpJson); JSONObject getEipServiceJson(); JSONObject getGeoIpJson(); String getGeoIpJsonString(); String getEipServiceJsonString(); boolean isDefault(); String getPrivateKey(); void setPrivateKey(String privateKey); boolean hasPrivateKey(); String getVpnCertificate(); void setVpnCertificate(String vpnCertificate); boolean hasVpnCertificate(); String getCertificatePin(); String getCertificatePinEncoding(); String getCaCertFingerprint(); void reset(); final static String API_URL; static final Parcelable.Creator<Provider> CREATOR; }
@Test public void testIsPluggableTransportsSupported_Obfs4_returnsTrue() throws Exception { Provider p1 = TestSetupHelper.getProvider( "https: null, null, null, null, null, "ptdemo.bitmask.eip-service.json", null); assertTrue(p1.supportsPluggableTransports()); } @Test public void testIsPluggableTransportsSupported_noObfs4_returnsFalse() throws Exception { Provider p1 = TestSetupHelper.getProvider( null, null, null, null, null, null, "eip-service-two-gateways.json", null); assertFalse(p1.supportsPluggableTransports()); }
GatewaysManager { public int getPosition(VpnProfile profile) { if (presortedList.size() > 0) { return getPositionFromPresortedList(profile); } return getPositionFromTimezoneCalculatedList(profile); } GatewaysManager(Context context); Gateway select(int nClosest); int getPosition(VpnProfile profile); boolean isEmpty(); int size(); @Override String toString(); }
@Test public void TestGetPosition_VpnProfileExtistingObfs4_returnPositionZero() throws JSONException, ConfigParser.ConfigParseError, IOException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", null); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator configGenerator = new VpnConfigGenerator(provider.getDefinition(), secrets, gateway1, 3); VpnProfile profile = configGenerator.createProfile(OBFS4); profile.mGatewayIp = "37.218.247.60"; assertEquals(0, gatewaysManager.getPosition(profile)); } @Test public void TestGetPosition_VpnProfileExtistingOpenvpn_returnPositionZero() throws JSONException, ConfigParser.ConfigParseError, IOException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", null); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator configGenerator = new VpnConfigGenerator(provider.getDefinition(), secrets, gateway1, 3); VpnProfile profile = configGenerator.createProfile(OPENVPN); profile.mGatewayIp = "37.218.247.60"; assertEquals(0, gatewaysManager.getPosition(profile)); } @Test public void TestGetPosition_VpnProfileExistingObfs4FromPresortedList_returnsPositionOne() throws JSONException, ConfigParser.ConfigParseError, IOException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", "ptdemo_three_mixed_gateways.geoip.json"); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator configGenerator = new VpnConfigGenerator(provider.getDefinition(), secrets, gateway1, 3); VpnProfile profile = configGenerator.createProfile(OBFS4); profile.mGatewayIp = "37.218.247.60"; assertEquals(1, gatewaysManager.getPosition(profile)); } @Test public void TestGetPosition_VpnProfileExistingOpenvpnFromPresortedList_returnsPositionOne() throws JSONException, ConfigParser.ConfigParseError, IOException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", "ptdemo_three_mixed_gateways.geoip.json"); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator configGenerator = new VpnConfigGenerator(provider.getDefinition(), secrets, gateway1, 3); VpnProfile profile = configGenerator.createProfile(OPENVPN); profile.mGatewayIp = "37.218.247.60"; assertEquals(2, gatewaysManager.getPosition(profile)); } @Test public void TestGetPosition_VpnProfileDifferentIp_returnMinusOne() throws JSONException, ConfigParser.ConfigParseError, IOException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", null); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(0); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator configGenerator = new VpnConfigGenerator(provider.getDefinition(), secrets, gateway1, 3); VpnProfile profile = configGenerator.createProfile(OBFS4); profile.mGatewayIp = "37.218.247.61"; assertEquals(-1, gatewaysManager.getPosition(profile)); } @Test public void TestGetPosition_VpnProfileMoscow_returnOne() throws JSONException, ConfigParser.ConfigParseError, IOException { Provider provider = getProvider(null, null, null, null, null, null, "ptdemo_three_mixed_gateways.json", null); JSONObject eipServiceJson = provider.getEipServiceJson(); JSONObject gateway1 = eipServiceJson.getJSONArray(GATEWAYS).getJSONObject(1); MockHelper.mockProviderObserver(provider); GatewaysManager gatewaysManager = new GatewaysManager(mockContext); VpnConfigGenerator configGenerator = new VpnConfigGenerator(provider.getDefinition(), secrets, gateway1, 3); VpnProfile profile = configGenerator.createProfile(OBFS4); profile.mGatewayIp = "3.21.247.89"; assertEquals(1, gatewaysManager.getPosition(profile)); }
RotationOrderDetector implements OrderDetector { public double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept) throws StructureException { if(intercept) { int[] orders = new int[maxOrder+1]; for(int i=0;i<=maxOrder;i++) { orders[i] = i; } return getWeightsForFit(ca, axis, orders); } else { int[] orders = new int[maxOrder]; for(int i=0;i<maxOrder;i++) { orders[i] = i+1; } double[] amps = getWeightsForFit(ca, axis, orders); double[] ampIntercept = new double[maxOrder+1]; ampIntercept[0] = 0.; for(int i=0;i<maxOrder;i++) { ampIntercept[i+1] = amps[i]; } return ampIntercept; } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; }
@Test public void testFitHarmonics() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, HARMONICS); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.tryAllOrders(ca1, axis, false); expectedHarmonics = new double[] { 0, 1.218482, 2.110836, 0.7203669, 0.8226358, 0.6092911, 0.6339138, 0.4439472, 0.4737434, }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "d1ijqa1"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.tryAllOrders(ca1, axis, false); expectedHarmonics = new double[] { 0, 0.5176411, 0.5359353, 0.4928912, 0.5044149, 0.4031307, 1.915722, 0.4049375, 0.4456366 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); } @Test public void testFitHarmonicsFloating() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, HARMONICS_FLOATING); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.tryAllOrders(ca1, axis, true); expectedHarmonics = new double[] { 2.597383371368633, 0.5213221707509845, 1.4121594197036587, 0.06167606937029615, 0.17901478726304354, 0.019300560598982656, 0.06908612977051289, -0.06104875791630157, -0.003831898183546225 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "d1ijqa1"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.tryAllOrders(ca1, axis, true); expectedHarmonics = new double[] { 1.2739427717435365, 0.2761280960318058, 0.2718581473051768, 0.22837118857649835, 0.20840059641118155, 0.10054298829557395, 1.5787950609554844, 0.06204472152219612, 0.07230120934912426 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "1TIM.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.tryAllOrders(ca1, axis, true); expectedHarmonics = new double[] { 2.835403848327179, 0.1468762702349724, 0.1159408606767334, 0.09051681783286569, 0.10420798340774699, -0.04381730637594528, 0.2023844545733075, -0.0059047948160164, 0.17631879026416564 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); }
CeSymmMain { public static List<String> parseInputStructures(String filename) throws FileNotFoundException { File file = new File(filename); Scanner s = new Scanner(file); List<String> structures = new ArrayList<String>(); while (s.hasNext()) { String name = s.next(); if (name.startsWith("#")) { s.nextLine(); } else { structures.add(name); } } s.close(); return structures; } static void main(String[] args); static List<String> parseInputStructures(String filename); }
@Test public void testParseInput() throws FileNotFoundException { URL url = CeSymmMainTest.class.getResource("/cesymmtest.txt"); String filename = url.getFile(); List<String> names = CeSymmMain.parseInputStructures(filename); assertEquals(6,names.size()); int i = 0; assertEquals("d1ijqa1",names.get(i++)); assertEquals("1G6S",names.get(i++)); assertEquals("1MER.A",names.get(i++)); assertEquals("d1h70a_",names.get(i++)); assertEquals("2YMS_A:,C:,B:,D:",names.get(i++)); assertEquals("1HIV",names.get(i++)); }
RotationOrderDetector implements OrderDetector { @Override public int calculateOrder(AFPChain afpChain, Atom[] ca) throws RefinerFailedException { try { RotationAxis axis = new RotationAxis(afpChain); if(!axis.isDefined()) { return 1; } switch(method) { case HARMONICS: { double[] coefficients = tryAllOrders(ca, axis, false); return maxIndex(coefficients, 1); } case HARMONICS_FLOATING: { double[] coefficients = tryAllOrders(ca, axis, true); return maxIndex(coefficients, 1); } case SINGLE_HARMONIC_AMP: case SINGLE_CUSP_AMP: case SINGLE_CUSP_FIXED_AMP: { double[] coefficients = trySingleOrdersByAmp(ca,axis); return maxIndex(coefficients,0) + 1; } case SINGLE_HARMONIC_SSE: case SINGLE_CUSP_SSE: case SINGLE_CUSP_FIXED_SSE: { double[] coefficients = trySingleOrdersBySSE(ca,axis); return minIndex(coefficients,0) + 1; } default: throw new UnsupportedOperationException("Unimplemented method "+method); } } catch (StructureException e) { throw new RefinerFailedException(e); } } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; }
@Test public void testCalculateOrderByHarmonics() throws IOException, StructureException, RefinerFailedException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, HARMONICS); Atom[] ca1; AFPChain alignment; int order; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); order = detector.calculateOrder(alignment, ca1); assertEquals(name, 2, order); name = "d1ijqa1"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); order = detector.calculateOrder(alignment, ca1); assertEquals(name, 6, order); name = "1TIM.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); order = detector.calculateOrder(alignment, ca1); assertEquals(name, 1, order); } @Test public void testCalculateOrderByHarmonicsFloating() throws IOException, StructureException, RefinerFailedException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, HARMONICS_FLOATING); Atom[] ca1; AFPChain alignment; int order; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); order = detector.calculateOrder(alignment, ca1); assertEquals(name, 2, order); name = "d1ijqa1"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); order = detector.calculateOrder(alignment, ca1); assertEquals(name, 6, order); name = "1TIM.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); order = detector.calculateOrder(alignment, ca1); assertEquals(name, 6, order); }
RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis) throws StructureException { double[] amps = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { double[] weights = getWeightsForFit(ca, axis, new int[] {0,order}); amps[order-1] = weights[1]; } return amps; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; }
@Test public void testTrySingleHarmonicsFloatingByAmp() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, SINGLE_HARMONIC_AMP); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { 0.009384193201414186, 1.1740333517311115, -0.44686757545089734, -0.2884995929083228, -0.2677652242044436, -0.19546335129315567, -0.15476867112456613, -0.09201871044036189 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "d1ijqa1"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { -0.09799681735927843, -0.21364824515873054, -0.11035897329374683, -0.21342288908870446, -0.1855205123692191, 1.4483981845191647, -0.14753158983373432, -0.20318262394650666 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "1TIM.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { 0.05425570731331745, -0.019746339856520342, -0.007014170110096962, -0.010253935127542774, -0.1363341693467633, 0.13180804348846586, -0.06217377718239171, 0.13580312417478568 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); } @Test public void testTrySingleCuspByAmp() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, SINGLE_CUSP_AMP); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { 0.1820283077630485, 1.0136815511756285, -0.3905901172609695, -0.26201199397108704, -0.20690437223329403, -0.1616881748238757, -0.11567568721588678, -0.08632416298270444 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "d1ijqa1"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { -0.1476801436899504, -0.12885346994573413, 0.16933007895862143, -0.21743126249158864, -0.18435161092570687, 1.1878594622938643, -0.13766536861375353, -0.1779357492984687 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); name = "1TIM.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { 0.048573997778241465, -0.004122183485246968, 0.016836424264462534, 0.011565079482636204, -0.11506791209963799, 0.10046269754081401, -0.055177206937627045, 0.10338290890177872 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); } @Test public void testTrySingleCuspFixedByAmp() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, SINGLE_CUSP_FIXED_AMP); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getAtomCAArray(StructureTools.getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersByAmp(ca1, axis); expectedHarmonics = new double[] { 0.1287134, 1.030371, -0.5324238, -0.4618442, -0.5114463, -0.4755183, -0.4395435, -0.3174656 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); }
RotationOrderDetector implements OrderDetector { public double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis) throws StructureException { double[] sses = new double[maxOrder]; for( int order=1;order <= maxOrder; order++) { sses[order-1] = getSSEForFit(ca, axis, new int[] {0,order}); } return sses; } RotationOrderDetector(); RotationOrderDetector(int maxOrder); RotationOrderDetector(int maxOrder, RotationOrderMethod method); @Override String toString(); void setMethod(RotationOrderMethod m); RotationOrderMethod getMethod(); int getMaxOrder(); void setMaxOrder(int maxOrder); double getAngleIncr(); void setAngleIncr(double angleIncr); @Override int calculateOrder(AFPChain afpChain, Atom[] ca); static Pair<double[],double[]> sampleRotations(Atom[] ca, RotationAxis axis, double degreesIncrement); static double superpositionDistance(Atom[] ca1, Atom[] ca2); double[] trySingleOrdersBySSE(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis); double[] trySingleOrdersByAmp(Atom[] ca, RotationAxis axis,int[] orders); double[] tryAllOrders(Atom[] ca, RotationAxis axis,boolean intercept); static final double DEFAULT_ANGLE_INCR; }
@Test public void testTrySingleHarmonicsFloatingBySSE() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, SINGLE_HARMONIC_SSE); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersBySSE(ca1, axis); expectedHarmonics = new double[] { 0.4072455479103931, 0.14067952827982602, 0.3779933525800668, 0.39480256016817444, 0.3960406707063868, 0.4012976706684556, 0.4035501028422771, 0.4059768120251738 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); } @Test public void testTrySingleCuspBySSE() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, SINGLE_CUSP_SSE); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getRepresentativeAtomArray(StructureTools .getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersBySSE(ca1, axis); expectedHarmonics = new double[] { 0.4023477, 0.1620938, 0.3740037, 0.3923604, 0.3973309, 0.4011318, 0.4041583, 0.4054583 }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-4); } @Test public void testTrySingleCuspFixedBySSE() throws IOException, StructureException { String name; RotationOrderDetector detector = new RotationOrderDetector(8, SINGLE_CUSP_FIXED_SSE); Atom[] ca1; AFPChain alignment; RotationAxis axis; double[] coefs, expectedHarmonics; name = "1MER.A"; ca1 = StructureTools.getAtomCAArray(StructureTools.getStructure(name)); alignment = CeSymm.analyze(ca1, params).getSelfAlignment(); axis = new RotationAxis(alignment); coefs = detector.trySingleOrdersBySSE(ca1, axis); expectedHarmonics = new double[] { 0.4023477, 0.1485084, 0.3794772, 0.3946517, 0.3969921, 0.4006527, 0.4033445, 0.4056923, }; assertArrayEquals(name, expectedHarmonics, coefs, 1e-2); }
PrincipalAutoSuggestion { public List<Principal> autoSuggestion(final String name) { if (name.length() >= 3) { String lowerCaseName = name.toLowerCase(); ListRolesRequest listRolesRequest = new ListRolesRequest(); listRolesRequest.withMaxItems(1000); ListRolesResult result = client.listRoles(listRolesRequest); List<Principal> tmp = result.getRoles().stream() .filter(p -> p.getRoleName().toLowerCase().contains(lowerCaseName)) .map(p -> new Principal(PrincipalType.ROLE, p.getRoleName())).collect(Collectors.toList()); return tmp.subList(0, Math.min(5, tmp.size())); } return new ArrayList<>(); } PrincipalAutoSuggestion(AmazonIdentityManagement client); static PrincipalAutoSuggestion fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); List<Principal> autoSuggestion(final String name); }
@Test public void testAutoSuggestion() throws Exception { ListRolesRequest request = new ListRolesRequest().withMaxItems(1000); Role role1 = new Role().withRoleName("foobar1"); Role role2 = new Role().withRoleName("afoobar"); Role role3 = new Role().withRoleName("foooobar"); ListRolesResult mockResult = new ListRolesResult(); mockResult.withRoles(role1, role2, role3); when(mockClient.listRoles(request)).thenReturn(mockResult); List<Principal> list = partiallyMockedPrincipalAutoSuggestion.autoSuggestion("foobar"); assertEquals(list.size(), 2); assertEquals(list.get(0).name, "foobar1"); assertEquals(list.get(1).name, "afoobar"); verify(mockClient, times(1)).listRoles(request); } @Test public void testAutoSuggestionShortName() throws Exception { ListRolesRequest request = new ListRolesRequest().withMaxItems(1000); List<Principal> list = partiallyMockedPrincipalAutoSuggestion.autoSuggestion("fo"); assertTrue(list.isEmpty()); verify(mockClient, never()).listRoles(request); } @Test public void testAutoSuggestionCaseInsensitive() throws Exception { ListRolesRequest request = new ListRolesRequest().withMaxItems(1000); Role lowercase = new Role().withRoleName("foobar"); Role uppercase = new Role().withRoleName("FOOBAR"); Role mixedCase = new Role().withRoleName("FooBar"); ListRolesResult mockResult = new ListRolesResult(); mockResult.withRoles(lowercase, uppercase, mixedCase); when(mockClient.listRoles(request)).thenReturn(mockResult); List<Principal> list = partiallyMockedPrincipalAutoSuggestion.autoSuggestion("fOOb"); assertEquals(list.size(), 3); assertEquals(list.get(0).name, "foobar"); assertEquals(list.get(1).name, "FOOBAR"); assertEquals(list.get(2).name, "FooBar"); }
DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public List<StringSecretEntry> getAllStringSecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.UTF8) .map(StringSecretEntry::of) .collect(Collectors.toList()); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); }
@Test public void getAllStringSecrets() { List<StringSecretEntry> secrets = simpleSecretsGroup.getAllStringSecrets(); StringSecretEntry one = new StringSecretEntry(stringSecretIdentifier2, 1l, stringSecretValue2.asString()); StringSecretEntry two = new StringSecretEntry(stringSecretIdentifier3, 1l, stringSecretValue3.asString()); assertThat(secrets, is(Arrays.asList(one, two))); }
DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public List<ByteSecretEntry> getAllBinarySecrets() { return secretsGroup.getLatestActiveVersionOfAllSecrets() .stream() .filter(secretEntry -> secretEntry.secretValue.encoding == Encoding.BINARY) .map(ByteSecretEntry::of) .collect(Collectors.toList()); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); }
@Test public void getAllByteSecrets() { List<ByteSecretEntry> secrets = simpleSecretsGroup.getAllBinarySecrets(); ByteSecretEntry one = new ByteSecretEntry(binarySecretIdentifier2, 1l, binarySecretValue2.asByteArray()); ByteSecretEntry two = new ByteSecretEntry(binarySecretIdentifier3, 1l, binarySecretValue3.asByteArray()); assertThat(secrets, is(Arrays.asList(one, two))); }
DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); }
@Test public void getStringSecret() { Optional<String> result = simpleSecretsGroup.getStringSecret(stringSecretIdentifier); assertThat(result, is(Optional.of(value1))); } @Test public void versioned_getStringSecret() { Optional<String> result = simpleSecretsGroup.getStringSecret(stringSecretIdentifier, version); assertThat(result, is(Optional.of(value2))); } @Test public void not_present_getStringSecret() { Optional<String> result = simpleSecretsGroup.getStringSecret(notPresent); assertThat(result, is(Optional.empty())); } @Test public void not_present_versioned_getStringSecret() { Optional<String> result = simpleSecretsGroup.getStringSecret(notPresent, version); assertThat(result, is(Optional.empty())); } @Test(expectedExceptions = EncodingException.class) public void getStringSecret_on_binary_secret() { simpleSecretsGroup.getStringSecret(binarySecretIdentifier); }
DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final RoleARN role); DefaultSimpleSecretsGroup(final SecretsGroupIdentifier groupIdentifier, final AWSCredentialsProvider credentialsProvider); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier); @Override Optional<String> getStringSecret(String secretIdentifier); @Override Optional<String> getStringSecret(final SecretIdentifier secretIdentifier, long version); @Override Optional<String> getStringSecret(String secretIdentifier, long version); @Override List<StringSecretEntry> getAllStringSecrets(); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier); @Override Optional<byte[]> getBinarySecret(String secretIdentifier); @Override Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier, final long version); @Override Optional<byte[]> getBinarySecret(String secretIdentifier, long version); @Override List<ByteSecretEntry> getAllBinarySecrets(); }
@Test public void getBinarySecret() { Optional<byte[]> result = simpleSecretsGroup.getBinarySecret(binarySecretIdentifier); assertThat(result, is(Optional.of(value3))); } @Test public void versioned_getBinarySecret() { Optional<byte[]> result = simpleSecretsGroup.getBinarySecret(binarySecretIdentifier, version); assertThat(result, is(Optional.of(value4))); } @Test public void not_present_getBinarySecret() { Optional<byte[]> result = simpleSecretsGroup.getBinarySecret(notPresent); assertThat(result, is(Optional.empty())); } @Test public void not_present_versioned_getBinarySecret() { Optional<byte[]> result = simpleSecretsGroup.getBinarySecret(notPresent, version); assertThat(result, is(Optional.empty())); } @Test(expectedExceptions = EncodingException.class) public void getBinarySecret_on_string_secret() { simpleSecretsGroup.getBinarySecret(stringSecretIdentifier); }
IAMPolicyManager { public void detachReadOnly(SecretsGroupIdentifier group, Principal principal) { detachPrincipal(group,principal, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }
@Test public void testDetachReadonlyRole() throws Exception { Principal principal = new Principal(PrincipalType.ROLE, "awesome-service"); partiallyMockedPolicyManager.detachReadOnly(group, principal); DetachRolePolicyRequest request = new DetachRolePolicyRequest() .withPolicyArn(READONLY_POLICY_ARN) .withRoleName(principal.name); verify(mockClient, times(1)).detachRolePolicy(request); }
IAMPolicyManager { public void detachAllPrincipals(SecretsGroupIdentifier group) { try { List<Principal> admins = listAttachedAdmin(group); admins.forEach(p -> detachAdmin(group, p)); } catch (DoesNotExistException e) { } try { List<Principal> readonly = listAttachedReadOnly(group); readonly.forEach(p -> detachReadOnly(group, p)); } catch (DoesNotExistException e) { } } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }
@Test public void testDetachAllPrincipals() throws Exception { }
IAMPolicyManager { public List<Principal> listAttachedAdmin(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }
@Test public void testListAttachedAdminNoneAttached() throws Exception { ListEntitiesForPolicyRequest request = new ListEntitiesForPolicyRequest() .withPolicyArn(ADMIN_POLICY_ARN); ListEntitiesForPolicyResult result = new ListEntitiesForPolicyResult(); when(mockClient.listEntitiesForPolicy(request)).thenReturn(result); List<Principal> list = partiallyMockedPolicyManager.listAttachedAdmin(group); assertTrue(list.isEmpty()); } @Test public void testListAttachedAdmin() throws Exception { ListEntitiesForPolicyRequest request = new ListEntitiesForPolicyRequest() .withPolicyArn(ADMIN_POLICY_ARN); PolicyGroup policyGroup = new PolicyGroup().withGroupName("awesome-group"); PolicyRole policyRole = new PolicyRole().withRoleName("awesome-service"); PolicyUser policyUser = new PolicyUser().withUserName("bob"); ListEntitiesForPolicyResult result = new ListEntitiesForPolicyResult() .withPolicyGroups(policyGroup) .withPolicyUsers(policyUser) .withPolicyRoles(policyRole); when(mockClient.listEntitiesForPolicy(request)).thenReturn(result); List<Principal> list = partiallyMockedPolicyManager.listAttachedAdmin(group); assertEquals(list.size(), 3); assertEquals(list.get(0), new Principal(PrincipalType.GROUP, "awesome-group")); assertEquals(list.get(1), new Principal(PrincipalType.USER, "bob")); assertEquals(list.get(2), new Principal(PrincipalType.ROLE, "awesome-service")); }
IAMPolicyManager { public List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }
@Test public void testListAttachedReadOnly() throws Exception { ListEntitiesForPolicyRequest request = new ListEntitiesForPolicyRequest() .withPolicyArn(READONLY_POLICY_ARN); PolicyGroup policyGroup = new PolicyGroup().withGroupName("awesome-group"); PolicyRole policyRole = new PolicyRole().withRoleName("awesome-service"); PolicyUser policyUser = new PolicyUser().withUserName("alice"); ListEntitiesForPolicyResult result = new ListEntitiesForPolicyResult() .withPolicyGroups(policyGroup) .withPolicyUsers(policyUser) .withPolicyRoles(policyRole); when(mockClient.listEntitiesForPolicy(request)).thenReturn(result); List<Principal> list = partiallyMockedPolicyManager.listAttachedReadOnly(group); assertEquals(list.size(), 3); assertEquals(list.get(0), new Principal(PrincipalType.GROUP, "awesome-group")); assertEquals(list.get(1), new Principal(PrincipalType.USER, "alice")); assertEquals(list.get(2), new Principal(PrincipalType.ROLE, "awesome-service")); }
IAMPolicyManager { public Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers() { ListPoliciesRequest request = new ListPoliciesRequest(); request.setMaxItems(1000); request.setPathPrefix(PATH_PREFIX); ListPoliciesResult result = client.listPolicies(request); return result.getPolicies().stream() .map(p -> IAMPolicyName.fromString(p.getPolicyName()).group).distinct().collect(Collectors.toSet()); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }
@Test public void testGetSecretsGroupIdentifiersNoGroups() throws Exception { ListPoliciesRequest request = new ListPoliciesRequest().withMaxItems(1000).withPathPrefix("/strongbox/"); when(mockClient.listPolicies(request)).thenReturn(new ListPoliciesResult()); Set<SecretsGroupIdentifier> identifiers = partiallyMockedPolicyManager.getSecretsGroupIdentifiers(); assertTrue(identifiers.isEmpty()); } @Test public void testGetSecretsGroupIdentifiers() throws Exception { ListPoliciesRequest request = new ListPoliciesRequest().withMaxItems(1000).withPathPrefix("/strongbox/"); Policy policyUS1 = new Policy().withPolicyName("strongbox_us-west-1_test-group1_admin"); Policy policyUS2 = new Policy().withPolicyName("strongbox_us-west-1_test-group2_admin"); Policy policyEU1 = new Policy().withPolicyName("strongbox_eu-west-1_test-group1_admin"); Policy policyEU1readonly = new Policy().withPolicyName("strongbox_eu-west-1_test-group1_readonly"); ListPoliciesResult result = new ListPoliciesResult() .withPolicies(policyUS1, policyUS2, policyEU1, policyEU1readonly); when(mockClient.listPolicies(request)).thenReturn(new ListPoliciesResult() .withPolicies(policyUS1, policyUS2, policyEU1, policyEU1readonly)); Set<SecretsGroupIdentifier> identifiers = partiallyMockedPolicyManager.getSecretsGroupIdentifiers(); assertEquals(identifiers.size(), 3); assertTrue(identifiers.contains(new SecretsGroupIdentifier(Region.US_WEST_1, "test.group1"))); assertTrue(identifiers.contains(new SecretsGroupIdentifier(Region.US_WEST_1, "test.group2"))); assertTrue(identifiers.contains(new SecretsGroupIdentifier(Region.EU_WEST_1, "test.group1"))); verify(mockClient, times(1)).listPolicies(request); }
IAMPolicyManager { public String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store) { String adminPolicy = "{\n" + " \"Version\": \"2012-10-17\",\n" + " \"Statement\": [\n" + kmsEncryptor.awsAdminPolicy().get() + ",\n" + storeAdminPolicyString(store) + ",\n" + listAllPolicies() + ",\n" + getPolicyInfo(group) + ",\n" + managePolicies(group) + "\n ]\n" + "}"; return createPolicy(group, AccessLevel.ADMIN, adminPolicy); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }
@Test public void testCreateAdminPolicy() throws Exception { String policyDocument = new String(Files.readAllBytes(Paths.get(TEST_DATA_DIR, "test_admin_policy"))); CreatePolicyRequest request = constructCreatePolicyRequest("admin", policyDocument); CreatePolicyResult result = new CreatePolicyResult().withPolicy(new Policy().withArn(ADMIN_POLICY_ARN)); when(mockClient.createPolicy(request)).thenReturn(result); DescribeKeyRequest keyRequest = new DescribeKeyRequest().withKeyId(KMS_ALIAS_ARN); when(mockKMSClient.describeKey(keyRequest)).thenReturn(constructDescribeKeyResult()); String policyArn = partiallyMockedPolicyManager.createAdminPolicy(group, kmsEncryptor, partiallyMockedStore); verify(mockClient, times(1)).createPolicy(request); verify(mockKMSClient, times(1)).describeKey(keyRequest); assertEquals(policyArn, ADMIN_POLICY_ARN); }
IAMPolicyManager { public String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store) { String readOnlyPolicy = "{\n" + " \"Version\": \"2012-10-17\",\n" + " \"Statement\": [\n" + storeReadOnlyPolicyString(store) + ",\n" + kmsEncryptor.awsReadOnlyPolicy().get() + "\n ]\n" + "}"; return createPolicy(group, AccessLevel.READONLY, readOnlyPolicy); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }
@Test public void testCreateReadOnlyPolicy() throws Exception { String policyDocument = new String(Files.readAllBytes(Paths.get(TEST_DATA_DIR, "test_readonly_policy"))); CreatePolicyRequest request = constructCreatePolicyRequest("readonly", policyDocument); CreatePolicyResult result = new CreatePolicyResult().withPolicy(new Policy().withArn(READONLY_POLICY_ARN)); when(mockClient.createPolicy(request)).thenReturn(result); DescribeKeyRequest keyRequest = new DescribeKeyRequest().withKeyId(KMS_ALIAS_ARN); when(mockKMSClient.describeKey(keyRequest)).thenReturn(constructDescribeKeyResult()); String policyArn = partiallyMockedPolicyManager.createReadOnlyPolicy(group, kmsEncryptor, partiallyMockedStore); verify(mockClient, times(1)).createPolicy(request); verify(mockKMSClient, times(1)).describeKey(keyRequest); assertEquals(policyArn, READONLY_POLICY_ARN); }
IAMPolicyManager { public void deleteAdminPolicy(SecretsGroupIdentifier group) { deletePolicy(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }
@Test public void testDeleteAdminPolicy() throws Exception { DeletePolicyRequest request = new DeletePolicyRequest().withPolicyArn(ADMIN_POLICY_ARN); partiallyMockedPolicyManager.deleteAdminPolicy(group); verify(mockClient, times(1)).deletePolicy(request); }
IAMPolicyManager { public void deleteReadonlyPolicy(SecretsGroupIdentifier group) { deletePolicy(group, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }
@Test public void testDeleteReadonlyPolicy() throws Exception { DeletePolicyRequest request = new DeletePolicyRequest().withPolicyArn(READONLY_POLICY_ARN); partiallyMockedPolicyManager.deleteReadonlyPolicy(group); verify(mockClient, times(1)).deletePolicy(request); }
RegionLocalResourceName { @Override public String toString() { return String.format("%s_%s_%s", PREFIX, group.region.getName(), AWSResourceNameSerialization.encodeSecretsGroupName(group.name)); } RegionLocalResourceName(SecretsGroupIdentifier group); @Override String toString(); static RegionLocalResourceName fromString(String wrappedAWSResourceName); @Override boolean equals(final Object obj); final SecretsGroupIdentifier group; }
@Test public void testToString() throws Exception { assertEquals(resourceName.toString(), resourceAsString); }
RegionLocalResourceName { public static RegionLocalResourceName fromString(String wrappedAWSResourceName) { String[] parts = wrappedAWSResourceName.split(AWSResourceNameSerialization.GLOBAL_STRING_DELIMITER); if (!parts[0].equals(PREFIX)) { throw new InvalidResourceName( wrappedAWSResourceName, "Regional local resource name should start with " + PREFIX); } if (parts.length != 3) { throw new InvalidResourceName( wrappedAWSResourceName, "Regional local resource name should have exactly 3 parts"); } Region region = Region.fromName(parts[1]); String name = AWSResourceNameSerialization.decodeSecretsGroupName(parts[2]); SecretsGroupIdentifier group = new SecretsGroupIdentifier(region, name); return new RegionLocalResourceName(group); } RegionLocalResourceName(SecretsGroupIdentifier group); @Override String toString(); static RegionLocalResourceName fromString(String wrappedAWSResourceName); @Override boolean equals(final Object obj); final SecretsGroupIdentifier group; }
@Test public void testFromString() throws Exception { assertEquals(RegionLocalResourceName.fromString(resourceAsString).group, resourceName.group); assertEquals(RegionLocalResourceName.fromString(resourceAsString).toString(), resourceAsString); } @Test(expectedExceptions = InvalidResourceName.class) public void testFromStringInvalidPrefix() throws Exception { RegionLocalResourceName.fromString("sm_us-west-1_test-group"); } @Test(expectedExceptions = InvalidResourceName.class) public void testFromStringMissingRegion() throws Exception { RegionLocalResourceName.fromString("strongbox_test-group"); }
RegionLocalResourceName { @Override public boolean equals(final Object obj) { if(obj instanceof RegionLocalResourceName){ final RegionLocalResourceName other = (RegionLocalResourceName) obj; return Objects.equal(group, other.group); } else{ return false; } } RegionLocalResourceName(SecretsGroupIdentifier group); @Override String toString(); static RegionLocalResourceName fromString(String wrappedAWSResourceName); @Override boolean equals(final Object obj); final SecretsGroupIdentifier group; }
@Test public void testEquals() { assertTrue(resourceName.equals(resourceName)); assertTrue(resourceName.equals(new RegionLocalResourceName(new SecretsGroupIdentifier(Region.US_WEST_1, "test.group")))); assertFalse(resourceName.equals(new RegionLocalResourceName(new SecretsGroupIdentifier(Region.EU_WEST_1, "test.group")))); assertFalse(resourceName.equals(new RegionLocalResourceName(new SecretsGroupIdentifier(Region.US_WEST_1, "test.group2")))); assertFalse(resourceName.equals(resourceAsString)); }
SessionCache { String resolveFileName() { return String.format("%s--%s.json", profile.name, roleToAssume.toArn().replace(':', '_').replace('/', '-')); } SessionCache(final ProfileIdentifier profile, final RoleARN roleToAssume); Optional<BasicSessionCredentials> load(); void save(final AssumedRoleUser assumedRoleUser, final BasicSessionCredentials credentials, final ZonedDateTime expiration); }
@Test public void resolve_filename() { ProfileIdentifier profile = new ProfileIdentifier("my-profile"); RoleARN arn = new RoleARN("arn:aws:iam::12345678910:role/my-role"); SessionCache sessionCache = new SessionCache(profile, arn); assertThat(sessionCache.resolveFileName(), is("my-profile--arn_aws_iam__12345678910_role-my-role.json")); }
AWSCLIConfigFile { public Config getConfig() { try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { return getConfig(bufferedReader); } catch (Exception e) { throw new RuntimeException(String.format("Failed to load config from '%s': %s", file.getAbsolutePath(), e.getMessage()), e); } } AWSCLIConfigFile(final File file); Config getConfig(); static Optional<File> getCredentialProfilesFile(); static Optional<File> getConfigFile(); }
@Test public void single_section_single_property() { AWSCLIConfigFile configFile = new AWSCLIConfigFile(new File("")); AWSCLIConfigFile.Config config = configFile.getConfig(asBufferedReader("[default]\nkey=value\n")); assertSectionAndPropertyExists(config, "default", new AWSCLIConfigFile.Property("key", "value")); } @Test public void multiple_sections_multiple_properties() { AWSCLIConfigFile configFile = new AWSCLIConfigFile(new File("")); AWSCLIConfigFile.Config config = configFile.getConfig(asBufferedReader("[default]\nkey=value\n[my section]\nkey2=value2\nkey3=value3")); assertSectionAndPropertyExists(config, "default", new AWSCLIConfigFile.Property("key", "value")); assertSectionAndPropertyExists(config, "my section", new AWSCLIConfigFile.Property("key2", "value2")); assertSectionAndPropertyExists(config, "my section", new AWSCLIConfigFile.Property("key3", "value3")); } @Test public void surrounding_spaces_in_section_name() { AWSCLIConfigFile configFile = new AWSCLIConfigFile(new File("")); AWSCLIConfigFile.Config config = configFile.getConfig(asBufferedReader("[ default ]\nkey=value\n")); assertSectionAndPropertyExists(config, "default", new AWSCLIConfigFile.Property("key", "value")); } @Test public void surrounding_spaces_in_property() { AWSCLIConfigFile configFile = new AWSCLIConfigFile(new File("")); AWSCLIConfigFile.Config config = configFile.getConfig(asBufferedReader("[default]\n key = value \n")); assertSectionAndPropertyExists(config, "default", new AWSCLIConfigFile.Property("key", "value")); } @Test public void when_there_are_duplicate_properties_use_the_last() { AWSCLIConfigFile configFile = new AWSCLIConfigFile(new File("")); AWSCLIConfigFile.Config config = configFile.getConfig(asBufferedReader("[default]\nkey=value\n[default]\nkey=value2\n")); assertSectionAndPropertyExists(config, "default", new AWSCLIConfigFile.Property("key", "value2")); }
KMSEncryptor implements Encryptor, ManagedResource { @Override public String encrypt(String plaintext, EncryptionContext context) { return crypto.encryptString(getProvider(), plaintext, context.toMap()).getResult(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, EncryptionStrength encryptionStrength); static KMSEncryptor fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, EncryptionStrength encryptionStrength); @Override String encrypt(String plaintext, EncryptionContext context); @Override String decrypt(String ciphertext, EncryptionContext context); @Override byte[] encrypt(byte[] plaintext, EncryptionContext context); @Override byte[] decrypt(byte[] ciphertext, EncryptionContext context); byte[] generateRandom(Integer numberOfBytes); @Override String create(); String create(boolean allowExistingPendingDeletedOrDisabledKey); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); boolean exists(boolean allowExistingPendingDeletedOrDisabledKey); int pendingDeletionWindowInDays(); }
@Test public void testEncrypt() throws Exception { String plaintext = "jsonblob"; EncryptionContext mockContext = mock(EncryptionContext.class); CryptoResult mockCryptoResult = mock(CryptoResult.class); Map<String, String> contextMap = new HashMap<>(); when(mockContext.toMap()).thenReturn(contextMap); when(mockCryptoResult.getResult()).thenReturn(encryptedPayload); when(mockAwsCrypto.encryptString(mockProvider, plaintext, contextMap)).thenReturn( mockCryptoResult); assertEquals(kmsEncryptor.encrypt(plaintext, mockContext), encryptedPayload); }
KMSEncryptor implements Encryptor, ManagedResource { @Override public String create() { return kmsManager.create(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, EncryptionStrength encryptionStrength); static KMSEncryptor fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, EncryptionStrength encryptionStrength); @Override String encrypt(String plaintext, EncryptionContext context); @Override String decrypt(String ciphertext, EncryptionContext context); @Override byte[] encrypt(byte[] plaintext, EncryptionContext context); @Override byte[] decrypt(byte[] ciphertext, EncryptionContext context); byte[] generateRandom(Integer numberOfBytes); @Override String create(); String create(boolean allowExistingPendingDeletedOrDisabledKey); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); boolean exists(boolean allowExistingPendingDeletedOrDisabledKey); int pendingDeletionWindowInDays(); }
@Test public void testCreate() throws Exception { when(mockKmsManager.create()).thenReturn(KMS_ARN); assertEquals(kmsEncryptor.create(), KMS_ARN); verify(mockKmsManager, times(1)).create(); }
KMSEncryptor implements Encryptor, ManagedResource { @Override public void delete() { kmsManager.delete(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, EncryptionStrength encryptionStrength); static KMSEncryptor fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, EncryptionStrength encryptionStrength); @Override String encrypt(String plaintext, EncryptionContext context); @Override String decrypt(String ciphertext, EncryptionContext context); @Override byte[] encrypt(byte[] plaintext, EncryptionContext context); @Override byte[] decrypt(byte[] ciphertext, EncryptionContext context); byte[] generateRandom(Integer numberOfBytes); @Override String create(); String create(boolean allowExistingPendingDeletedOrDisabledKey); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); boolean exists(boolean allowExistingPendingDeletedOrDisabledKey); int pendingDeletionWindowInDays(); }
@Test public void testDelete() throws Exception { kmsEncryptor.delete(); verify(mockKmsManager, times(1)).delete(); }
KMSEncryptor implements Encryptor, ManagedResource { @Override public Optional<String> awsAdminPolicy() { return kmsManager.awsAdminPolicy(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, EncryptionStrength encryptionStrength); static KMSEncryptor fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, EncryptionStrength encryptionStrength); @Override String encrypt(String plaintext, EncryptionContext context); @Override String decrypt(String ciphertext, EncryptionContext context); @Override byte[] encrypt(byte[] plaintext, EncryptionContext context); @Override byte[] decrypt(byte[] ciphertext, EncryptionContext context); byte[] generateRandom(Integer numberOfBytes); @Override String create(); String create(boolean allowExistingPendingDeletedOrDisabledKey); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); boolean exists(boolean allowExistingPendingDeletedOrDisabledKey); int pendingDeletionWindowInDays(); }
@Test public void testAwsAdminPolicy() throws Exception { String adminPolicy = "Admin policy"; when(mockKmsManager.awsAdminPolicy()).thenReturn(Optional.of(adminPolicy)); assertEquals(kmsEncryptor.awsAdminPolicy().get(),adminPolicy); verify(mockKmsManager, times(1)).awsAdminPolicy(); }
KMSEncryptor implements Encryptor, ManagedResource { @Override public Optional<String> awsReadOnlyPolicy() { return kmsManager.awsReadOnlyPolicy(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, EncryptionStrength encryptionStrength); static KMSEncryptor fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, EncryptionStrength encryptionStrength); @Override String encrypt(String plaintext, EncryptionContext context); @Override String decrypt(String ciphertext, EncryptionContext context); @Override byte[] encrypt(byte[] plaintext, EncryptionContext context); @Override byte[] decrypt(byte[] ciphertext, EncryptionContext context); byte[] generateRandom(Integer numberOfBytes); @Override String create(); String create(boolean allowExistingPendingDeletedOrDisabledKey); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); boolean exists(boolean allowExistingPendingDeletedOrDisabledKey); int pendingDeletionWindowInDays(); }
@Test public void testAwsReadOnlyPolicy() throws Exception { String readonlyPolicy = "Readonly policy"; when(mockKmsManager.awsReadOnlyPolicy()).thenReturn(Optional.of(readonlyPolicy)); assertEquals(kmsEncryptor.awsReadOnlyPolicy().get(), readonlyPolicy); verify(mockKmsManager, times(1)).awsReadOnlyPolicy(); }
KMSEncryptor implements Encryptor, ManagedResource { @Override public String getArn() { return kmsManager.getArn(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, EncryptionStrength encryptionStrength); static KMSEncryptor fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, EncryptionStrength encryptionStrength); @Override String encrypt(String plaintext, EncryptionContext context); @Override String decrypt(String ciphertext, EncryptionContext context); @Override byte[] encrypt(byte[] plaintext, EncryptionContext context); @Override byte[] decrypt(byte[] ciphertext, EncryptionContext context); byte[] generateRandom(Integer numberOfBytes); @Override String create(); String create(boolean allowExistingPendingDeletedOrDisabledKey); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); boolean exists(boolean allowExistingPendingDeletedOrDisabledKey); int pendingDeletionWindowInDays(); }
@Test public void testGetArn() throws Exception { when(mockKmsManager.getArn()).thenReturn(KMS_ARN); assertEquals(kmsEncryptor.getArn(), KMS_ARN); verify(mockKmsManager, times(1)).getArn(); }
KMSEncryptor implements Encryptor, ManagedResource { @Override public boolean exists() { return kmsManager.exists(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, EncryptionStrength encryptionStrength); static KMSEncryptor fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, EncryptionStrength encryptionStrength); @Override String encrypt(String plaintext, EncryptionContext context); @Override String decrypt(String ciphertext, EncryptionContext context); @Override byte[] encrypt(byte[] plaintext, EncryptionContext context); @Override byte[] decrypt(byte[] ciphertext, EncryptionContext context); byte[] generateRandom(Integer numberOfBytes); @Override String create(); String create(boolean allowExistingPendingDeletedOrDisabledKey); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); boolean exists(boolean allowExistingPendingDeletedOrDisabledKey); int pendingDeletionWindowInDays(); }
@Test public void testExists() throws Exception { when(mockKmsManager.exists()).thenReturn(true); assertTrue(kmsEncryptor.exists()); verify(mockKmsManager, times(1)).exists(); }
DefaultEncryptionContext implements EncryptionContext { @Override public Map<String, String> toMap() { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); builder.put("0", Padding.padWithSpaces(groupIdentifier.region.getName(), 14)); builder.put("1", Padding.padWithSpaces(groupIdentifier.name, 64)); builder.put("2", Padding.padWithSpaces(secretIdentifier.name, 128)); builder.put("3", Padding.padWithZeros(secretVersion)); builder.put("4", Padding.singleDigit(state.asByte())); builder.put("5", Padding.isPresent(notBefore)); builder.put("6", Padding.asOptionalString(notBefore)); builder.put("7", Padding.isPresent(notAfter)); builder.put("8", Padding.asOptionalString(notAfter)); return builder.build(); } DefaultEncryptionContext(SecretsGroupIdentifier groupIdentifier, SecretIdentifier secretIdentifier, long secretVersion, State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter); @Override Map<String, String> toMap(); final SecretsGroupIdentifier groupIdentifier; final SecretIdentifier secretIdentifier; final Long secretVersion; final State state; final Optional<ZonedDateTime> notBefore; final Optional<ZonedDateTime> notAfter; }
@Test public void testToMap() { DefaultEncryptionContext context = new DefaultEncryptionContext( new SecretsGroupIdentifier(Region.US_WEST_1, "test.group"), new SecretIdentifier("secret1"), Long.parseUnsignedLong("8446744073709551615"), State.ENABLED, Optional.of(ZonedDateTime.of(2016,1,2,3,4,0,0, ZoneId.of("UTC"))), Optional.empty() ); Map<String, String> map = context.toMap(); assertEquals(map.get("0"), "us-west-1 "); assertEquals(map.get("0").length(), 14); assertEquals(map.get("1"), "test.group "); assertEquals(map.get("1").length(), 64); assertEquals(map.get("2"), "secret1 "); assertEquals(map.get("2").length(), 128); assertEquals(map.get("3"), "08446744073709551615"); assertEquals(map.get("3").length(), 20); assertEquals(map.get("4"), "2"); assertEquals(map.get("4").length(), 1); assertEquals(map.get("5"), "1"); assertEquals(map.get("5").length(), 1); assertEquals(map.get("6"), "00000000001451703840"); assertEquals(map.get("6").length(), 20); assertEquals(map.get("7"), "0"); assertEquals(map.get("7").length(), 1); assertEquals(map.get("8"), "00000000000000000000"); assertEquals(map.get("8").length(), 20); }
IAMPolicyManager { public String getAdminPolicyArn(SecretsGroupIdentifier group) { return getArn(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }
@Test public void testGetAdminPolicyArn() throws Exception { String arn = partiallyMockedPolicyManager.getAdminPolicyArn(group); assertEquals(arn, ADMIN_POLICY_ARN); }
KMSManager implements ManagedResource { public String create(boolean allowExistingPendingDeletedOrDisabledKey) { String arn; Optional<KeyMetadata> current = describeKey(); if (current.isPresent()) { if (!allowExistingPendingDeletedOrDisabledKey) { throw new com.schibsted.security.strongbox.sdk.exceptions.AlreadyExistsException(String.format( "KMS key already exists for group=%s,region=%s, and override not set", group.name, group.region.getName())); } arn = current.get().getArn(); KMSKeyState state = KMSKeyState.fromString(current.get().getKeyState()); switch (state) { case PENDING_DELETION: CancelKeyDeletionRequest request = new CancelKeyDeletionRequest(); request.withKeyId(arn); kms.cancelKeyDeletion(request); case DISABLED: EnableKeyRequest enableKeyRequest = new EnableKeyRequest(); enableKeyRequest.withKeyId(arn); kms.enableKey(enableKeyRequest); break; default: throw new com.schibsted.security.strongbox.sdk.exceptions.AlreadyExistsException(String.format( "KMS key already exists for group=%s,region=%s", group.name, group.region.getName())); } } else { CreateKeyRequest keyRequest = new CreateKeyRequest(); keyRequest.setDescription("This key is automatically managed by Strongbox"); CreateKeyResult result = kms.createKey(keyRequest); arn = result.getKeyMetadata().getArn(); CreateAliasRequest createAliasRequest = new CreateAliasRequest(); createAliasRequest.setAliasName(aliasKeyName); createAliasRequest.setTargetKeyId(arn); kms.createAlias(createAliasRequest); EnableKeyRotationRequest enableKeyRotationRequest = new EnableKeyRotationRequest(); enableKeyRotationRequest.setKeyId(arn); kms.enableKeyRotation(enableKeyRotationRequest); } waitForKeyState(KMSKeyState.ENABLED); return arn; } KMSManager(AWSKMS client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier); static KMSManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier); String create(boolean allowExistingPendingDeletedOrDisabledKey); @Override String create(); byte[] generateRandom(Integer numberOfBytes); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); boolean exists(boolean allowExistingPendingDeletedOrDisabledKey); String getAliasArn(); int pendingDeletionWindowInDays(); }
@Test public void testCreate() throws Exception { CreateKeyRequest createKeyRequest = new CreateKeyRequest().withDescription( "This key is automatically managed by Strongbox"); CreateKeyResult createKeyResult = new CreateKeyResult().withKeyMetadata(new KeyMetadata().withArn(KMS_ARN)); CreateAliasRequest createAliasRequest = new CreateAliasRequest().withAliasName(ALIAS_KEY_NAME).withTargetKeyId(KMS_ARN); when(mockKMSClient.describeKey(describeKeyRequest)) .thenThrow(NotFoundException.class) .thenThrow(NotFoundException.class) .thenReturn(enabledKeyResult()); when(mockKMSClient.createKey(createKeyRequest)).thenReturn(createKeyResult); String arn = kmsManager.create(); assertEquals(arn, KMS_ARN); verify(mockKMSClient, times(3)).describeKey(describeKeyRequest); verify(mockKMSClient, times(1)).createAlias(createAliasRequest); verify(mockKMSClient, times(1)).createKey(createKeyRequest); }
KMSManager implements ManagedResource { @Override public void delete() { deleteAndGetSchedule(); waitForKeyState(KMSKeyState.PENDING_DELETION); } KMSManager(AWSKMS client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier); static KMSManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier); String create(boolean allowExistingPendingDeletedOrDisabledKey); @Override String create(); byte[] generateRandom(Integer numberOfBytes); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); boolean exists(boolean allowExistingPendingDeletedOrDisabledKey); String getAliasArn(); int pendingDeletionWindowInDays(); }
@Test public void testDelete() throws Exception { ScheduleKeyDeletionRequest deleteRequest = new ScheduleKeyDeletionRequest() .withKeyId(KMS_ARN) .withPendingWindowInDays(7); ScheduleKeyDeletionResult deleteResult = new ScheduleKeyDeletionResult(). withDeletionDate(new Date()); when(mockKMSClient.scheduleKeyDeletion(deleteRequest)).thenReturn(deleteResult); when(mockKMSClient.describeKey(describeKeyRequest)) .thenReturn(enabledKeyResult()) .thenReturn(enabledKeyResult()) .thenReturn(constructDescribeKeyResult(KeyState.PendingDeletion)); kmsManager.delete(); verify(mockKMSClient, times(3)).describeKey(describeKeyRequest); verify(mockKMSClient, times(1)).scheduleKeyDeletion(deleteRequest); }
KMSManager implements ManagedResource { @Override public boolean exists() { return exists(false); } KMSManager(AWSKMS client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier); static KMSManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier); String create(boolean allowExistingPendingDeletedOrDisabledKey); @Override String create(); byte[] generateRandom(Integer numberOfBytes); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); boolean exists(boolean allowExistingPendingDeletedOrDisabledKey); String getAliasArn(); int pendingDeletionWindowInDays(); }
@Test public void testExists() throws Exception { when(mockKMSClient.describeKey(describeKeyRequest)).thenReturn(enabledKeyResult()); assertTrue(kmsManager.exists()); }
EncryptionPayload implements BestEffortShred { public String toJsonBlob() { try { return objectMapper.writeValueAsString(this); } catch (JsonProcessingException e) { throw new SerializationException("Failed to serialize to JSON blob", e); } } @JsonCreator EncryptionPayload(@JsonProperty("value") SecretValue value, @JsonProperty("userdata") Optional<UserData> userData, @JsonProperty("created") ZonedDateTime created, Optional<UserAlias> createdBy, @JsonProperty("modified") ZonedDateTime modified, Optional<UserAlias> modifiedBy, @JsonProperty("comment") Optional<Comment> comment); static byte[] computeSHA(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter); static boolean verifyDataIntegrity(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter, byte[] sha); byte[] toByteArray(); static EncryptionPayload fromByteArray(byte[] payload); String toJsonBlob(); static EncryptionPayload fromJsonBlob(String jsonBlob); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override void bestEffortShred(); final SecretValue value; final Optional<UserData> userData; final ZonedDateTime created; final ZonedDateTime modified; final Optional<UserAlias> createdBy; final Optional<UserAlias> modifiedBy; final Optional<Comment> comment; }
@Test(enabled = false) public void testSerialize() { String serialized = encryptionPayload.toJsonBlob(); assertThat(serialized, is(blob)); }
EncryptionPayload implements BestEffortShred { public static EncryptionPayload fromJsonBlob(String jsonBlob) { try { return objectMapper.readValue(jsonBlob, EncryptionPayload.class); } catch (IOException e) { throw new ParseException("Failed to deserialize JSON blob", e); } } @JsonCreator EncryptionPayload(@JsonProperty("value") SecretValue value, @JsonProperty("userdata") Optional<UserData> userData, @JsonProperty("created") ZonedDateTime created, Optional<UserAlias> createdBy, @JsonProperty("modified") ZonedDateTime modified, Optional<UserAlias> modifiedBy, @JsonProperty("comment") Optional<Comment> comment); static byte[] computeSHA(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter); static boolean verifyDataIntegrity(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter, byte[] sha); byte[] toByteArray(); static EncryptionPayload fromByteArray(byte[] payload); String toJsonBlob(); static EncryptionPayload fromJsonBlob(String jsonBlob); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override void bestEffortShred(); final SecretValue value; final Optional<UserData> userData; final ZonedDateTime created; final ZonedDateTime modified; final Optional<UserAlias> createdBy; final Optional<UserAlias> modifiedBy; final Optional<Comment> comment; }
@Test(enabled = false) public void testDeserialize() { EncryptionPayload deserialized = EncryptionPayload.fromJsonBlob(blob); assertThat(deserialized, is(encryptionPayload)); } @Test(expectedExceptions = ParseException.class) public void testDeserializeInvalidJson() { EncryptionPayload deserialized = EncryptionPayload.fromJsonBlob("{!@#$%^"); }
EncryptionPayload implements BestEffortShred { public static EncryptionPayload fromByteArray(byte[] payload) { ByteBuffer byteBuffer = ByteBuffer.wrap(payload); byte version = byteBuffer.get(); if (version != (byte)1) { throw new IllegalStateException(String.format("Expected version 1, got %d", version)); } ZonedDateTime created = FormattedTimestamp.fromEpoch(byteBuffer.getLong()); ZonedDateTime modified = FormattedTimestamp.fromEpoch(byteBuffer.getLong()); Optional<UserAlias> createdBy = readOptionalString(byteBuffer).map(UserAlias::new); Optional<UserAlias> modifiedBy = readOptionalString(byteBuffer).map(UserAlias::new); Encoding encoding = Encoding.fromByte(byteBuffer.get()); SecretType secretType = SecretType.fromByte(byteBuffer.get()); SecretValue value = new SecretValue(readArray(byteBuffer), encoding, secretType); Optional<UserData> userData = readUserData(byteBuffer); Optional<Comment> comment = readComment(byteBuffer); return new EncryptionPayload(value, userData, created, createdBy, modified, modifiedBy, comment); } @JsonCreator EncryptionPayload(@JsonProperty("value") SecretValue value, @JsonProperty("userdata") Optional<UserData> userData, @JsonProperty("created") ZonedDateTime created, Optional<UserAlias> createdBy, @JsonProperty("modified") ZonedDateTime modified, Optional<UserAlias> modifiedBy, @JsonProperty("comment") Optional<Comment> comment); static byte[] computeSHA(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter); static boolean verifyDataIntegrity(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter, byte[] sha); byte[] toByteArray(); static EncryptionPayload fromByteArray(byte[] payload); String toJsonBlob(); static EncryptionPayload fromJsonBlob(String jsonBlob); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override void bestEffortShred(); final SecretValue value; final Optional<UserData> userData; final ZonedDateTime created; final ZonedDateTime modified; final Optional<UserAlias> createdBy; final Optional<UserAlias> modifiedBy; final Optional<Comment> comment; }
@Test void deserializeBinary() { EncryptionPayload deserializedPayload = EncryptionPayload.fromByteArray(binaryBlob); assertThat(deserializedPayload, is(encryptionPayload)); }
EncryptionPayload implements BestEffortShred { @Override public String toString() { return MoreObjects.toStringHelper(this) .add("value", value) .add("userdata", userData) .add("created", created) .add("modified", modified) .add("comment", comment) .toString(); } @JsonCreator EncryptionPayload(@JsonProperty("value") SecretValue value, @JsonProperty("userdata") Optional<UserData> userData, @JsonProperty("created") ZonedDateTime created, Optional<UserAlias> createdBy, @JsonProperty("modified") ZonedDateTime modified, Optional<UserAlias> modifiedBy, @JsonProperty("comment") Optional<Comment> comment); static byte[] computeSHA(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter); static boolean verifyDataIntegrity(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter, byte[] sha); byte[] toByteArray(); static EncryptionPayload fromByteArray(byte[] payload); String toJsonBlob(); static EncryptionPayload fromJsonBlob(String jsonBlob); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override void bestEffortShred(); final SecretValue value; final Optional<UserData> userData; final ZonedDateTime created; final ZonedDateTime modified; final Optional<UserAlias> createdBy; final Optional<UserAlias> modifiedBy; final Optional<Comment> comment; }
@Test public void testToString() { assertEquals( encryptionPayload.toString(), "EncryptionPayload{value=SecretValue{type=opaque, secretEncoding=utf8}, userdata=Optional[UserData{}], " + "created=2016-06-01T00:00Z[UTC], modified=2017-06-01T00:00Z[UTC], " + "comment=Optional[Comment{}]}"); }
EncryptionPayload implements BestEffortShred { public static byte[] computeSHA(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter) { try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(state.asByte()); messageDigest.update(toByteArray(notBefore)); messageDigest.update(toByteArray(notAfter)); return messageDigest.digest(); } catch (NoSuchAlgorithmException e) { throw new SerializationException("Failed to get SHA for encryption payload", e); } } @JsonCreator EncryptionPayload(@JsonProperty("value") SecretValue value, @JsonProperty("userdata") Optional<UserData> userData, @JsonProperty("created") ZonedDateTime created, Optional<UserAlias> createdBy, @JsonProperty("modified") ZonedDateTime modified, Optional<UserAlias> modifiedBy, @JsonProperty("comment") Optional<Comment> comment); static byte[] computeSHA(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter); static boolean verifyDataIntegrity(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter, byte[] sha); byte[] toByteArray(); static EncryptionPayload fromByteArray(byte[] payload); String toJsonBlob(); static EncryptionPayload fromJsonBlob(String jsonBlob); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override void bestEffortShred(); final SecretValue value; final Optional<UserData> userData; final ZonedDateTime created; final ZonedDateTime modified; final Optional<UserAlias> createdBy; final Optional<UserAlias> modifiedBy; final Optional<Comment> comment; }
@Test public void ensureNotCommutative() { byte[] sha1 = EncryptionPayload.computeSHA(State.ENABLED, notAfter, Optional.empty()); byte[] sha2 = EncryptionPayload.computeSHA(State.ENABLED, Optional.empty(), notAfter); assertNotEquals(sha1, sha2, "Should not be able to reorder and have the same hash"); }
EncryptionPayload implements BestEffortShred { @Override public boolean equals(final Object obj) { if(obj instanceof EncryptionPayload){ final EncryptionPayload other = (EncryptionPayload) obj; return Objects.equal(value, other.value) && Objects.equal(userData, other.userData) && Objects.equal(created, other.created) && Objects.equal(modified, other.modified) && Objects.equal(comment, other.comment); } else { return false; } } @JsonCreator EncryptionPayload(@JsonProperty("value") SecretValue value, @JsonProperty("userdata") Optional<UserData> userData, @JsonProperty("created") ZonedDateTime created, Optional<UserAlias> createdBy, @JsonProperty("modified") ZonedDateTime modified, Optional<UserAlias> modifiedBy, @JsonProperty("comment") Optional<Comment> comment); static byte[] computeSHA(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter); static boolean verifyDataIntegrity(State state, Optional<ZonedDateTime> notBefore, Optional<ZonedDateTime> notAfter, byte[] sha); byte[] toByteArray(); static EncryptionPayload fromByteArray(byte[] payload); String toJsonBlob(); static EncryptionPayload fromJsonBlob(String jsonBlob); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override void bestEffortShred(); final SecretValue value; final Optional<UserData> userData; final ZonedDateTime created; final ZonedDateTime modified; final Optional<UserAlias> createdBy; final Optional<UserAlias> modifiedBy; final Optional<Comment> comment; }
@Test public void testEquals() { EncryptionPayload samePayload = new EncryptionPayload(value, userData, created, createdBy, modified, modifiedBy, comment); assertTrue(encryptionPayload.equals(samePayload)); EncryptionPayload differentPayload = new EncryptionPayload(new SecretValue("DifferentValue", SecretType.OPAQUE), userData, created, createdBy, modified, modifiedBy, comment); assertFalse(encryptionPayload.equals(differentPayload)); differentPayload = new EncryptionPayload(value, Optional.of(new UserData("different userdata".getBytes(StandardCharsets.UTF_8))), created, createdBy, modified, modifiedBy, comment); assertFalse(encryptionPayload.equals(differentPayload)); differentPayload = new EncryptionPayload(value, userData, ZonedDateTime.of(2017,12,1,0,0,0,0, ZoneId.of("UTC")), createdBy, modified, modifiedBy, comment); assertFalse(encryptionPayload.equals(differentPayload)); differentPayload = new EncryptionPayload(value, userData, created, createdBy, ZonedDateTime.of(2017,12,1,0,0,0,0, ZoneId.of("UTC")), modifiedBy, comment); assertFalse(encryptionPayload.equals(differentPayload)); differentPayload = new EncryptionPayload(value, userData, created, createdBy, modified, modifiedBy, Optional.of(new Comment("different comment"))); assertFalse(encryptionPayload.equals(differentPayload)); assertFalse(encryptionPayload.equals("some string value")); }
IAMPolicyManager { public String getReadOnlyArn(SecretsGroupIdentifier group) { return getArn(group, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }
@Test public void testGetReadOnlyArn() throws Exception { String arn = partiallyMockedPolicyManager.getReadOnlyArn(group); assertEquals(arn, READONLY_POLICY_ARN); }
FileEncryptionContext implements EncryptionContext { @Override public Map<String, String> toMap() { return ImmutableMap.of( "0", FILE_VERSION, "1", groupIdentifier.region.getName(), "2", groupIdentifier.name); } FileEncryptionContext(SecretsGroupIdentifier groupIdentifier); @Override Map<String, String> toMap(); final SecretsGroupIdentifier groupIdentifier; }
@Test public void testToMap() { FileEncryptionContext context = new FileEncryptionContext( new SecretsGroupIdentifier(Region.EU_WEST_1, "test.group") ); Map<String, String> map = context.toMap(); assertEquals(map.get("0"), "1"); assertEquals(map.get("1"), "eu-west-1"); assertEquals(map.get("2"), "test.group"); }
GenericDynamoDB implements GenericStore<Entry, Primary>, ManagedResource, AutoCloseable { @Override public String create() { readWriteLock.writeLock().lock(); try { CreateTableResult result = client.createTable(constructCreateTableRequest()); waitForTableToBecomeActive(); return result.getTableDescription().getTableArn(); } catch (ResourceInUseException e) { throw new AlreadyExistsException(String.format("There is already a DynamoDB table called '%s'", tableName), e); } finally { readWriteLock.writeLock().unlock(); } } GenericDynamoDB(AmazonDynamoDB client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, Class<Entry> clazz, Converters converters, ReadWriteLock readWriteLock); CreateTableRequest constructCreateTableRequest(); @Override String create(); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); @Override void create(Entry entry); @Override void update(Entry entry, Entry existingEntry); @Override void delete(Primary partitionKeyValue); @Override Set<Primary> keySet(); @Override KVStream<Entry> stream(); @Override void close(); }
@Test public void testCreateEntry() throws Exception { RawSecretEntry rawSecretEntry = constructRawEntry(SECRET_NAME); UpdateItemRequest expectedUpdateRequest = constructUpdateItemRequest(rawSecretEntry, false, Optional.empty()); dynamoDB.create(rawSecretEntry); verify(mockDynamoDBClient, times(1)).updateItem(expectedUpdateRequest); } @Test public void testCreateEntryAlreadyExists() throws Exception { RawSecretEntry rawSecretEntry = constructRawEntry(SECRET_NAME); UpdateItemRequest expectedUpdateRequest = constructUpdateItemRequest(rawSecretEntry, false, Optional.empty()); when(mockDynamoDBClient.updateItem(expectedUpdateRequest)).thenThrow( new ConditionalCheckFailedException("")); boolean exceptionThrown = false; try { dynamoDB.create(rawSecretEntry); } catch (AlreadyExistsException e) { assertEquals(e.getMessage(), "DynamoDB store entry already exists:{1={S: secret1,}, 2={N: 1,}}"); exceptionThrown = true; } assertTrue(exceptionThrown); verify(mockDynamoDBClient, times(1)).updateItem(expectedUpdateRequest); }
GenericDynamoDB implements GenericStore<Entry, Primary>, ManagedResource, AutoCloseable { @Override public void update(Entry entry, Entry existingEntry) { readWriteLock.writeLock().lock(); try { Map<String, AttributeValue> keys = createKey(entry); Map<String, AttributeValueUpdate> attributes = createAttributes(entry); Map<String, ExpectedAttributeValue> expected = expectExists(existingEntry); try { executeUpdate(keys, attributes, expected); } catch (ConditionalCheckFailedException e) { throw new DoesNotExistException("Precondition to update entry in DynamoDB failed:" + keys.toString()); } } finally { readWriteLock.writeLock().unlock(); } } GenericDynamoDB(AmazonDynamoDB client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, Class<Entry> clazz, Converters converters, ReadWriteLock readWriteLock); CreateTableRequest constructCreateTableRequest(); @Override String create(); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); @Override void create(Entry entry); @Override void update(Entry entry, Entry existingEntry); @Override void delete(Primary partitionKeyValue); @Override Set<Primary> keySet(); @Override KVStream<Entry> stream(); @Override void close(); }
@Test public void testUpdateEntry() throws Exception { RawSecretEntry rawSecretEntry = constructRawEntry(SECRET_NAME); RawSecretEntry alternativeRawSecretEntry = constructAlternativeRawSecretEntry(SECRET_NAME); UpdateItemRequest expectedUpdateRequest = constructUpdateItemRequest(rawSecretEntry, true, Optional.of(alternativeRawSecretEntry)); dynamoDB.update(rawSecretEntry, alternativeRawSecretEntry); verify(mockDynamoDBClient, times(1)).updateItem(expectedUpdateRequest); } @Test public void testUpdateEntryDoesNotExist() throws Exception { RawSecretEntry rawSecretEntry = constructRawEntry(SECRET_NAME); RawSecretEntry alternativeRawSecretEntry = constructAlternativeRawSecretEntry(SECRET_NAME); UpdateItemRequest expectedUpdateRequest = constructUpdateItemRequest(rawSecretEntry, true, Optional.of(alternativeRawSecretEntry)); when(mockDynamoDBClient.updateItem(expectedUpdateRequest)).thenThrow( new ConditionalCheckFailedException("")); boolean exceptionThrown = false; try { dynamoDB.update(rawSecretEntry, alternativeRawSecretEntry); } catch (DoesNotExistException e) { assertEquals(e.getMessage(), "Precondition to update entry in DynamoDB failed:{1={S: secret1,}, 2={N: 1,}}"); exceptionThrown = true; } assertTrue(exceptionThrown); verify(mockDynamoDBClient, times(1)).updateItem(expectedUpdateRequest); }
GenericDynamoDB implements GenericStore<Entry, Primary>, ManagedResource, AutoCloseable { @Override public Set<Primary> keySet() { readWriteLock.readLock().lock(); try { return stream() .uniquePrimaryKey() .toJavaStream() .map(this::getUnconvertedPartitionKeyValue) .collect(Collectors.toSet()); } finally { readWriteLock.readLock().unlock(); } } GenericDynamoDB(AmazonDynamoDB client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, Class<Entry> clazz, Converters converters, ReadWriteLock readWriteLock); CreateTableRequest constructCreateTableRequest(); @Override String create(); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); @Override void create(Entry entry); @Override void update(Entry entry, Entry existingEntry); @Override void delete(Primary partitionKeyValue); @Override Set<Primary> keySet(); @Override KVStream<Entry> stream(); @Override void close(); }
@Test public void testKeySet() throws Exception { ScanRequest request = new ScanRequest().withConsistentRead(true).withTableName(tableName); ScanResult result = constructScanResult(); when(mockDynamoDBClient.scan(request)).thenReturn(result); Set<SecretIdentifier> keys = dynamoDB.keySet(); assertEquals(keys.size(), 2); assertTrue(keys.contains(new SecretIdentifier(SECRET_NAME))); assertTrue(keys.contains(new SecretIdentifier(SECRET2_NAME))); verify(mockDynamoDBClient, times(1)).scan(request); } @Test public void testKeySetEmpty() throws Exception { ScanRequest request = new ScanRequest().withConsistentRead(true).withTableName(tableName); ScanResult result = new ScanResult().withCount(0).withItems(new ArrayList<>()); when(mockDynamoDBClient.scan(request)).thenReturn(result); Set<SecretIdentifier> keySet = dynamoDB.keySet(); assertTrue(keySet.isEmpty()); verify(mockDynamoDBClient, times(1)).scan(request); }
GenericDynamoDB implements GenericStore<Entry, Primary>, ManagedResource, AutoCloseable { @Override public void delete() { readWriteLock.writeLock().lock(); try { client.deleteTable(tableName); waitForTableToFinishDeleting(); } finally { readWriteLock.writeLock().unlock(); } } GenericDynamoDB(AmazonDynamoDB client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, Class<Entry> clazz, Converters converters, ReadWriteLock readWriteLock); CreateTableRequest constructCreateTableRequest(); @Override String create(); @Override void delete(); @Override Optional<String> awsAdminPolicy(); @Override Optional<String> awsReadOnlyPolicy(); @Override String getArn(); @Override boolean exists(); @Override void create(Entry entry); @Override void update(Entry entry, Entry existingEntry); @Override void delete(Primary partitionKeyValue); @Override Set<Primary> keySet(); @Override KVStream<Entry> stream(); @Override void close(); }
@Test public void testDeleteSecret() { QueryRequest request = constructQueryRequest(SECRET_NAME); QueryResult result = constructQueryResult(false); when(mockDynamoDBClient.query(request)).thenReturn(result); dynamoDB.delete(new SecretIdentifier(SECRET_NAME)); verify(mockDynamoDBClient, times(1)).query(request); verify(mockDynamoDBClient, times(1)).deleteItem(tableName, constructKey(SECRET_NAME, 1)); verify(mockDynamoDBClient, times(1)).deleteItem(tableName, constructKey(SECRET_NAME, 2)); verify(mockDynamoDBClient, never()).deleteItem(tableName, constructKey(SECRET2_NAME, 1)); } @Test public void testDeleteSecretMaliciousResults() { QueryRequest request = constructQueryRequest(SECRET_NAME); QueryResult maliciousResult = constructQueryResult(true); when(mockDynamoDBClient.query(request)).thenReturn(maliciousResult); boolean consideredMalicious = false; try { dynamoDB.delete(new SecretIdentifier(SECRET_NAME)); } catch (PotentiallyMaliciousDataException e) { consideredMalicious = true; } assertTrue(consideredMalicious); verify(mockDynamoDBClient, times(1)).query(request); verify(mockDynamoDBClient, never()).deleteItem(tableName, constructKey(SECRET_NAME, 1)); verify(mockDynamoDBClient, never()).deleteItem(tableName, constructKey(SECRET_NAME, 2)); verify(mockDynamoDBClient, never()).deleteItem(tableName, constructKey(SECRET2_NAME, 1)); } @Test public void testDeleteSecretNotInTable() { QueryRequest request = constructQueryRequest(SECRET_NAME); QueryResult result = new QueryResult().withCount(0).withItems(new ArrayList<>()); when(mockDynamoDBClient.query(request)).thenReturn(result); dynamoDB.delete(new SecretIdentifier(SECRET_NAME)); verify(mockDynamoDBClient, times(1)).query(request); verify(mockDynamoDBClient, never()).deleteItem(tableName, constructKey(SECRET_NAME, 1)); }
IAMPolicyManager { public void attachAdmin(SecretsGroupIdentifier group, Principal principal) { attachPrincipalToPolicy(group, principal, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }
@Test public void testAttachAdminUser() throws Exception { Principal principal = new Principal(PrincipalType.USER, "alice"); partiallyMockedPolicyManager.attachAdmin(group, principal); AttachUserPolicyRequest request = new AttachUserPolicyRequest() .withPolicyArn(ADMIN_POLICY_ARN) .withUserName(principal.name); verify(mockClient, times(1)).attachUserPolicy(request); } @Test public void testAttachAdminGroup() throws Exception { Principal principal = new Principal(PrincipalType.GROUP, "awesome-team"); partiallyMockedPolicyManager.attachAdmin(group, principal); AttachGroupPolicyRequest request = new AttachGroupPolicyRequest() .withPolicyArn(ADMIN_POLICY_ARN) .withGroupName(principal.name); verify(mockClient, times(1)).attachGroupPolicy(request); }
FilterGenerator { public static String convertNumberToLetters(int number) { int range = 'z'-'a' + 1; StringBuilder sb = new StringBuilder(); do { int last = number % range; sb.append(Character.toChars('a' + last)); number /= range; } while (number != 0); return sb.reverse().toString(); } FilterGenerator(int startCount); FilterGenerator(); Filter process(RSEF.ParsedAttributeCondition<Entry> attributeCondition, Converters converters); Filter createTerm(RSEF.TypedTerm<T> typedTerm, Converters converters); static String getOperator(RSEF.BinaryOpType binaryOpType); static Map<A, B> merge(Map<A, B> left, Map<A, B> right); static String convertNumberToLetters(int number); public int count; }
@Test public void test() { assertThat(FilterGenerator.convertNumberToLetters(0), is("a")); assertThat(FilterGenerator.convertNumberToLetters(1), is("b")); assertThat(FilterGenerator.convertNumberToLetters(26-1), is("z")); assertThat(FilterGenerator.convertNumberToLetters(26), is("ba")); assertThat(FilterGenerator.convertNumberToLetters(26+1), is("bb")); assertThat(FilterGenerator.convertNumberToLetters(26*26-1), is("zz")); assertThat(FilterGenerator.convertNumberToLetters(26*26), is("baa")); assertThat(FilterGenerator.convertNumberToLetters(26*26+1), is("bab")); assertThat(FilterGenerator.convertNumberToLetters(26*26*26-1), is("zzz")); }
FilterGenerator { public <Entry> Filter process(RSEF.ParsedAttributeCondition<Entry> attributeCondition, Converters converters) { if (attributeCondition instanceof RSEF.AndOperator) { RSEF.AndOperator<Entry> current = (RSEF.AndOperator<Entry>) attributeCondition; Filter left = process(current.left, converters); Filter right = process(current.right, converters); Map<String, String> expressionAttributeNames = merge(left.expressionAttributeNames, right.expressionAttributeNames); Map<String, AttributeValue> expressionAttributeValues = merge(left.expressionAttributeValues, right.expressionAttributeValues); String filterExpression = String.format("(%s) AND (%s)", left.filterExpression, right.filterExpression); return new Filter(expressionAttributeNames, expressionAttributeValues, filterExpression); } else if (attributeCondition instanceof RSEF.OrOperator) { RSEF.OrOperator<Entry> current = (RSEF.OrOperator<Entry>) attributeCondition; Filter left = process(current.left, converters); Filter right = process(current.right, converters); Map<String, String> expressionAttributeNames = merge(left.expressionAttributeNames, right.expressionAttributeNames); Map<String, AttributeValue> expressionAttributeValues = merge(left.expressionAttributeValues, right.expressionAttributeValues); String filterExpression = String.format("(%s) OR (%s)", left.filterExpression, right.filterExpression); return new Filter(expressionAttributeNames, expressionAttributeValues, filterExpression); } else if (attributeCondition instanceof RSEF.NotOperator) { RSEF.NotOperator<Entry> current = (RSEF.NotOperator<Entry>) attributeCondition; Filter left = process(current.left, converters); String filterExpression = String.format("NOT (%s)", left.filterExpression); return new Filter(left.expressionAttributeNames, left.expressionAttributeValues, filterExpression); } else if (attributeCondition instanceof RSEF.ComparisonOperator) { RSEF.ComparisonOperator<Entry, ?> current = (RSEF.ComparisonOperator<Entry, ?>) attributeCondition; Filter left = createTerm(current.left, converters); Filter right = createTerm(current.right, converters); Map<String, String> expressionAttributeNames = merge(left.expressionAttributeNames, right.expressionAttributeNames); Map<String, AttributeValue> expressionAttributeValues = merge(left.expressionAttributeValues, right.expressionAttributeValues); String filterExpression = String.format("%s %s %s", left.filterExpression, getOperator(current.binaryOpType), right.filterExpression); return new Filter(expressionAttributeNames, expressionAttributeValues, filterExpression); } else if (attributeCondition instanceof RSEF.ExistsOperator) { RSEF.ExistsOperator<Entry, ?> current = (RSEF.ExistsOperator<Entry, ?>) attributeCondition; Filter left = createTerm(current.reference, converters); String filterExpression = String.format("attribute_exists(%s)", left.filterExpression); return new Filter(left.expressionAttributeNames, filterExpression); } else if (attributeCondition instanceof RSEF.NotExistsOperator) { RSEF.NotExistsOperator<Entry, ?> current = (RSEF.NotExistsOperator<Entry, ?>) attributeCondition; Filter left = createTerm(current.reference, converters); String filterExpression = String.format("attribute_not_exists(%s)", left.filterExpression); return new Filter(left.expressionAttributeNames, filterExpression); } else { throw new UnsupportedTypeException(attributeCondition.getClass().getName()); } } FilterGenerator(int startCount); FilterGenerator(); Filter process(RSEF.ParsedAttributeCondition<Entry> attributeCondition, Converters converters); Filter createTerm(RSEF.TypedTerm<T> typedTerm, Converters converters); static String getOperator(RSEF.BinaryOpType binaryOpType); static Map<A, B> merge(Map<A, B> left, Map<A, B> right); static String convertNumberToLetters(int number); public int count; }
@Test public void test2() { ZonedDateTime notBeforeValue = ZonedDateTime.now(); RSEF.AttributeCondition condition = notAfter.isPresent() .AND(RSEF.NOT(notAfter.get().eq(notBeforeValue))) .OR(notAfter.get().eq(notBeforeValue)) .AND(notBefore.get().eq(notAfter.get())); RSEF.ParsedAttributeCondition ast = Parser.createAST(condition); FilterGenerator filterGenerator = new FilterGenerator(); FilterGenerator.Filter filter = filterGenerator.process(ast, Config.converters); log.info(filter.filterExpression); } @Test public void test3() { RSEF.AttributeCondition condition = notBefore.isNotPresent(); RSEF.ParsedAttributeCondition ast = Parser.createAST(condition); FilterGenerator filterGenerator = new FilterGenerator(); FilterGenerator.Filter filter = filterGenerator.process(ast, Config.converters); log.info(filter.filterExpression); } @Test public void test4() { SecretIdentifier secretIdentifier = new SecretIdentifier("MySecret"); long myVersion = 1; RSEF.KeyCondition condition = name.eq(secretIdentifier).AND(version.le(myVersion)); RSEF.ParsedKeyCondition ast = Parser.createAST(condition); KeyExpressionGenerator generator = new KeyExpressionGenerator(); KeyExpressionGenerator.KeyCondition keyCondition = generator.process(ast, Config.converters); log.info(keyCondition.keyConditionExpression); }
IAMPolicyName { @Override public String toString() { return String.format("%s_%s_%s_%s", AWSResourceNameSerialization.GLOBAL_PREFIX, group.region.getName(), AWSResourceNameSerialization.encodeSecretsGroupName(group.name), accessLevel); } IAMPolicyName(SecretsGroupIdentifier group, AccessLevel accessLevel); @Override String toString(); static IAMPolicyName fromString(String wrappedAWSResourceName); @Override boolean equals(final Object obj); final SecretsGroupIdentifier group; final AccessLevel accessLevel; }
@Test public void testToString() throws Exception { assertEquals(adminPolicyName.toString(), adminPolicyAsString); assertEquals(readonlyPolicyName.toString(), readonlyPolicyAsString); }
IAMPolicyName { public static IAMPolicyName fromString(String wrappedAWSResourceName) { String[] parts = wrappedAWSResourceName.split(AWSResourceNameSerialization.GLOBAL_STRING_DELIMITER); if (!parts[0].equals(AWSResourceNameSerialization.GLOBAL_PREFIX)) { throw new InvalidResourceName(wrappedAWSResourceName, "An IAM policy name should start with " + AWSResourceNameSerialization.GLOBAL_PREFIX); } if (parts.length != 4) { throw new InvalidResourceName(wrappedAWSResourceName, "An IAM policy name should have exactly 4 parts"); } Region region = Region.fromName(parts[1]); String name = AWSResourceNameSerialization.decodeSecretsGroupName(parts[2]); SecretsGroupIdentifier group = new SecretsGroupIdentifier(region, name); AccessLevel accessLevel = AccessLevel.fromString(parts[3]); return new IAMPolicyName(group, accessLevel); } IAMPolicyName(SecretsGroupIdentifier group, AccessLevel accessLevel); @Override String toString(); static IAMPolicyName fromString(String wrappedAWSResourceName); @Override boolean equals(final Object obj); final SecretsGroupIdentifier group; final AccessLevel accessLevel; }
@Test public void testFromString() throws Exception { IAMPolicyName adminFromString = IAMPolicyName.fromString(adminPolicyAsString); assertEquals(adminFromString.group, group); assertEquals(adminFromString.accessLevel, AccessLevel.ADMIN); IAMPolicyName readonlyFromString = IAMPolicyName.fromString(readonlyPolicyAsString); assertEquals(readonlyFromString.group, group); assertEquals(readonlyFromString.accessLevel, AccessLevel.READONLY); } @Test(expectedExceptions = IllegalArgumentException.class) public void testFromStringInvalidAccessLevel() throws Exception { IAMPolicyName.fromString("strongbox_us-west-1_test-group_invalid"); } @Test(expectedExceptions = InvalidResourceName.class) public void testFromStringMissingRegion() throws Exception { IAMPolicyName.fromString("strongbox_test-group_admin"); } @Test(expectedExceptions = InvalidResourceName.class) public void testFromStringInvalidPrefix() throws Exception { IAMPolicyName.fromString("sm_eu-west-1_test-group_admin"); }
IAMPolicyName { @Override public boolean equals(final Object obj) { if (obj instanceof IAMPolicyName) { final IAMPolicyName other = (IAMPolicyName) obj; return Objects.equal(group, other.group) && Objects.equal(accessLevel, other.accessLevel); } else { return false; } } IAMPolicyName(SecretsGroupIdentifier group, AccessLevel accessLevel); @Override String toString(); static IAMPolicyName fromString(String wrappedAWSResourceName); @Override boolean equals(final Object obj); final SecretsGroupIdentifier group; final AccessLevel accessLevel; }
@Test public void testEquals() throws Exception { assertTrue(adminPolicyName.equals(new IAMPolicyName(group, AccessLevel.ADMIN))); assertTrue(readonlyPolicyName.equals(new IAMPolicyName(group, AccessLevel.READONLY))); assertFalse(adminPolicyName.equals(readonlyPolicyName)); assertFalse(adminPolicyName.equals( new IAMPolicyName(new SecretsGroupIdentifier(Region.EU_WEST_1, "test.group"), AccessLevel.ADMIN))); assertFalse(adminPolicyName.equals( new IAMPolicyName(new SecretsGroupIdentifier(Region.US_WEST_1, "test.group2"), AccessLevel.ADMIN))); }
UserConfig { public void addLocalFilePath(SecretsGroupIdentifier group, File path) { checkUniqueGroup(group); checkUniqueFilePath(path); localFiles.put(group, path); } UserConfig(@JsonProperty("localFiles") Map<SecretsGroupIdentifier, File> localFiles); UserConfig(); Map<SecretsGroupIdentifier, File> getMap(); Optional<File> getLocalFilePath(SecretsGroupIdentifier group); void addLocalFilePath(SecretsGroupIdentifier group, File path); void updateLocalFilePath(SecretsGroupIdentifier group, File path); void removeLocalFilePath(SecretsGroupIdentifier group); }
@Test(expectedExceptions = AlreadyExistsException.class) public void addSamePathToConfig() { SecretsGroupIdentifier anotherGroup = new SecretsGroupIdentifier(Region.EU_CENTRAL_1, "test2.group"); userConfig.addLocalFilePath(EU_GROUP, new File("path-eu")); userConfig.addLocalFilePath(anotherGroup, new File("path-eu")); } @Test(expectedExceptions = AlreadyExistsException.class) public void addSameGroupToConfigWithDifferentPath() { userConfig.addLocalFilePath(EU_GROUP, new File("path-eu")); userConfig.addLocalFilePath(EU_GROUP, new File("path-foobar")); }
FileUserConfig extends UserConfig { @Override public Optional<File> getLocalFilePath(SecretsGroupIdentifier group) { return Optional.ofNullable(localFiles.get(group)); } FileUserConfig(File configFile); @Override Optional<File> getLocalFilePath(SecretsGroupIdentifier group); @Override void addLocalFilePath(SecretsGroupIdentifier group, File path); @Override void updateLocalFilePath(SecretsGroupIdentifier group, File path); @Override void removeLocalFilePath(SecretsGroupIdentifier group); }
@Test public void testGetLocalFilePath() throws Exception { assertEquals(fileUserConfig.getLocalFilePath(GROUP1_US), Optional.of(new File("uswest1-test-group.sm"))); assertEquals(fileUserConfig.getLocalFilePath(GROUP1_EU), Optional.of(new File("euwest1-test-group.sm"))); assertEquals(fileUserConfig.getLocalFilePath(GROUP2_EU), Optional.of(new File("euwest1-test-group2.sm"))); assertEquals(fileUserConfig.getLocalFilePath( new SecretsGroupIdentifier(Region.EU_CENTRAL_1, "test.group")), Optional.empty()); }
FileUserConfig extends UserConfig { @Override public void updateLocalFilePath(SecretsGroupIdentifier group, File path) { checkUniqueFilePath(path); localFiles.put(group, path); persist(); } FileUserConfig(File configFile); @Override Optional<File> getLocalFilePath(SecretsGroupIdentifier group); @Override void addLocalFilePath(SecretsGroupIdentifier group, File path); @Override void updateLocalFilePath(SecretsGroupIdentifier group, File path); @Override void removeLocalFilePath(SecretsGroupIdentifier group); }
@Test public void testUpdateLocalFilePath() throws Exception { assertEquals(fileUserConfig.getLocalFilePath(GROUP1_US), Optional.of(new File("uswest1-test-group.sm"))); fileUserConfig.updateLocalFilePath(GROUP1_US, new File("some-other-file.sm")); assertEquals(fileUserConfig.getLocalFilePath(GROUP1_US), Optional.of(new File("some-other-file.sm"))); }
FileUserConfig extends UserConfig { @Override public void removeLocalFilePath(SecretsGroupIdentifier group) { localFiles.remove(group); persist(); } FileUserConfig(File configFile); @Override Optional<File> getLocalFilePath(SecretsGroupIdentifier group); @Override void addLocalFilePath(SecretsGroupIdentifier group, File path); @Override void updateLocalFilePath(SecretsGroupIdentifier group, File path); @Override void removeLocalFilePath(SecretsGroupIdentifier group); }
@Test public void testRemoveLocalFilePath() throws Exception { fileUserConfig.removeLocalFilePath(GROUP1_EU); fileUserConfig.removeLocalFilePath(GROUP2_EU); assertEquals(fileUserConfig.getLocalFilePath(GROUP1_EU), Optional.empty()); assertEquals(fileUserConfig.getLocalFilePath(GROUP2_EU), Optional.empty()); assertEquals(fileUserConfig.getLocalFilePath(GROUP1_US), Optional.of(new File("uswest1-test-group.sm"))); }
AWSResourceNameSerialization { public static String decodeSecretsGroupName(String encoded) { return encoded.replace('-', '.'); } static String decodeSecretsGroupName(String encoded); static String encodeSecretsGroupName(String name); static final String GLOBAL_PREFIX; static final String GLOBAL_STRING_DELIMITER; }
@Test public void testDecodeSecretsGroupName() { String decoded = AWSResourceNameSerialization.decodeSecretsGroupName("test-group-1"); assertEquals(decoded, "test.group.1"); }
AWSResourceNameSerialization { public static String encodeSecretsGroupName(String name) { return name.replace('.', '-'); } static String decodeSecretsGroupName(String encoded); static String encodeSecretsGroupName(String name); static final String GLOBAL_PREFIX; static final String GLOBAL_STRING_DELIMITER; }
@Test public void testEncodeSecretsGroupName() { String encoded = AWSResourceNameSerialization.encodeSecretsGroupName("test.group.1"); assertEquals(encoded, "test-group-1"); assertEquals(AWSResourceNameSerialization.encodeSecretsGroupName( AWSResourceNameSerialization.decodeSecretsGroupName("test-group-1")), "test-group-1"); }
RawSecretEntry implements BestEffortShred { public String toJsonBlob() { try { return objectMapper.writeValueAsString(this); } catch (JsonProcessingException e) { throw new SerializationException("Failed to serialize secret entry to JSON blob", e); } } @Deprecated RawSecretEntry(); RawSecretEntry(@JsonProperty("secretIdentifier") SecretIdentifier secretIdentifier, @JsonProperty("version") long version, @JsonProperty("state") State state, @JsonProperty("notBefore") Optional<ZonedDateTime> notBefore, @JsonProperty("notAfter") Optional<ZonedDateTime> notAfter, @JsonProperty("encryptedPayload") byte[] encryptedPayload); String toJsonBlob(); static RawSecretEntry fromJsonBlob(String jsonBlob); byte[] sha1OfEncryptionPayload(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override void bestEffortShred(); @PartitionKey(position=Config.KEY, padding = 128) @JsonProperty("secretIdentifier") public SecretIdentifier secretIdentifier; @SortKey(position=Config.VERSION) @JsonProperty("version") public Long version; @Attribute(position=Config.STATE) @JsonProperty("state") public State state; @Attribute(position=Config.NOT_BEFORE) @JsonProperty("notBefore") public Optional<ZonedDateTime> notBefore; @Attribute(position=Config.NOT_AFTER) @JsonProperty("notAfter") public Optional<ZonedDateTime> notAfter; @Attribute(position=Config.VALUE) @JsonProperty("encryptedPayload") public byte[] encryptedPayload; }
@Test public void serialize() { String serialized = rawSecretEntry.toJsonBlob(); assertThat(serialized, is(jsonBlob)); }
RawSecretEntry implements BestEffortShred { public static RawSecretEntry fromJsonBlob(String jsonBlob) { try { return objectMapper.readValue(jsonBlob, RawSecretEntry.class); } catch (IOException e) { throw new ParseException("Failed to deserialize secret entry from JSON blob", e); } } @Deprecated RawSecretEntry(); RawSecretEntry(@JsonProperty("secretIdentifier") SecretIdentifier secretIdentifier, @JsonProperty("version") long version, @JsonProperty("state") State state, @JsonProperty("notBefore") Optional<ZonedDateTime> notBefore, @JsonProperty("notAfter") Optional<ZonedDateTime> notAfter, @JsonProperty("encryptedPayload") byte[] encryptedPayload); String toJsonBlob(); static RawSecretEntry fromJsonBlob(String jsonBlob); byte[] sha1OfEncryptionPayload(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override void bestEffortShred(); @PartitionKey(position=Config.KEY, padding = 128) @JsonProperty("secretIdentifier") public SecretIdentifier secretIdentifier; @SortKey(position=Config.VERSION) @JsonProperty("version") public Long version; @Attribute(position=Config.STATE) @JsonProperty("state") public State state; @Attribute(position=Config.NOT_BEFORE) @JsonProperty("notBefore") public Optional<ZonedDateTime> notBefore; @Attribute(position=Config.NOT_AFTER) @JsonProperty("notAfter") public Optional<ZonedDateTime> notAfter; @Attribute(position=Config.VALUE) @JsonProperty("encryptedPayload") public byte[] encryptedPayload; }
@Test public void deserialize() { RawSecretEntry deserialized = RawSecretEntry.fromJsonBlob(jsonBlob); assertThat(deserialized, is(rawSecretEntry)); } @Test(expectedExceptions = ParseException.class) public void deserializeInvalidJson() { RawSecretEntry.fromJsonBlob("{#$%^&*"); }
IAMPolicyManager { public void attachReadOnly(SecretsGroupIdentifier group, Principal principal) { attachPrincipalToPolicy(group, principal, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; }
@Test public void testAttachReadOnly() throws Exception { Principal principal = new Principal(PrincipalType.USER, "bob"); partiallyMockedPolicyManager.attachReadOnly(group, principal); AttachUserPolicyRequest request = new AttachUserPolicyRequest() .withPolicyArn(READONLY_POLICY_ARN) .withUserName(principal.name); verify(mockClient, times(1)).attachUserPolicy(request); } @Test public void testAttachReadonlyRole() throws Exception { Principal principal = new Principal(PrincipalType.ROLE, "awesome-service"); partiallyMockedPolicyManager.attachReadOnly(group, principal); AttachRolePolicyRequest request = new AttachRolePolicyRequest() .withPolicyArn(READONLY_POLICY_ARN) .withRoleName(principal.name); verify(mockClient, times(1)).attachRolePolicy(request); }
RawSecretEntry implements BestEffortShred { @Override public boolean equals(final Object obj) { if(obj instanceof RawSecretEntry){ final RawSecretEntry other = (RawSecretEntry) obj; return Objects.equal(secretIdentifier, other.secretIdentifier) && Objects.equal(version, other.version) && Objects.equal(state, other.state) && Objects.equal(notBefore, other.notBefore) && Objects.equal(notAfter, other.notAfter) && Arrays.equals(encryptedPayload, other.encryptedPayload); } else { return false; } } @Deprecated RawSecretEntry(); RawSecretEntry(@JsonProperty("secretIdentifier") SecretIdentifier secretIdentifier, @JsonProperty("version") long version, @JsonProperty("state") State state, @JsonProperty("notBefore") Optional<ZonedDateTime> notBefore, @JsonProperty("notAfter") Optional<ZonedDateTime> notAfter, @JsonProperty("encryptedPayload") byte[] encryptedPayload); String toJsonBlob(); static RawSecretEntry fromJsonBlob(String jsonBlob); byte[] sha1OfEncryptionPayload(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override void bestEffortShred(); @PartitionKey(position=Config.KEY, padding = 128) @JsonProperty("secretIdentifier") public SecretIdentifier secretIdentifier; @SortKey(position=Config.VERSION) @JsonProperty("version") public Long version; @Attribute(position=Config.STATE) @JsonProperty("state") public State state; @Attribute(position=Config.NOT_BEFORE) @JsonProperty("notBefore") public Optional<ZonedDateTime> notBefore; @Attribute(position=Config.NOT_AFTER) @JsonProperty("notAfter") public Optional<ZonedDateTime> notAfter; @Attribute(position=Config.VALUE) @JsonProperty("encryptedPayload") public byte[] encryptedPayload; }
@Test public void equals() { assertFalse(rawSecretEntry.equals(secretIdentifier)); RawSecretEntry rawSecretEntry2 = new RawSecretEntry( secretIdentifier, version, state, Optional.empty(), Optional.empty(), secret); assertFalse(rawSecretEntry.equals(rawSecretEntry2)); RawSecretEntry rawSecretEntry3 = new RawSecretEntry( secretIdentifier, version, state, Optional.empty(), Optional.empty(), secret); assertTrue(rawSecretEntry2.equals(rawSecretEntry3)); }