org.jclouds.net.domain.IpPermission Java Examples

The following examples show how to use org.jclouds.net.domain.IpPermission. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AWSEC2SecurityGroupExtensionApiMockTest.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public void addIpPermissionCidrFromIpPermission() throws Exception {
   enqueueRegions(DEFAULT_REGION);
   enqueueXml(DEFAULT_REGION, "/authorize_securitygroup_ingress_response.xml");
   enqueueXml(DEFAULT_REGION, "/describe_securitygroups_extension_cidr.xml");
   enqueueXml(DEFAULT_REGION, "/availabilityZones.xml");

   SecurityGroup newGroup = extension().addIpPermission(permByCidrBlock, group);

   assertEquals(1, newGroup.getIpPermissions().size());

   IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());
   assertEquals(newPerm, permByCidrBlock);

   assertPosted(DEFAULT_REGION, "Action=DescribeRegions");
   assertPosted(DEFAULT_REGION,
         "Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=40&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0");
   assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654");
   assertPosted(DEFAULT_REGION, "Action=DescribeAvailabilityZones");
}
 
Example #2
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecurityGroupsLoadedWhenAddingPermissionsToUncachedNode() {
    IpPermission ssh = newPermission(22);
    SecurityGroup sharedGroup = newGroup(customizer.getNameForSharedSecurityGroup());
    SecurityGroup uniqueGroup = newGroup("unique");

    when(securityApi.listSecurityGroupsForNode(NODE_ID)).thenReturn(ImmutableSet.of(sharedGroup, uniqueGroup));
    when(computeService.getContext().unwrap().getId()).thenReturn("aws-ec2");
    SecurityGroup updatedSecurityGroup = newGroup(uniqueGroup.getId(), ImmutableSet.of(ssh));
    when(securityApi.addIpPermission(ssh, sharedGroup)).thenReturn(updatedSecurityGroup);
    SecurityGroup updatedUniqueSecurityGroup = newGroup(uniqueGroup.getId(), ImmutableSet.of(ssh));
    when(securityApi.addIpPermission(ssh, updatedUniqueSecurityGroup)).thenReturn(updatedUniqueSecurityGroup);

    // Expect first call to list security groups on nodeId, second to use cached version
    customizer.addPermissionsToLocation(jcloudsMachineLocation, ImmutableSet.of(ssh));
    customizer.addPermissionsToLocation(jcloudsMachineLocation, ImmutableSet.of(ssh));

    verify(securityApi, times(1)).listSecurityGroupsForNode(NODE_ID);
    verify(securityApi, times(2)).addIpPermission(ssh, uniqueGroup);
    verify(securityApi, never()).addIpPermission(any(IpPermission.class), eq(sharedGroup));
}
 
Example #3
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddRuleNotRetriedByDefault() {
    IpPermission ssh = newPermission(22);
    SecurityGroup sharedGroup = newGroup(customizer.getNameForSharedSecurityGroup());
    SecurityGroup uniqueGroup = newGroup("unique");
    when(securityApi.listSecurityGroupsForNode(NODE_ID)).thenReturn(ImmutableSet.of(sharedGroup, uniqueGroup));
    when(securityApi.addIpPermission(eq(ssh), eq(uniqueGroup)))
            .thenThrow(new RuntimeException("exception creating " + ssh));
    when(computeService.getContext().unwrap().getId()).thenReturn("aws-ec2");

    try {
        customizer.addPermissionsToLocation(jcloudsMachineLocation, ImmutableList.of(ssh));
    } catch (Exception e) {
        assertTrue(e.getMessage().contains("repeated errors from provider"), "message=" + e.getMessage());
    }
    verify(securityApi, never()).createSecurityGroup(anyString(), any(Location.class));
    verify(securityApi, times(1)).addIpPermission(ssh, uniqueGroup);
}
 
Example #4
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddPermissionWhenNoExtension() {
    IpPermission ssh = newPermission(22);
    IpPermission jmx = newPermission(31001);

    when(securityApi.listSecurityGroupsForNode(NODE_ID)).thenReturn(Collections.<SecurityGroup>emptySet());

    RuntimeException exception = null;
    try {
        customizer.addPermissionsToLocation(jcloudsMachineLocation, ImmutableList.of(ssh, jmx));
    } catch(RuntimeException e){
        exception = e;
    }

    assertNotNull(exception);
}
 
Example #5
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveMultiplePermissionsFromNode() {
    IpPermission ssh = newPermission(22);
    IpPermission jmx = newPermission(31001);
    SecurityGroup sharedGroup = newGroup(customizer.getNameForSharedSecurityGroup());
    SecurityGroup group = newGroup("id");
    when(securityApi.listSecurityGroupsForNode(NODE_ID)).thenReturn(ImmutableSet.of(sharedGroup, group));
    SecurityGroup updatedSecurityGroup = newGroup("id", ImmutableSet.of(ssh, jmx));
    when(securityApi.addIpPermission(ssh, group)).thenReturn(updatedSecurityGroup);
    when(securityApi.addIpPermission(jmx, group)).thenReturn(updatedSecurityGroup);
    when(computeService.getContext().unwrap().getId()).thenReturn("aws-ec2");

    customizer.addPermissionsToLocation(jcloudsMachineLocation, ImmutableList.of(ssh, jmx));

    when(securityApi.removeIpPermission(ssh, group)).thenReturn(updatedSecurityGroup);
    when(securityApi.removeIpPermission(jmx, group)).thenReturn(updatedSecurityGroup);
    customizer.removePermissionsFromLocation(jcloudsMachineLocation, ImmutableList.of(ssh, jmx));

    verify(securityApi, times(1)).removeIpPermission(ssh, group);
    verify(securityApi, times(1)).removeIpPermission(jmx, group);
}
 
Example #6
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemovePermissionsFromNode() {
    IpPermission ssh = newPermission(22);
    IpPermission jmx = newPermission(31001);
    SecurityGroup sharedGroup = newGroup(customizer.getNameForSharedSecurityGroup());
    SecurityGroup group = newGroup("id");
    when(securityApi.listSecurityGroupsForNode(NODE_ID)).thenReturn(ImmutableSet.of(sharedGroup, group));
    SecurityGroup updatedSecurityGroup = newGroup("id", ImmutableSet.of(ssh, jmx));
    when(securityApi.addIpPermission(ssh, group)).thenReturn(updatedSecurityGroup);
    when(securityApi.addIpPermission(jmx, group)).thenReturn(updatedSecurityGroup);
    when(computeService.getContext().unwrap().getId()).thenReturn("aws-ec2");

    customizer.addPermissionsToLocation(jcloudsMachineLocation, ImmutableList.of(ssh, jmx));
    customizer.removePermissionsFromLocation(jcloudsMachineLocation, ImmutableList.of(jmx));

    verify(securityApi, never()).removeIpPermission(ssh, group);
    verify(securityApi, times(1)).removeIpPermission(jmx, group);
}
 
Example #7
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddPermissionsToNode() {
    IpPermission ssh = newPermission(22);
    IpPermission jmx = newPermission(31001);
    SecurityGroup sharedGroup = newGroup(customizer.getNameForSharedSecurityGroup());
    SecurityGroup group = newGroup("id");
    when(securityApi.listSecurityGroupsForNode(NODE_ID)).thenReturn(ImmutableSet.of(sharedGroup, group));
    SecurityGroup updatedSecurityGroup = newGroup("id", ImmutableSet.of(ssh, jmx));
    when(securityApi.addIpPermission(ssh, group)).thenReturn(updatedSecurityGroup);
    when(securityApi.addIpPermission(jmx, group)).thenReturn(updatedSecurityGroup);
    when(computeService.getContext().unwrap().getId()).thenReturn("aws-ec2");

    customizer.addPermissionsToLocation(jcloudsMachineLocation, ImmutableList.of(ssh, jmx));

    verify(securityApi, never()).createSecurityGroup(anyString(), any(Location.class));
    verify(securityApi, times(1)).addIpPermission(ssh, group);
    verify(securityApi, times(1)).addIpPermission(jmx, group);
}
 
Example #8
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testSharedGroupLoadedWhenItExistsButIsNotCached() {
    Template template = mock(Template.class);
    TemplateOptions templateOptions = mock(TemplateOptions.class);
    when(template.getLocation()).thenReturn(location);
    when(template.getOptions()).thenReturn(templateOptions);
    JcloudsLocation jcloudsLocation = new JcloudsLocation(MutableMap.of("deferConstruction", true));
    SecurityGroup shared = newGroup(customizer.getNameForSharedSecurityGroup());
    SecurityGroup irrelevant = newGroup("irrelevant");
    when(securityApi.createSecurityGroup(shared.getName(), location)).thenReturn(shared);
    when(securityApi.createSecurityGroup(irrelevant.getName(), location)).thenReturn(irrelevant);
    when(securityApi.listSecurityGroupsInLocation(location)).thenReturn(ImmutableSet.of(irrelevant, shared));
    when(securityApi.addIpPermission(any(IpPermission.class), eq(shared))).thenReturn(shared);
    when(securityApi.addIpPermission(any(IpPermission.class), eq(irrelevant))).thenReturn(irrelevant);

    customizer.customize(jcloudsLocation, computeService, template);

    verify(securityApi).listSecurityGroupsInLocation(location);
    verify(securityApi, never()).createSecurityGroup(anyString(), any(Location.class));
}
 
Example #9
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecurityGroupAddedWhenJcloudsLocationCustomised() {
    Template template = mock(Template.class);
    TemplateOptions templateOptions = mock(TemplateOptions.class);
    when(template.getLocation()).thenReturn(location);
    when(template.getOptions()).thenReturn(templateOptions);
    SecurityGroup group = newGroup("id");
    when(securityApi.createSecurityGroup(anyString(), eq(location))).thenReturn(group);
    when(securityApi.addIpPermission(any(IpPermission.class), eq(group))).thenReturn(group);

    // Two Brooklyn.JcloudsLocations added to same Jclouds.Location
    JcloudsLocation jcloudsLocationA = new JcloudsLocation(MutableMap.of("deferConstruction", true));
    JcloudsLocation jcloudsLocationB = new JcloudsLocation(MutableMap.of("deferConstruction", true));
    customizer.customize(jcloudsLocationA, computeService, template);
    customizer.customize(jcloudsLocationB, computeService, template);

    // One group with three permissions shared by both locations.
    // Expect TCP, UDP and ICMP between members of group and SSH to Brooklyn
    verify(securityApi).createSecurityGroup(anyString(), eq(location));
    verify(securityApi, times(4)).addIpPermission(any(IpPermission.class), eq(group));
    // New groups set on options
    verify(templateOptions, times(2)).securityGroups(anyString());
}
 
Example #10
Source File: JcloudsRateLimitedRetryLiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void doOneSecurityEditorOperationCycle(String id, SecurityGroupEditor editor,
         JcloudsSshMachineLocation machine) {

    SecurityGroup securityGroup = editor.createSecurityGroup(id);
    final String groupId = securityGroup.getId();
    final IpPermission permission = aPermission();

    securityGroup = editor.addPermission(securityGroup, permission);
    assertTrue(securityGroup.getIpPermissions().contains(permission));

    securityGroup = editor.removePermission(securityGroup, permission);
    assertFalse(securityGroup.getIpPermissions().contains(permission));

    assertTrue(editor.removeSecurityGroup(securityGroup));
    final Set<SecurityGroup> securityGroups = editor.listSecurityGroupsForNode(machine.getNode().getId());
    for (SecurityGroup s: securityGroups) {
        assertFalse(s.getId().equals(groupId));
    }
}
 
Example #11
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddRuleRetriedOnAwsFailure() {
    IpPermission ssh = newPermission(22);
    SecurityGroup sharedGroup = newGroup(customizer.getNameForSharedSecurityGroup());
    SecurityGroup uniqueGroup = newGroup("unique");
    customizer.setRetryExceptionPredicate(JcloudsLocationSecurityGroupCustomizer.newAwsExceptionRetryPredicate());
    when(securityApi.listSecurityGroupsForNode(NODE_ID)).thenReturn(ImmutableSet.of(sharedGroup, uniqueGroup));
    when(securityApi.addIpPermission(any(IpPermission.class), eq(uniqueGroup)))
            .thenThrow(newAwsResponseExceptionWithCode("InvalidGroup.InUse"))
            .thenThrow(newAwsResponseExceptionWithCode("DependencyViolation"))
            .thenThrow(newAwsResponseExceptionWithCode("RequestLimitExceeded"))
            .thenThrow(newAwsResponseExceptionWithCode("Blocked"))
            .thenReturn(sharedGroup);
    when(computeService.getContext().unwrap().getId()).thenReturn("aws-ec2");

    try {
        customizer.addPermissionsToLocation(jcloudsMachineLocation, ImmutableList.of(ssh));
    } catch (Exception e) {
        String expected = "repeated errors from provider";
        assertTrue(e.getMessage().contains(expected), "expected exception message to contain " + expected + ", was: " + e.getMessage());
    }

    verify(securityApi, never()).createSecurityGroup(anyString(), any(Location.class));
    verify(securityApi, times(4)).addIpPermission(ssh, uniqueGroup);
}
 
Example #12
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private SecurityGroup newGroup(String name, Set<IpPermission> ipPermissions) {
    String id = name;
    if (!name.startsWith(JCLOUDS_PREFIX_AWS)) {
        id = JCLOUDS_PREFIX_AWS + name;
    }
    URI uri = null;
    String ownerId = null;
    return new SecurityGroup(
        "providerId",
        id,
        id,
        location,
        uri,
        Collections.<String, String>emptyMap(),
        ImmutableSet.<String>of(),
        ipPermissions,
        ownerId);
}
 
Example #13
Source File: AWSEC2SecurityGroupExtensionApiMockTest.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public void addIpPermissionCidrFromParams() throws Exception {
   enqueueRegions(DEFAULT_REGION);
   enqueueXml(DEFAULT_REGION, "/authorize_securitygroup_ingress_response.xml");
   enqueueXml(DEFAULT_REGION, "/describe_securitygroups_extension_cidr.xml");
   enqueueXml(DEFAULT_REGION, "/availabilityZones.xml");

   SecurityGroup newGroup = extension()
         .addIpPermission(permByCidrBlock.getIpProtocol(), permByCidrBlock.getFromPort(),
               permByCidrBlock.getToPort(), permByCidrBlock.getTenantIdGroupNamePairs(),
               permByCidrBlock.getCidrBlocks(), permByCidrBlock.getGroupIds(), group);

   IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());
   assertEquals(newPerm, permByCidrBlock);

   assertPosted(DEFAULT_REGION, "Action=DescribeRegions");
   assertPosted(DEFAULT_REGION,
         "Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=40&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0");
   assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654");
   assertPosted(DEFAULT_REGION, "Action=DescribeAvailabilityZones");
}
 
Example #14
Source File: AWSEC2SecurityGroupExtensionApiMockTest.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public void addIpPermissionGroupFromIpPermission() throws Exception {
   enqueueRegions(DEFAULT_REGION);
   enqueueXml(DEFAULT_REGION, "/authorize_securitygroup_ingress_response.xml");
   enqueueXml(DEFAULT_REGION, "/describe_securitygroups_extension_group.xml");
   enqueueXml(DEFAULT_REGION, "/availabilityZones.xml");

   SecurityGroup newGroup = extension().addIpPermission(permByGroup, group);

   assertEquals(1, newGroup.getIpPermissions().size());

   IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());
   assertEquals(newPerm, permByGroup);

   assertPosted(DEFAULT_REGION, "Action=DescribeRegions");
   assertPosted(DEFAULT_REGION,
         "Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=40&IpPermissions.0.Groups.0.UserId=993194456877&IpPermissions.0.Groups.0.GroupId=sg-3c6ef654");
   assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654");
   assertPosted(DEFAULT_REGION, "Action=DescribeAvailabilityZones");
}
 
Example #15
Source File: SecurityGroupEditor.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Add a permission to the security group. This operation is idempotent (will return the group unmodified if the
 * permission already exists on it).
 * @param group The group to update
 * @param permission The new permission
 * @return The updated group with the added permissions.
 */
public SecurityGroup addPermission(final SecurityGroup group, final IpPermission permission) {
    LOG.debug("Adding permission to security group {}: {}", group.getName(), permission);
    Callable<SecurityGroup> callable = new Callable<SecurityGroup>() {
        @Override
        public SecurityGroup call() throws Exception {
            try {
                return securityApi.addIpPermission(permission, group);
            } catch (Exception e) {
                Exceptions.propagateIfFatal(e);

                if (isDuplicate(e)) {
                    return group;
                }

                throw Exceptions.propagate(e);
            }
        }

        @Override
        public String toString() {
            return "Add permission " + permission + " to security group " + group;
        }
    };
    return runOperationWithRetry(callable);
}
 
Example #16
Source File: AWSEC2SecurityGroupExtensionApiMockTest.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public void addIpPermissionGroupFromParams() throws Exception {
   enqueueRegions(DEFAULT_REGION);
   enqueueXml(DEFAULT_REGION, "/authorize_securitygroup_ingress_response.xml");
   enqueueXml(DEFAULT_REGION, "/describe_securitygroups_extension_group.xml");
   enqueueXml(DEFAULT_REGION, "/availabilityZones.xml");

   SecurityGroup newGroup = extension()
         .addIpPermission(permByGroup.getIpProtocol(), permByGroup.getFromPort(), permByGroup.getToPort(),
               permByGroup.getTenantIdGroupNamePairs(), permByGroup.getCidrBlocks(), permByGroup.getGroupIds(),
               group);

   IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());
   assertEquals(newPerm, permByGroup);

   assertPosted(DEFAULT_REGION, "Action=DescribeRegions");
   assertPosted(DEFAULT_REGION,
         "Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=40&IpPermissions.0.Groups.0.UserId=993194456877&IpPermissions.0.Groups.0.GroupId=sg-3c6ef654");
   assertPosted(DEFAULT_REGION, "Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654");
   assertPosted(DEFAULT_REGION, "Action=DescribeAvailabilityZones");
}
 
Example #17
Source File: AWSEC2SecurityGroupToSecurityGroupTest.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@Test
public void testApply() {
   IpPermissions authorization = IpPermissions.permitAnyProtocol();

   org.jclouds.ec2.domain.SecurityGroup origGroup = org.jclouds.ec2.domain.SecurityGroup.builder()
      .region("us-east-1")
      .id("some-id")
      .name("some-group")
      .ownerId("some-owner")
      .description("some-description")
      .ipPermission(authorization)
      .build();

   AWSEC2SecurityGroupToSecurityGroup parser = createGroupParser(ImmutableSet.of(provider));

   SecurityGroup group = parser.apply(origGroup);
   
   assertEquals(group.getLocation(), provider);
   assertEquals(group.getId(), provider.getId() + "/" + origGroup.getId());
   assertEquals(group.getProviderId(), origGroup.getId());
   assertEquals(group.getName(), origGroup.getName());
   assertEquals(group.getIpPermissions(), (Set<IpPermission>)origGroup);
   assertEquals(group.getOwnerId(), origGroup.getOwnerId());
}
 
Example #18
Source File: AWSSecurityGroupApiTest.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public void testAuthorizeSecurityGroupIpPermission() throws SecurityException, NoSuchMethodException, IOException {
   Invokable<?, ?> method = method(AWSSecurityGroupApi.class, "authorizeSecurityGroupIngressInRegion",
         String.class, String.class, IpPermission.class);
   GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "group", IpPermissions.permitAnyProtocol()));

   assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
   assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
   assertPayloadEquals(
         request,
         "Action=AuthorizeSecurityGroupIngress&GroupId=group&IpPermissions.0.IpProtocol=-1&IpPermissions.0.FromPort=1&IpPermissions.0.ToPort=65535&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0",
         "application/x-www-form-urlencoded", false);

   assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
   assertSaxResponseParserClassEquals(method, null);
   assertFallbackClassEquals(method, null);

   checkFilters(request);
}
 
Example #19
Source File: JcloudsLocationSecurityGroupCustomizer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Removes the given security group permissions from the given node.
 * <p>
 * Takes no action if the compute service does not have a security group extension.
 * @param location Location of the node to remove permissions from
 * @param permissions The set of permissions to be removed from the node
 */
private void removePermissionsInternal(JcloudsMachineLocation location, Iterable<IpPermission> permissions) {
    ComputeService computeService = location.getParent().getComputeService();
    String nodeId = location.getNode().getId();

    final Optional<SecurityGroupExtension> securityApi = computeService.getSecurityGroupExtension();
    if (!securityApi.isPresent()) {
        LOG.warn("Security group extension for {} absent; cannot update node {} with {}",
                new Object[] {computeService, nodeId, permissions});
        return;
    }

    final SecurityGroupEditor editor = createSecurityGroupEditor(securityApi.get(), location.getNode().getLocation());
    String locationId = computeService.getContext().unwrap().getId();
    SecurityGroup machineUniqueSecurityGroup = getMachineUniqueSecurityGroup(nodeId, locationId, editor);
    editor.removePermissions(machineUniqueSecurityGroup, permissions);
}
 
Example #20
Source File: AWSSecurityGroupApiTest.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public void testAuthorizeSecurityGroupIpPermissions() throws SecurityException, NoSuchMethodException, IOException {
   Invokable<?, ?> method = method(AWSSecurityGroupApi.class, "authorizeSecurityGroupIngressInRegion",
         String.class, String.class, Iterable.class);
   GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "group", ImmutableSet.<IpPermission> of(IpPermissions
         .permit(IpProtocol.TCP).originatingFromCidrBlock("1.1.1.1/32"), IpPermissions.permitICMP().type(8).andCode(0)
         .originatingFromSecurityGroupId("groupId"))));

   assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
   assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
   assertPayloadEquals(
         request,
         "Action=AuthorizeSecurityGroupIngress&GroupId=group&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=1&IpPermissions.0.ToPort=65535&IpPermissions.0.IpRanges.0.CidrIp=1.1.1.1/32&IpPermissions.1.IpProtocol=icmp&IpPermissions.1.FromPort=8&IpPermissions.1.ToPort=0&IpPermissions.1.Groups.0.GroupId=groupId",
         "application/x-www-form-urlencoded", false);

   assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
   assertSaxResponseParserClassEquals(method, null);
   assertFallbackClassEquals(method, null);

   checkFilters(request);
}
 
Example #21
Source File: AWSSecurityGroupApiTest.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public void testRevokeSecurityGroupIpPermission() throws SecurityException, NoSuchMethodException, IOException {
   Invokable<?, ?> method = method(AWSSecurityGroupApi.class, "revokeSecurityGroupIngressInRegion", String.class,
         String.class, IpPermission.class);
   GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "group", IpPermissions.permitAnyProtocol()));

   assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
   assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
   assertPayloadEquals(
         request,
         "Action=RevokeSecurityGroupIngress&GroupId=group&IpPermissions.0.IpProtocol=-1&IpPermissions.0.FromPort=1&IpPermissions.0.ToPort=65535&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0",
         "application/x-www-form-urlencoded", false);

   assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
   assertSaxResponseParserClassEquals(method, null);
   assertFallbackClassEquals(method, null);

   checkFilters(request);
}
 
Example #22
Source File: AWSSecurityGroupApiTest.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public void testRevokeSecurityGroupIpPermissions() throws SecurityException, NoSuchMethodException, IOException {
   Invokable<?, ?> method = method(AWSSecurityGroupApi.class, "revokeSecurityGroupIngressInRegion", String.class,
         String.class, Iterable.class);
   GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "group", ImmutableSet.<IpPermission> of(IpPermissions
         .permit(IpProtocol.TCP).originatingFromCidrBlock("1.1.1.1/32"), IpPermissions.permitICMP().type(8).andCode(0)
         .originatingFromSecurityGroupId("groupId"))));

   assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
   assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
   assertPayloadEquals(
         request,
         "Action=RevokeSecurityGroupIngress&GroupId=group&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=1&IpPermissions.0.ToPort=65535&IpPermissions.0.IpRanges.0.CidrIp=1.1.1.1/32&IpPermissions.1.IpProtocol=icmp&IpPermissions.1.FromPort=8&IpPermissions.1.ToPort=0&IpPermissions.1.Groups.0.GroupId=groupId",
         "application/x-www-form-urlencoded", false);

   assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
   assertSaxResponseParserClassEquals(method, null);
   assertFallbackClassEquals(method, null);

   checkFilters(request);
}
 
Example #23
Source File: SecurityGroupTool.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected void addPermissions(SecurityGroupExtension sgExt, SecurityGroup sg) {

        Object api = ((ApiContext<?>)location.getComputeService().getContext().unwrap()).getApi();
        if (api instanceof AWSEC2Api) {
            // optimization for AWS where rules can be added all at once, and it cuts down Req Limit Exceeded problems!
            String region = AWSUtils.getRegionFromLocationOrNull(sg.getLocation());
            String id = sg.getProviderId();
            
            ((AWSEC2Api)api).getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(region, id, sgDef.getPermissions());
            
        } else {
            for (IpPermission p: sgDef.getPermissions()) {
                sgExt.addIpPermission(p, sg);
            }
        }
    }
 
Example #24
Source File: DescribeSecurityGroupsResponseTest.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
public Set<SecurityGroup> expected() {
      return ImmutableSet.of(SecurityGroup.builder()
                                          .region(defaultRegion)
                                          .ownerId("123123123123")
                                          .id("sg-11111111")
                                          .name("default")
                                          .description("default VPC security group")
//                                          .vpcId("vpc-99999999")
                                          .ipPermission(IpPermission.builder()
                                                                    .ipProtocol(IpProtocol.ALL)
                                                                    .tenantIdGroupNamePair("123123123123", "sg-11111111").build())
//                                          .ipPermissionEgress(IpPermission.builder()
//                                                                    .ipProtocol(IpProtocol.ALL)
//                                                                    .ipRange("0.0.0.0/0").build())
                                          .build());

   }
 
Example #25
Source File: NetworkingEffectorsLiveTests.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Predicate<SecurityGroup> ruleExistsPredicate(final int fromPort, final int toPort, final IpProtocol ipProtocol) {
    return new Predicate<SecurityGroup>() {
        @Override
        public boolean apply(SecurityGroup scipPermission) {
            for (IpPermission ipPermission : scipPermission.getIpPermissions()) {
                if (ipPermission.getFromPort() == fromPort && ipPermission.getToPort() == toPort && ipPermission.getIpProtocol() == ipProtocol) {
                    return true;
                }
            }
            return false;
        }
    };
}
 
Example #26
Source File: AWSEC2SecurityGroupExtension.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public SecurityGroup addIpPermission(IpPermission ipPermission, SecurityGroup group) {
   String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
   String id = group.getProviderId();

   client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(region, id, ipPermission);

   return getSecurityGroupById(group.getId());
}
 
Example #27
Source File: AWSEC2SecurityGroupExtension.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort,
                                     Multimap<String, String> tenantIdGroupNamePairs,
                                     Iterable<String> ipRanges,
                                     Iterable<String> groupIds, SecurityGroup group) {
   String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
   String id = group.getProviderId();

   IpPermission.Builder builder = IpPermission.builder();

   builder.ipProtocol(protocol);
   builder.fromPort(startPort);
   builder.toPort(endPort);

   if (!Iterables.isEmpty(ipRanges)) {
      for (String cidr : ipRanges) {
         builder.cidrBlock(cidr);
      }
   }

   if (!tenantIdGroupNamePairs.isEmpty()) {
      for (String userId : tenantIdGroupNamePairs.keySet()) {
         for (String groupString : tenantIdGroupNamePairs.get(userId)) {
            String[] parts = AWSUtils.parseHandle(groupString);
            String groupId = parts[1];
            builder.tenantIdGroupNamePair(userId, groupId);
         }
      }
   }

   client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(region, id, builder.build());

   return getSecurityGroupById(group.getId());
}
 
Example #28
Source File: AWSEC2SecurityGroupExtension.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public SecurityGroup removeIpPermission(IpPermission ipPermission, SecurityGroup group) {
   String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
   String id = group.getProviderId();

   client.getSecurityGroupApi().get().revokeSecurityGroupIngressInRegion(region, id, ipPermission);

   return getSecurityGroupById(group.getId());
}
 
Example #29
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomExceptionRetryablePredicate() {
    final String message = "testCustomExceptionRetryablePredicate";
    Predicate<Exception> messageChecker = new Predicate<Exception>() {
        @Override
        public boolean apply(Exception input) {
            Throwable t = input;
            while (t != null) {
                if (t.getMessage().contains(message)) {
                    return true;
                } else {
                    t = t.getCause();
                }
            }
            return false;
        }
    };
    customizer.setRetryExceptionPredicate(messageChecker);
    when(computeService.getContext().unwrap().getId()).thenReturn("aws-ec2");

    IpPermission ssh = newPermission(22);
    SecurityGroup sharedGroup = newGroup(customizer.getNameForSharedSecurityGroup());
    SecurityGroup uniqueGroup = newGroup("unique");
    when(securityApi.listSecurityGroupsForNode(NODE_ID)).thenReturn(ImmutableSet.of(sharedGroup, uniqueGroup));
    when(securityApi.addIpPermission(eq(ssh), eq(uniqueGroup)))
            .thenThrow(new RuntimeException(new Exception(message)))
            .thenThrow(new RuntimeException(new Exception(message)))
            .thenReturn(sharedGroup);

    customizer.addPermissionsToLocation(jcloudsMachineLocation, ImmutableList.of(ssh));

    verify(securityApi, never()).createSecurityGroup(anyString(), any(Location.class));
    verify(securityApi, times(3)).addIpPermission(ssh, uniqueGroup);
}
 
Example #30
Source File: AWSEC2SecurityGroupExtension.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort,
                                        Multimap<String, String> tenantIdGroupNamePairs,
                                        Iterable<String> ipRanges,
                                        Iterable<String> groupIds, SecurityGroup group) {
   String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
   String id = group.getProviderId();

   IpPermission.Builder builder = IpPermission.builder();

   builder.ipProtocol(protocol);
   builder.fromPort(startPort);
   builder.toPort(endPort);

   if (!Iterables.isEmpty(ipRanges)) {
      for (String cidr : ipRanges) {
         builder.cidrBlock(cidr);
      }
   }

   if (!tenantIdGroupNamePairs.isEmpty()) {
      for (String userId : tenantIdGroupNamePairs.keySet()) {
         for (String groupString : tenantIdGroupNamePairs.get(userId)) {
            String[] parts = AWSUtils.parseHandle(groupString);
            String groupId = parts[1];
            builder.tenantIdGroupNamePair(userId, groupId);
         }
      }
   }

   client.getSecurityGroupApi().get().revokeSecurityGroupIngressInRegion(region, id, builder.build());

   return getSecurityGroupById(group.getId());
}