com.google.api.services.cloudresourcemanager.model.Project Java Examples

The following examples show how to use com.google.api.services.cloudresourcemanager.model.Project. 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: LiveProjectSourceTest.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
@Test
public void testAdvanceWithoutStart() {
  PipelineOptions options = PipelineOptionsFactory.create();
  LiveProjectReader reader;

  this.listProjectsResponse.setProjects(new ArrayList<Project>(0));
  this.listProjectsResponse.setNextPageToken(null);
  try {
    reader = (LiveProjectReader) this.source.createReader(options);
    assertFalse(reader.advance());
    assertNull(reader.getNextPageToken());
    assertTrue(reader.getProjects().isEmpty());
    reader.getCurrent();
  } catch (IOException e) {
    fail("IOException in reader.start");
  } catch (NoSuchElementException ignored) {
    // test passed.
  }
}
 
Example #2
Source File: GcpOptions.java    From beam with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the project number or throws an error if the project does not exist or has other
 * access errors.
 */
private static long getProjectNumber(
    String projectId, CloudResourceManager crmClient, BackOff backoff, Sleeper sleeper)
    throws IOException {
  CloudResourceManager.Projects.Get getProject = crmClient.projects().get(projectId);
  try {
    Project project =
        ResilientOperation.retry(
            ResilientOperation.getGoogleRequestCallable(getProject),
            backoff,
            RetryDeterminer.SOCKET_ERRORS,
            IOException.class,
            sleeper);
    return project.getProjectNumber();
  } catch (Exception e) {
    throw new IOException("Unable to get project number", e);
  }
}
 
Example #3
Source File: RunOptionsDefaultsComponentTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
private void mockProjectList(Credential credential, GcpProject... gcpProjects)
    throws IOException {
  Projects projectsApi = mock(Projects.class);
  Projects.List listApi = mock(Projects.List.class);
  List<Project> projectsList = new ArrayList<>();
  for (GcpProject gcpProject : gcpProjects) {
    Project project = new Project(); // cannot mock final classes
    project.setName(gcpProject.getName());
    project.setProjectId(gcpProject.getId());
    projectsList.add(project);
  }
  ListProjectsResponse response = new ListProjectsResponse(); // cannot mock final classes
  response.setProjects(projectsList);
  doReturn(projectsApi).when(apiFactory).newProjectsApi(credential);
  doReturn(listApi).when(listApi).setPageSize(anyInt());
  doReturn(listApi).when(projectsApi).list();
  doReturn(response).when(listApi).execute();
}
 
Example #4
Source File: MiniSelectorTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
private void mockProjectsList(Credential credential, GcpProject... gcpProjects) {
  Projects projectsApi = mock(Projects.class);
  Projects.List listApi = mock(Projects.List.class);
  List<Project> projectsList = new ArrayList<>();
  for (GcpProject gcpProject : gcpProjects) {
    Project project = new Project();
    project.setName(gcpProject.getName());
    project.setProjectId(gcpProject.getId());
    projectsList.add(project);
  }
  ListProjectsResponse response = new ListProjectsResponse();
  response.setProjects(projectsList);
  try {
    doReturn(projectsApi).when(apiFactory).newProjectsApi(credential);
    doReturn(listApi).when(listApi).setPageSize(any(Integer.class));
    doReturn(listApi).when(projectsApi).list();
    doReturn(response).when(listApi).execute();
  } catch (IOException ex) {
    fail(ex.toString());
  }
}
 
Example #5
Source File: ProjectRepositoryTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetProjects_pagination() throws IOException, ProjectRepositoryException {
  Projects.List list = initializeListRequest();
  ListProjectsResponse response1 = new ListProjectsResponse();
  response1.setProjects(Collections.singletonList(project));
  response1.setNextPageToken("a token");
  
  ListProjectsResponse response2 = new ListProjectsResponse();
  Project project2 = new Project();
  project2.setName("project 2").setProjectId("project_2");
  response2.setProjects(Collections.singletonList(project2));
  
  when(list.execute()).thenReturn(response1, response2);

  List<GcpProject> gcpProjects = repository.getProjects(mock(Credential.class));

  assertThat(gcpProjects.size(), is(2));
  GcpProject gcpProject = gcpProjects.get(0);
  assertThat(gcpProject.getName(), is("projectName"));
  assertThat(gcpProject.getId(), is("projectId"));
  GcpProject gcpProject2 = gcpProjects.get(1);
  assertThat(gcpProject2.getName(), is("project 2"));
  assertThat(gcpProject2.getId(), is("project_2"));
}
 
Example #6
Source File: Authenticator.java    From styx with Apache License 2.0 6 votes vote down vote up
void cacheResources() throws IOException {
  final CloudResourceManager.Projects.List request = cloudResourceManager.projects().list();

  ListProjectsResponse response;
  do {
    response = executeWithRetries(request, retryWaitStrategy, retryStopStrategy);
    if (response.getProjects() == null) {
      continue;
    }
    for (Project project : response.getProjects()) {
      final boolean access = resolveProject(project);
      logger.info("Resolved project: {}, access={}", project.getProjectId(), access);
    }
    request.setPageToken(response.getNextPageToken());
  } while (response.getNextPageToken() != null);

  logger.info("Resource cache loaded");
}
 
Example #7
Source File: GcpOptionsTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  options = PipelineOptionsFactory.create();
  options.as(GcsOptions.class).setGcsUtil(mockGcsUtil);
  options.as(GcpOptions.class).setProject("foo");
  options.as(GcpOptions.class).setZone("us-north1-a");
  when(mockCrmClient.projects()).thenReturn(mockProjects);
  when(mockProjects.get(any(String.class))).thenReturn(mockGet);
  fakeProject = new Project().setProjectNumber(1L);
}
 
Example #8
Source File: LiveStateCheckerTest.java    From policyscanner with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws GeneralSecurityException, IOException {
  GCPProject.setProjectsApiStub(projectsObject);

  CloudResourceManager.Projects.List emptyList = mock(CloudResourceManager.Projects.List.class);
  ListProjectsResponse emptyListProjectResponse = new ListProjectsResponse();

  when(projectsObject.list()).thenReturn(listProjects);
  when(listProjects.setPageToken(anyString())).thenReturn(emptyList);
  when(listProjects.setPageToken(null)).thenReturn(listProjects);
  when(listProjects.setFilter(anyString())).thenReturn(listProjects);

  when(emptyList.setPageToken(null)).thenReturn(emptyList);
  when(emptyList.setPageToken(anyString())).thenReturn(emptyList);
  when(emptyList.setFilter(anyString())).thenReturn(emptyList);

  when(emptyList.execute()).thenReturn(emptyListProjectResponse
      .setNextPageToken("maybe halt?")
      .setProjects(new ArrayList<Project>(0)));

  when(objectList.setPageToken(anyString())).thenReturn(objectList);
  when(objectList.setPageToken(null)).thenReturn(objectList);
  when(objectList.setPrefix(anyString())).thenReturn(objectList);

  when(objects.list(anyString())).thenReturn(objectList);
  when(objects.get(anyString(), anyString())).thenReturn(objectGet);
  when(gcs.objects()).thenReturn(objects);

  when(buckets.get(anyString())).thenReturn(bucketGet);
  when(gcs.buckets()).thenReturn(buckets);

  when(this.projectsObject.getIamPolicy(anyString(), any(GetIamPolicyRequest.class)))
      .thenReturn(this.getIamPolicy);

  GCSFilesSource.setStorageApiStub(gcs);
  this.checkedSource = new GCSFilesSource(BUCKET, ORG_ID);
}
 
Example #9
Source File: LiveProjectSource.java    From policyscanner with Apache License 2.0 5 votes vote down vote up
private boolean refreshProjects(String nextPageToken) throws IOException {
  ListProjectsResponse projectListResponse;
  Projects.List projectsList;
  try {
    projectsList = GCPProject.getProjectsApiStub().list();
    if (nextPageToken != null) {
      projectsList = projectsList.setPageToken(nextPageToken);
    }
    if (source.getOrgId() != null) {
        projectsList = projectsList
            .setFilter("parent.type:organization parent.id:" + source.getOrgId());
    }
    projectListResponse = projectsList.execute();
  } catch (GeneralSecurityException gse) {
    throw new IOException("Cannot get projects. Access denied");
  }
  List<Project> projects = projectListResponse.getProjects();

  for (Project project : projects) {
    String orgId = null;
    if (project.getParent() != null) {
      orgId = project.getParent().getId();
    }
    if (project.getLifecycleState() == null
        || project.getLifecycleState().startsWith(DELETE_PREFIX)) {
      continue;
    }
    this.projects.add(new GCPProject(project.getProjectId(), orgId, project.getName()));
  }
  this.nextPageToken = projectListResponse.getNextPageToken();

  return !this.projects.isEmpty();
}
 
Example #10
Source File: ProjectRepository.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static List<GcpProject> convertToGcpProjects(List<Project> projects) {
  List<GcpProject> gcpProjects = new ArrayList<>();
  if (projects != null) {
    for (Project project : projects) {
      if (!PROJECT_DELETE_REQUESTED.equals(project.getLifecycleState())) {
        gcpProjects.add(convertToGcpProject(project));
      }
    }
  }
  return gcpProjects;
}
 
Example #11
Source File: ProjectRepository.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/**
 * @return all active projects the account identified by {@code credential} has access to
 * @throws ProjectRepositoryException if an error happens while communicating with the backend
 */
public List<GcpProject> getProjects(Credential credential) throws ProjectRepositoryException {
  Preconditions.checkNotNull(credential);
  // TODO cache results https://github.com/GoogleCloudPlatform/google-cloud-eclipse/issues/1374
  try {
    Projects projects = apiFactory.newProjectsApi(credential);
    
    String token = null;
    List<Project> projectList = new ArrayList<>();
    do {
      Projects.List listRequest = projects.list().setPageSize(PROJECT_LIST_PAGESIZE);
      if (token != null) {
        listRequest = listRequest.setPageToken(token); 
      }
      ListProjectsResponse response = listRequest.execute();
      List<Project> responseProjects = response.getProjects();
      if (responseProjects != null) {
        projectList.addAll(responseProjects);
      }
      token = response.getNextPageToken();
    } while (token != null);
    List<GcpProject> gcpProjects = convertToGcpProjects(projectList);
    return gcpProjects;
  } catch (IOException ex) {
    throw new ProjectRepositoryException(ex);
  }
}
 
Example #12
Source File: Authenticator.java    From styx with Apache License 2.0 5 votes vote down vote up
private boolean resolveProject(Project project) throws IOException {
  final ResourceId resourceId = resourceId(project);
  if (isWhitelisted(resourceId)) {
    return true;
  }
  if (project.getParent() != null && isWhitelisted(project.getParent())) {
    return true;
  }
  return resolveProjectAccess(project.getProjectId());
}
 
Example #13
Source File: DesiredStateEnforcerTest.java    From policyscanner with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws GeneralSecurityException, IOException {
  GCPProject.setProjectsApiStub(projectsObject);

  CloudResourceManager.Projects.List emptyList = mock(CloudResourceManager.Projects.List.class);
  ListProjectsResponse emptyListProjectResponse = new ListProjectsResponse();

  when(projectsObject.list()).thenReturn(listProjects);
  when(listProjects.setPageToken(anyString())).thenReturn(emptyList);
  when(listProjects.setPageToken(null)).thenReturn(listProjects);
  when(listProjects.setFilter(anyString())).thenReturn(listProjects);

  when(emptyList.setPageToken(null)).thenReturn(emptyList);
  when(emptyList.setPageToken(anyString())).thenReturn(emptyList);
  when(emptyList.setFilter(anyString())).thenReturn(emptyList);

  when(emptyList.execute()).thenReturn(emptyListProjectResponse
      .setNextPageToken("maybe halt?")
      .setProjects(new ArrayList<Project>(0)));

  when(objectList.setPageToken(anyString())).thenReturn(objectList);
  when(objectList.setPageToken(null)).thenReturn(objectList);
  when(objectList.setPrefix(anyString())).thenReturn(objectList);

  when(objects.list(anyString())).thenReturn(objectList);
  when(objects.get(anyString(), anyString())).thenReturn(objectGet);
  when(gcs.objects()).thenReturn(objects);

  when(buckets.get(anyString())).thenReturn(bucketGet);
  when(gcs.buckets()).thenReturn(buckets);

  when(this.projectsObject.getIamPolicy(anyString(), any(GetIamPolicyRequest.class)))
      .thenReturn(this.getIamPolicy);

  GCSFilesSource.setStorageApiStub(gcs);
  this.checkedSource = new GCSFilesSource(BUCKET, ORG_ID);
}
 
Example #14
Source File: OnDemandLiveStateCheckerTest.java    From policyscanner with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws GeneralSecurityException, IOException {
  GCPProject.setProjectsApiStub(projectsObject);

  CloudResourceManager.Projects.List emptyList = mock(CloudResourceManager.Projects.List.class);
  ListProjectsResponse emptyListProjectResponse = new ListProjectsResponse();

  when(projectsObject.list()).thenReturn(listProjects);
  when(listProjects.setPageToken(anyString())).thenReturn(emptyList);
  when(listProjects.setPageToken(null)).thenReturn(listProjects);
  when(listProjects.setFilter(anyString())).thenReturn(listProjects);

  when(emptyList.setPageToken(null)).thenReturn(emptyList);
  when(emptyList.setPageToken(anyString())).thenReturn(emptyList);
  when(emptyList.setFilter(anyString())).thenReturn(emptyList);

  when(emptyList.execute()).thenReturn(emptyListProjectResponse
      .setNextPageToken("maybe halt?")
      .setProjects(new ArrayList<Project>(0)));

  when(objectList.setPageToken(anyString())).thenReturn(objectList);
  when(objectList.setPageToken(null)).thenReturn(objectList);
  when(objectList.setPrefix(anyString())).thenReturn(objectList);

  when(objects.list(anyString())).thenReturn(objectList);
  when(objects.get(anyString(), anyString())).thenReturn(objectGet);
  when(gcs.objects()).thenReturn(objects);

  when(buckets.get(anyString())).thenReturn(bucketGet);
  when(gcs.buckets()).thenReturn(buckets);

  when(this.projectsObject.getIamPolicy(anyString(), any(GetIamPolicyRequest.class)))
      .thenReturn(this.getIamPolicy);

  GCSFilesSource.setStorageApiStub(gcs);
  this.checkedSource = new GCSFilesSource(BUCKET, ORG_ID);
}
 
Example #15
Source File: LiveProjectSourceTest.java    From policyscanner with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdvanceWhenPageTokenNull() {
  String projectName = "sampleProjectName";
  String projectId = "sampleProjectId";
  String orgId = ORG;
  ResourceId resourceId = new ResourceId().setId(orgId);
  GCPProject gcpProject = new GCPProject(projectId, orgId, projectName);
  Project project =
      new Project()
          .setProjectId(projectId)
          .setParent(resourceId)
          .setName(projectName)
          .setLifecycleState("ACTIVE");
  List<Project> projects = Arrays.asList(project);
  PipelineOptions options = PipelineOptionsFactory.create();
  LiveProjectReader reader;

  this.listProjectsResponse.setProjects(projects);
  this.listProjectsResponse.setNextPageToken(null);
  try {
    reader = (LiveProjectReader) this.source.createReader(options);
    assertTrue(reader.start());
    assertEquals(reader.getNextPageToken(), null);
    assertEquals(reader.getCurrent(), gcpProject);
    assertFalse(reader.advance());
    reader.getCurrent();
    fail("No exception when reading from empty source");
  } catch (IOException e) {
    fail("IOException in reader.start");
  } catch (NoSuchElementException ignored) {
    // test passed.
  }
}
 
Example #16
Source File: AuthenticatorTest.java    From styx with Apache License 2.0 4 votes vote down vote up
private void mockAncestryResponse(Project project, ResourceId... ancestors) throws IOException {
  final CloudResourceManager.Projects.GetAncestry ancestry = mock(CloudResourceManager.Projects.GetAncestry.class);
  doReturn(ancestryResponse(ancestors)).when(ancestry).execute();
  when(cloudResourceManager.projects().getAncestry(eq(project.getProjectId()), any()))
      .thenReturn(ancestry);
}
 
Example #17
Source File: ProjectRepository.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
private static GcpProject convertToGcpProject(Project project) {
  Preconditions.checkNotNull(project);
  return new GcpProject(project.getName(), project.getProjectId());
}
 
Example #18
Source File: LiveProjectSourceTest.java    From policyscanner with Apache License 2.0 4 votes vote down vote up
@Test
public void testAdvance() {
  String projectName = "sampleProjectName";
  String projectId = "sampleProjectId";
  String orgId = "sampleOrgId";
  ResourceId resourceId = new ResourceId().setId(orgId);
  GCPProject gcpProject = new GCPProject(projectId, orgId, projectName);
  Project project =
      new Project()
          .setProjectId(projectId)
          .setParent(resourceId)
          .setName(projectName)
          .setLifecycleState("ACTIVE");
  List<Project> projects = new ArrayList<>();
  String nextPageToken = null;
  PipelineOptions options = PipelineOptionsFactory.create();
  LiveProjectReader reader;

  projects = Arrays.asList(project);
  nextPageToken = "samplePageToken";
  this.listProjectsResponse.setProjects(projects);
  this.listProjectsResponse.setNextPageToken(nextPageToken);

  try {
    reader = (LiveProjectReader) this.source.createReader(options);
    assertTrue(reader.start());
    assertEquals(reader.getNextPageToken(), nextPageToken);
    assertEquals(reader.getProjects().size(), 1);
    assertEquals(reader.getCurrent(), gcpProject);

    this.listProjectsResponse.setNextPageToken(null);
    assertTrue(reader.advance());
    assertEquals(reader.getProjects().size(), 1);
    assertEquals(reader.getCurrent(), gcpProject);
    assertFalse(reader.advance());
    assertEquals(reader.getProjects().size(), 0);

    projects = Arrays.asList(project, project);
    this.listProjectsResponse.setProjects(projects);
    reader = (LiveProjectReader) this.source.createReader(options);
    assertTrue(reader.start());
    assertEquals(reader.getProjects().size(), 2);
    assertEquals(reader.getCurrent(), gcpProject);
    assertTrue(reader.advance());
    assertEquals(reader.getProjects().size(), 1);
    assertEquals(reader.getCurrent(), gcpProject);

    projects = new ArrayList<>();
    this.listProjectsResponse.setProjects(projects);
    assertFalse(reader.advance());
    assertEquals(reader.getProjects().size(), 0);
    assertFalse(reader.advance());
    assertEquals(reader.getProjects().size(), 0);
  } catch (IOException e) {
    fail("IOException in reader.start");
  }
}
 
Example #19
Source File: Authenticator.java    From styx with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static ResourceId resourceId(Project project) {
  return resourceId("project", project.getProjectId());
}
 
Example #20
Source File: OnDemandLiveStateCheckerTest.java    From policyscanner with Apache License 2.0 4 votes vote down vote up
@Test
public void testPipeline() throws IOException {
  String editorRole = "roles/editor";
  String editorMember = "serviceAccount:[email protected]";
  String editorMemberLive = "serviceAccount:[email protected]";
  String ownerRole = "roles/owner";
  String ownerMember = "user:[email protected]";
  String fileContent = "[\n"
      + "      {\n"
      + "        \"role\": \"" + ownerRole + "\",\n"
      + "        \"members\": [\n"
      + "          \"" + ownerMember + "\"\n"
      + "        ]\n"
      + "      },\n"
      + "      {\n"
      + "        \"role\": \"" + editorRole + "\",\n"
      + "        \"members\": [\n"
      + "          \"" + editorMember + "\"\n"
      + "        ]\n"
      + "      }\n"
      + "    ]";
  String filePath = ORG_ID + DELIM + PROJECT_ID + DELIM + POLICY_FILE;
  String projectName = "sampleProjectName";
  String projectId = PROJECT_ID;
  String orgId = ORG_ID;
  ResourceId resourceId = new ResourceId().setId(orgId);
  Project project =
      new Project()
          .setProjectId(projectId)
          .setParent(resourceId)
          .setName(projectName)
          .setLifecycleState("ACTIVE");
  Binding editorBinding = new Binding()
      .setRole(editorRole)
      .setMembers(Arrays.asList(editorMemberLive));
  Binding ownerBinding = new Binding()
      .setRole(ownerRole)
      .setMembers(Arrays.asList(ownerMember));
  List<Binding> bindings = Arrays.asList(ownerBinding, editorBinding);
  Policy iamPolicy = new Policy().setBindings(bindings);
  PipelineOptions options = PipelineOptionsFactory.create();

  setUpGetFileContent(fileContent);
  setUpGetFilesPage(filePath);
  when(listProjects.execute())
      .thenReturn(this.listProjectsResponse
          .setNextPageToken("halting string")
          .setProjects(Arrays.asList(project)));
  when(this.getIamPolicy.execute()).thenReturn(iamPolicy);

  GCPProject.setProjectsApiStub(this.projectsObject);

  // setting up the output objects.
  GCPProject gcpProject = new GCPProject(projectId, orgId, projectName);
  PolicyBinding ownerPolicyBinding = new PolicyBinding(ownerRole, Arrays.asList(ownerMember));
  PolicyBinding editorPolicyBinding =
      new PolicyBinding(editorRole, Arrays.asList(editorMember));
  PolicyBinding editorPolicyBindingLive =
      new PolicyBinding(editorRole, Arrays.asList(editorMemberLive));
  GCPResourcePolicy checkedPolicy = new GCPResourcePolicy(
      gcpProject, Arrays.asList(ownerPolicyBinding, editorPolicyBinding));
  GCPResourcePolicy livePolicy = new GCPResourcePolicy(
      gcpProject, Arrays.asList(ownerPolicyBinding, editorPolicyBindingLive));
  Map<StateSource, GCPResourceState> outputMap = new HashMap<>(2);
  outputMap.put(StateSource.DESIRED, checkedPolicy);
  outputMap.put(StateSource.LIVE, livePolicy);

  new OnDemandLiveStateChecker(options, this.checkedSource)
  .appendAssertContains(new String[]{constructMessage(gcpProject, outputMap)})
  .run();
}
 
Example #21
Source File: LiveStateCheckerTest.java    From policyscanner with Apache License 2.0 4 votes vote down vote up
@Test
public void testUnmatchedStatesOutputIsCorrect() throws IOException {
  // create the policy for the live project
  String editorRole = "roles/editor";
  String editorMember = "serviceAccount:[email protected]";
  String ownerRole = "roles/owner";
  String ownerMember = "user:[email protected]";
  String fileContent = "[\n"
      + "      {\n"
      + "        \"role\": \"" + ownerRole + "\",\n"
      + "        \"members\": [\n"
      + "          \"" + ownerMember + "\"\n"
      + "        ]\n"
      + "      },\n"
      + "      {\n"
      + "        \"role\": \"" + editorRole + "\",\n"
      + "        \"members\": [\n"
      + "          \"" + editorMember + "\"\n"
      + "        ]\n"
      + "      }\n"
      + "    ]";
  String liveProjectName = "someLiveProjectName";
  String liveProjectId = "someLiveProjectId";
  String orgId = ORG_ID;
  ResourceId resourceId = new ResourceId().setId(orgId);
  Project liveProject =
      new Project()
          .setProjectId(liveProjectId)
          .setParent(resourceId)
          .setName(liveProjectName)
          .setLifecycleState("ACTIVE");
  Binding editorBinding = new Binding()
      .setRole(editorRole)
      .setMembers(Arrays.asList(editorMember));
  Binding ownerBinding = new Binding()
      .setRole(ownerRole)
      .setMembers(Arrays.asList(ownerMember));
  List<Binding> bindings = Arrays.asList(ownerBinding, editorBinding);
  Policy iamPolicy = new Policy().setBindings(bindings);
  // when calling projects().list(), return the live project
  when(listProjects.execute())
  .thenReturn(this.listProjectsResponse
      .setNextPageToken("halting string")
      .setProjects(Arrays.asList(liveProject)));
  when(this.getIamPolicy.execute()).thenReturn(iamPolicy);

  // mock out the desired policy
  String desiredProjectId = "someKnownGoodProject";
  String desiredPolicyPath = ORG_ID + DELIM + desiredProjectId + DELIM + POLICY_FILE;

  setUpGetFileContent(fileContent);
  setUpGetFilesPage(desiredPolicyPath);

  PipelineOptions options = PipelineOptionsFactory.create();

  LiveStateChecker liveStateChecker =
      new LiveStateChecker(options, this.checkedSource, ORG_ID)
        .build();

  String[] expectedOutput = new String[] {
      "DESIRED:someKnownGoodProject",
      "LIVE:someLiveProjectId"
  };

  DataflowAssert
      .that(liveStateChecker.getUnmatchedStatesOutput())
      .containsInAnyOrder(expectedOutput);

  liveStateChecker.run();
}
 
Example #22
Source File: LiveStateCheckerTest.java    From policyscanner with Apache License 2.0 4 votes vote down vote up
@Test
public void testPipeline() throws IOException {
  String editorRole = "roles/editor";
  String editorMember = "serviceAccount:[email protected]";
  String editorMemberLive = "serviceAccount:[email protected]";
  String ownerRole = "roles/owner";
  String ownerMember = "user:[email protected]";
  String fileContent = "[\n"
      + "      {\n"
      + "        \"role\": \"" + ownerRole + "\",\n"
      + "        \"members\": [\n"
      + "          \"" + ownerMember + "\"\n"
      + "        ]\n"
      + "      },\n"
      + "      {\n"
      + "        \"role\": \"" + editorRole + "\",\n"
      + "        \"members\": [\n"
      + "          \"" + editorMember + "\"\n"
      + "        ]\n"
      + "      }\n"
      + "    ]";
  String filePath = ORG_ID + DELIM + PROJECT_ID + DELIM + POLICY_FILE;
  String projectName = "sampleProjectName";
  String projectId = PROJECT_ID;
  String orgId = ORG_ID;
  ResourceId resourceId = new ResourceId().setId(orgId);
  Project project =
      new Project()
          .setProjectId(projectId)
          .setParent(resourceId)
          .setName(projectName)
          .setLifecycleState("ACTIVE");
  Binding editorBinding = new Binding()
      .setRole(editorRole)
      .setMembers(Arrays.asList(editorMemberLive));
  Binding ownerBinding = new Binding()
      .setRole(ownerRole)
      .setMembers(Arrays.asList(ownerMember));
  List<Binding> bindings = Arrays.asList(ownerBinding, editorBinding);
  Policy iamPolicy = new Policy().setBindings(bindings);
  PipelineOptions options = PipelineOptionsFactory.create();

  setUpGetFileContent(fileContent);
  setUpGetFilesPage(filePath);
  when(listProjects.execute())
      .thenReturn(this.listProjectsResponse
          .setNextPageToken("halting string")
          .setProjects(Arrays.asList(project)));
  when(this.getIamPolicy.execute()).thenReturn(iamPolicy);

  GCPProject.setProjectsApiStub(this.projectsObject);

  // setting up the output objects.
  GCPProject gcpProject = new GCPProject(projectId, orgId, projectName);
  PolicyBinding ownerPolicyBinding = new PolicyBinding(ownerRole, Arrays.asList(ownerMember));
  PolicyBinding editorPolicyBinding =
      new PolicyBinding(editorRole, Arrays.asList(editorMember));
  PolicyBinding editorPolicyBindingLive =
      new PolicyBinding(editorRole, Arrays.asList(editorMemberLive));
  GCPResourcePolicy desiredPolicy = new GCPResourcePolicy(
      gcpProject, Arrays.asList(ownerPolicyBinding, editorPolicyBinding));
  GCPResourcePolicy livePolicy = new GCPResourcePolicy(
      gcpProject, Arrays.asList(ownerPolicyBinding, editorPolicyBindingLive));
  GCPResourcePolicyDiff diff = GCPResourcePolicyDiff.diff(desiredPolicy, livePolicy);
  MessageConstructor messageConstructor =
      new MessageConstructor(gcpProject, desiredPolicy, livePolicy, diff);

  new LiveStateChecker(options, this.checkedSource, ORG_ID)
      .build()
      .appendAssertContains(new String[]{messageConstructor.constructMessage()})
      .run();
}
 
Example #23
Source File: DesiredStateEnforcerTest.java    From policyscanner with Apache License 2.0 4 votes vote down vote up
@Test
public void testPipeline() throws IOException {
  String editorRole = "roles/editor";
  String editorMember = "serviceAccount:[email protected]";
  String editorMemberLive = "serviceAccount:[email protected]";
  String ownerRole = "roles/owner";
  String ownerMember = "user:[email protected]";
  String fileContent = "[\n"
      + "      {\n"
      + "        \"role\": \"" + ownerRole + "\",\n"
      + "        \"members\": [\n"
      + "          \"" + ownerMember + "\"\n"
      + "        ]\n"
      + "      },\n"
      + "      {\n"
      + "        \"role\": \"" + editorRole + "\",\n"
      + "        \"members\": [\n"
      + "          \"" + editorMember + "\"\n"
      + "        ]\n"
      + "      }\n"
      + "    ]";
  String filePath = ORG_ID + DELIM + PROJECT_ID + DELIM + POLICY_FILE;
  String projectName = "sampleProjectName";
  String projectId = PROJECT_ID;
  String orgId = ORG_ID;
  ResourceId resourceId = new ResourceId().setId(orgId);
  Project project =
      new Project()
          .setProjectId(projectId)
          .setParent(resourceId)
          .setName(projectName)
          .setLifecycleState("ACTIVE");
  Binding liveEditorBinding = new Binding()
      .setRole(editorRole)
      .setMembers(Arrays.asList(editorMemberLive));
  Binding editorBinding = new Binding()
      .setRole(editorRole)
      .setMembers(Arrays.asList(editorMember));
  Binding ownerBinding = new Binding()
      .setRole(ownerRole)
      .setMembers(Arrays.asList(ownerMember));
  List<Binding> liveBindings = Arrays.asList(ownerBinding, liveEditorBinding);
  List<Binding> checkedBindings = Arrays.asList(ownerBinding, editorBinding);
  Policy liveIamPolicy = new Policy().setBindings(liveBindings);
  Policy checkedIamPolicy = new Policy().setBindings(checkedBindings);
  PipelineOptions options = PipelineOptionsFactory.create();
  final Policy[] fixedPolicy = new Policy[1];

  setUpGetFileContent(fileContent);
  setUpGetFilesPage(filePath);
  setUpSetIamPolicy(fixedPolicy);
  when(listProjects.execute())
      .thenReturn(this.listProjectsResponse
          .setNextPageToken("halting string")
          .setProjects(Arrays.asList(project)));
  when(this.getIamPolicy.execute()).thenReturn(liveIamPolicy);

  GCPProject.setProjectsApiStub(this.projectsObject);

  // setting up the output objects.
  GCPProject gcpProject = new GCPProject(projectId, orgId, projectName);
  PolicyBinding ownerPolicyBinding = new PolicyBinding(ownerRole, Arrays.asList(ownerMember));
  PolicyBinding editorPolicyBinding =
      new PolicyBinding(editorRole, Arrays.asList(editorMember));
  PolicyBinding editorPolicyBindingLive =
      new PolicyBinding(editorRole, Arrays.asList(editorMemberLive));
  GCPResourcePolicy checkedPolicy = new GCPResourcePolicy(
      gcpProject, Arrays.asList(ownerPolicyBinding, editorPolicyBinding));
  GCPResourcePolicy livePolicy = new GCPResourcePolicy(
      gcpProject, Arrays.asList(ownerPolicyBinding, editorPolicyBindingLive));
  Map<StateSource, GCPResourceState> outputMap = new HashMap<>(2);
  outputMap.put(StateSource.DESIRED, checkedPolicy);
  outputMap.put(StateSource.LIVE, livePolicy);

  try {
    new DesiredStateEnforcer(options, this.checkedSource, ORG_ID)
        .appendAssertContains(new String[]{constructMessage(gcpProject, outputMap)})
        .run();
  } catch (AggregatorRetrievalException are) {
    are.printStackTrace();
  }
  assertEquals(fixedPolicy[0], checkedIamPolicy);
}