Java Code Examples for org.jclouds.net.domain.IpPermission

The following examples show how to use org.jclouds.net.domain.IpPermission. These examples are extracted from open source projects. 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 Project: brooklyn-server   Source File: SecurityGroupTool.java    License: 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 2
/**
 * 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 3
Source Project: brooklyn-server   Source File: SecurityGroupEditor.java    License: 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 4
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 5
@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 6
@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 7
@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
@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 9
@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 10
@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 11
@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 12
@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 13
@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 14
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 15
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 16
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 17
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 18
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 19
@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 20
Source Project: attic-stratos   Source File: AWSSecurityGroupApiTest.java    License: 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 21
Source Project: attic-stratos   Source File: AWSSecurityGroupApiTest.java    License: 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 22
Source Project: attic-stratos   Source File: AWSSecurityGroupApiTest.java    License: 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 23
Source Project: attic-stratos   Source File: AWSSecurityGroupApiTest.java    License: 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 24
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 Project: brooklyn-library   Source File: RiakNodeImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void configureInternalNetworking() {
    Location location = getDriver().getLocation();
    if (!(location instanceof JcloudsSshMachineLocation)) {
        LOG.info("Not running in a JcloudsSshMachineLocation, not adding IP permissions to {}", this);
        return;
    }
    JcloudsMachineLocation machine = (JcloudsMachineLocation) location;
    JcloudsLocationSecurityGroupCustomizer customizer = JcloudsLocationSecurityGroupCustomizer.getInstance(getApplicationId());

    String cidr = Cidr.UNIVERSAL.toString(); // TODO configure with a more restrictive CIDR
    Collection<IpPermission> permissions = MutableList.<IpPermission>builder()
            .add(IpPermission.builder()
                    .ipProtocol(IpProtocol.TCP)
                    .fromPort(sensors().get(ERLANG_PORT_RANGE_START))
                    .toPort(sensors().get(ERLANG_PORT_RANGE_END))
                    .cidrBlock(cidr)
                    .build())
            .add(IpPermission.builder()
                    .ipProtocol(IpProtocol.TCP)
                    .fromPort(config().get(HANDOFF_LISTENER_PORT))
                    .toPort(config().get(HANDOFF_LISTENER_PORT))
                    .cidrBlock(cidr)
                    .build())
            .add(IpPermission.builder()
                    .ipProtocol(IpProtocol.TCP)
                    .fromPort(config().get(EPMD_LISTENER_PORT))
                    .toPort(config().get(EPMD_LISTENER_PORT))
                    .cidrBlock(cidr)
                    .build())
             .build();
    LOG.debug("Applying custom security groups to {}: {}", machine, permissions);
    customizer.addPermissionsToLocation(machine, permissions);
}
 
Example 26
/** @see #addPermissionsToLocation(JcloudsMachineLocation, java.lang.Iterable) */
public JcloudsLocationSecurityGroupCustomizer addPermissionsToLocation(final JcloudsMachineLocation location,
        IpPermission... permissions) {

    addPermissionsToLocation(location, ImmutableList.copyOf(permissions));
    return this;
}
 
Example 27
public Collection<SecurityGroup> addPermissionsToLocationAndReturnSecurityGroup(
    final JcloudsMachineLocation location, final Iterable<IpPermission> permissions) {

    synchronized (JcloudsLocationSecurityGroupCustomizer.class) {
        return addPermissionsInternal(permissions, location).values();
    }
}
 
Example 28
/**
 * Applies the given security group permissions to the given node with the given compute service.
 * <p>
 * Takes no action if the compute service does not have a security group extension.
 * @param permissions The set of permissions to be applied to the node
 * @param location
 */
private Map<String, SecurityGroup> addPermissionsInternal(Iterable<IpPermission> permissions,
        JcloudsMachineLocation location) {

    String nodeId = location.getNode().getId();
    final Location nodeLocation = location.getNode().getLocation();
    ComputeService computeService = location.getParent().getComputeService();

    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 ImmutableMap.of();
    }

    final SecurityGroupEditor groupEditor = createSecurityGroupEditor(securityApi.get(), nodeLocation);

    // Expect to have two security groups on the node: one shared between all nodes in the location,
    // that is cached in sharedGroupCache, and one created by Jclouds that is unique to the node.
    // Relies on customize having been called before. This should be safe because the arguments
    // needed to call this method are not available until post-instance creation.
    String locationId = computeService.getContext().unwrap().getId();
    SecurityGroup machineUniqueSecurityGroup = getMachineUniqueSecurityGroup(nodeId, locationId, groupEditor);
    MutableList<IpPermission> newPermissions = MutableList.copyOf(permissions);
    Iterables.removeAll(newPermissions, machineUniqueSecurityGroup.getIpPermissions());
    machineUniqueSecurityGroup = groupEditor.addPermissions(machineUniqueSecurityGroup, newPermissions);
    return MutableMap.of(machineUniqueSecurityGroup.getId(), machineUniqueSecurityGroup);
}
 
Example 29
/**
 * Creates a security group with rules to:
 * <ul>
 *     <li>Allow SSH access on port 22 from the world</li>
 *     <li>Allow TCP, UDP and ICMP communication between machines in the same group</li>
 * </ul>
 *
 * It needs to consider locationId as port ranges and groupId are cloud provider-dependent e.g openstack nova
 * wants from 1-65535 while aws-ec2 accepts from 0-65535.
 *
 *
 * @param groupName The name of the security group to create
 * @param securityApi The API to use to create the security group
 *
 * @return the created security group
 */
private SecurityGroup createBaseSecurityGroupInLocation(String groupName,
        SecurityGroupEditor groupEditor) {

    SecurityGroup group = groupEditor.createSecurityGroup(groupName);

    String groupId = group.getProviderId();
    int fromPort = 0;
    if (isOpenstackNova(groupEditor.getLocation())) {
        groupId = group.getId();
        fromPort = 1;
    }
    // Note: For groupName to work with GCE we also need to tag the machines with the same ID.
    // See sourceTags section at https://developers.google.com/compute/docs/networking#firewalls
    IpPermission.Builder allWithinGroup = IpPermission.builder()
            .groupId(groupId)
            .fromPort(fromPort)
            .toPort(65535);
    group = groupEditor.addPermission(group, allWithinGroup.ipProtocol(IpProtocol.TCP).build());
    group = groupEditor.addPermission(group, allWithinGroup.ipProtocol(IpProtocol.UDP).build());
    if (!isAzure(groupEditor.getLocation())) {
        group = groupEditor.addPermission(group,
            allWithinGroup.ipProtocol(IpProtocol.ICMP).fromPort(-1).toPort(-1).build());
    }

    IpPermission sshPermission = IpPermission.builder()
            .fromPort(22)
            .toPort(22)
            .ipProtocol(IpProtocol.TCP)
            .cidrBlock(getBrooklynCidrBlock())
            .build();
    group = groupEditor.addPermission(group, sshPermission);

    return group;
}
 
Example 30
Source Project: brooklyn-server   Source File: SecurityGroupEditor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add permissions to the security group, using {@link #addPermission(SecurityGroup, IpPermission)}.
 * @param group The group to update
 * @param permissions The new permissions
 * @return The updated group with the added permissions.
 */
public SecurityGroup addPermissions(final SecurityGroup group, final Iterable<IpPermission> permissions) {
    SecurityGroup lastGroup = group;
    for (IpPermission permission : permissions) {
        lastGroup = addPermission(group, permission);
    }
    return lastGroup;
}