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...
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 validateT...
@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); } } Claim...
@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...
@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.ROL...
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 = ...
@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_F...
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, lastPas...
@Test public void whenValidateTokenCalledWithNonExpiredTokenThenExpectSuccess() throws Exception { final String token = createToken(); assertThat(jwtUtils.validateTokenAndGetClaims(token)).isNotNull(); } @Test(expected = JwtAuthenticationException.class) public void whenValidateTokenCalledWithExpiredTokenThenExpectFail...
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);...
@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 shouldRetur...
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, F...
@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 shoul...
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, Funct...
@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 shouldR...
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<...
@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 shouldRet...
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> ...
@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...
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> ...
@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", n...
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 d...
@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()); } @...
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, Functi...
@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]); assertEq...
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)...
@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...
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); i...
@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() ...
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, Funct...
@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 shouldR...
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(),...
@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(system...
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(Suppl...
@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);...
@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, ...
@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 sho...
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(...
@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_...
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 vo...
@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()) .thenRe...
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 MojoExecuti...
@Test public void testExecute() throws IOException, MojoExecutionException, InterruptedException { List<String> minikubeCommand = Arrays.asList("some", "command"); Mockito.doReturn(minikubeCommand).when(spyAbstractMinikubeMojo).buildMinikubeCommand(); spyAbstractMinikubeMojo.setCommandExecutorSupplier(() -> mockCommand...
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<Str...
@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 t...
MinikubePlugin implements Plugin<Project> { @Override public void apply(Project project) { this.project = project; CommandExecutorFactory commandExecutorFactory = new CommandExecutorFactory(project.getLogger()); createMinikubeExtension(commandExecutorFactory); configureMinikubeTaskAdditionCallback(commandExecutorFactor...
@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...
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<Stri...
@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); } ...
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); } Gatew...
@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.getUsePluggableTransp...
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 (supportsO...
@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,...
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...
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("dataProviderSame...
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.toStri...
@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 providerAp...
@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<>(); default...
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 =...
@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_noOb...
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(); ...
@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(); JSON...
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 =...
@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(Stru...
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 { ...
@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(...
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, f...
@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(StructureT...
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...
@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.ge...
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; } RotationOrder...
@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.ge...
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<Pri...
@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 ListRolesRe...
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()...
@Test public void getAllStringSecrets() { List<StringSecretEntry> secrets = simpleSecretsGroup.getAllStringSecrets(); StringSecretEntry one = new StringSecretEntry(stringSecretIdentifier2, 1l, stringSecretValue2.asString()); StringSecretEntry two = new StringSecretEntry(stringSecretIdentifier3, 1l, stringSecretValue3.a...
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());...
@Test public void getAllByteSecrets() { List<ByteSecretEntry> secrets = simpleSecretsGroup.getAllBinarySecrets(); ByteSecretEntry one = new ByteSecretEntry(binarySecretIdentifier2, 1l, binarySecretValue2.asByteArray()); ByteSecretEntry two = new ByteSecretEntry(binarySecretIdentifier3, 1l, binarySecretValue3.asByteArra...
DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<String> getStringSecret(final SecretIdentifier secretIdentifier) { return asString(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final Se...
@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); assert...
DefaultSimpleSecretsGroup implements SimpleSecretsGroup { @Override public Optional<byte[]> getBinarySecret(final SecretIdentifier secretIdentifier) { return asBinary(secretsGroup.getLatestActiveVersion(secretIdentifier)); } DefaultSimpleSecretsGroup(final SecretsGroup secretsGroup); DefaultSimpleSecretsGroup(final Se...
@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); assert...
IAMPolicyManager { public void detachReadOnly(SecretsGroupIdentifier group, Principal principal) { detachPrincipal(group,principal, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCred...
@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(princ...
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...
@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(AWSCrede...
@Test public void testListAttachedAdminNoneAttached() throws Exception { ListEntitiesForPolicyRequest request = new ListEntitiesForPolicyRequest() .withPolicyArn(ADMIN_POLICY_ARN); ListEntitiesForPolicyResult result = new ListEntitiesForPolicyResult(); when(mockClient.listEntitiesForPolicy(request)).thenReturn(result);...
IAMPolicyManager { public List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group) { return listEntities(group, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AW...
@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-servic...
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 -> IAMPolicyN...
@Test public void testGetSecretsGroupIdentifiersNoGroups() throws Exception { ListPoliciesRequest request = new ListPoliciesRequest().withMaxItems(1000).withPathPrefix("/strongbox/"); when(mockClient.listPolicies(request)).thenReturn(new ListPoliciesResult()); Set<SecretsGroupIdentifier> identifiers = partiallyMockedPo...
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" + list...
@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 Pol...
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" + "}"; re...
@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().withPolic...
IAMPolicyManager { public void deleteAdminPolicy(SecretsGroupIdentifier group) { deletePolicy(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider aws...
@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(AWSCredentialsProvid...
@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 fromStrin...
@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...
@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 testFro...
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); @Overr...
@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")...
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, f...
@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...
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); } } AWSCL...
@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")); } @T...
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 clientC...
@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(mockCryptoRe...
KMSEncryptor implements Encryptor, ManagedResource { @Override public String create() { return kmsManager.create(); } KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, EncryptionStrength encryp...
@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 encryptionStren...
@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,...
@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 awsC...
@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 encryp...
@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 encry...
@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)); ...
@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"))), O...
IAMPolicyManager { public String getAdminPolicyArn(SecretsGroupIdentifier group) { return getArn(group, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider ...
@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.AlreadyExistsE...
@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 createAliasRequ...
KMSManager implements ManagedResource { @Override public void delete() { deleteAndGetSchedule(); waitForKeyState(KMSKeyState.PENDING_DELETION); } KMSManager(AWSKMS client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier); static KMSManager fromCrede...
@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(de...
KMSManager implements ManagedResource { @Override public boolean exists() { return exists(false); } KMSManager(AWSKMS client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier); static KMSManager fromCredentials(AWSCredentialsProvider awsCredentials, ...
@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, ...
@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(@JsonProper...
@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....
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)); } ZonedDateTi...
@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") S...
@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));...
@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) &...
@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), ...
IAMPolicyManager { public String getReadOnlyArn(SecretsGroupIdentifier group) { return getArn(group, AccessLevel.READONLY); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider ...
@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 ...
@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...
@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(expectedU...
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); ...
@Test public void testUpdateEntry() throws Exception { RawSecretEntry rawSecretEntry = constructRawEntry(SECRET_NAME); RawSecretEntry alternativeRawSecretEntry = constructAlternativeRawSecretEntry(SECRET_NAME); UpdateItemRequest expectedUpdateRequest = constructUpdateItemRequest(rawSecretEntry, true, Optional.of(altern...
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 { readWriteLoc...
@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);...
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, AWS...
@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(...
IAMPolicyManager { public void attachAdmin(SecretsGroupIdentifier group, Principal principal) { attachPrincipalToPolicy(group, principal, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromC...
@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(...
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)...
@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.conve...
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 ...
@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...
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 St...
@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 p...
@Test public void testFromString() throws Exception { IAMPolicyName adminFromString = IAMPolicyName.fromString(adminPolicyAsString); assertEquals(adminFromString.group, group); assertEquals(adminFromString.accessLevel, AccessLevel.ADMIN); IAMPolicyName readonlyFromString = IAMPolicyName.fromString(readonlyPolicyAsStrin...
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, Acces...
@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 IAMPo...
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(); Optiona...
@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")); }...
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(SecretsGroup...
@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(GRO...
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 addLocalF...
@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...
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, Fil...
@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()); assertEqual...
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-grou...
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("secre...
@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(); Ra...
@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...
@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); veri...
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.stat...
@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(...