Search in sources :

Example 1 with OrganizationPrincipal

use of gov.cms.dpc.api.auth.OrganizationPrincipal in project dpc-app by CMSgov.

the class MacaroonsAuthenticator method authenticate.

@Override
public Optional<OrganizationPrincipal> authenticate(DPCAuthCredentials credentials) {
    logger.debug("Performing token authentication");
    // If we don't have a path authorizer, just return the principal
    final OrganizationPrincipal principal = new OrganizationPrincipal(credentials.getOrganization());
    if (credentials.getPathAuthorizer() == null) {
        logger.debug("No path authorizer is present, returning principal");
        return Optional.of(principal);
    }
    // If we're an organization, we just check the org ID against the path value and see if it matches
    if (credentials.getPathAuthorizer().type() == DPCResourceType.Organization) {
        return validateOrganization(principal, credentials);
    }
    // Otherwise, try to lookup the matching resource
    logger.debug("Looking up resource {} in path authorizer. With value: {}", credentials.getPathAuthorizer().type(), credentials.getPathAuthorizer().pathParam());
    Map<String, List<String>> searchParams = new HashMap<>();
    searchParams.put("_id", Collections.singletonList(credentials.getPathValue()));
    searchParams.put("organization", Collections.singletonList(credentials.getOrganization().getId()));
    // TODO: Remove with DPC-552
    if (credentials.getPathAuthorizer().type() == DPCResourceType.Group) {
        searchParams.put("_tag", Collections.singletonList(String.format("%s|%s", DPCIdentifierSystem.DPC.getSystem(), credentials.getOrganization().getId())));
    }
    final Bundle bundle = this.client.search().forResource(credentials.getPathAuthorizer().type().toString()).whereMap(searchParams).returnBundle(Bundle.class).encodedJson().execute();
    if (bundle.getTotal() == 0) {
        return Optional.empty();
    }
    return Optional.of(principal);
}
Also used : OrganizationPrincipal(gov.cms.dpc.api.auth.OrganizationPrincipal) Bundle(org.hl7.fhir.dstu3.model.Bundle)

Example 2 with OrganizationPrincipal

use of gov.cms.dpc.api.auth.OrganizationPrincipal in project dpc-app by CMSgov.

the class GroupResourceUnitTest method testExportWithInvalidTimes.

@Test
public void testExportWithInvalidTimes() {
    UUID orgId = UUID.randomUUID();
    Organization organization = new Organization();
    organization.setId(orgId.toString());
    Identifier identifier = new Identifier();
    identifier.setSystem(DPCIdentifierSystem.NPPES.getSystem()).setValue(NPIUtil.generateNPI());
    organization.setIdentifier(List.of(identifier));
    OrganizationPrincipal organizationPrincipal = new OrganizationPrincipal(organization);
    String groupId = "123456789";
    // Mock Group
    Group group = new Group();
    group.setId(groupId);
    group.addMember();
    group.addCharacteristic().getCode().addCoding().setCode("attributed-to");
    CodeableConcept codeableConcept = new CodeableConcept();
    codeableConcept.addCoding().setSystem(DPCIdentifierSystem.NPPES.getSystem()).setCode(NPIUtil.generateNPI());
    group.getCharacteristicFirstRep().setValue(codeableConcept);
    IReadExecutable<Group> readExec = mock(IReadExecutable.class);
    when(attributionClient.read().resource(Group.class).withId(new IdType("Group", groupId)).encodedJson()).thenReturn(readExec);
    when(readExec.execute()).thenReturn(group);
    IReadExecutable<Organization> readExec2 = mock(IReadExecutable.class);
    when(attributionClient.read().resource(Organization.class).withId(new IdType("Organization", orgId.toString())).encodedJson()).thenReturn(readExec2);
    when(readExec2.execute()).thenReturn(organization);
    // Mock fetching request Url
    when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:3002/v1/Group/1234567890/$export"));
    // Mock get bundle
    IOperationUntypedWithInput<Bundle> bundleOperation = mock(IOperationUntypedWithInput.class);
    when(attributionClient.operation().onInstance(new IdType(groupId)).named("patients").withParameters(any(Parameters.class)).returnResourceType(Bundle.class).useHttpGet().encodedJson()).thenReturn(bundleOperation);
    Bundle patients = new Bundle();
    patients.addEntry(new Bundle.BundleEntryComponent().setResource(new Patient().setIdentifier(List.of(new Identifier().setSystem(DPCIdentifierSystem.MBI.getSystem()).setValue("9S79A00AA00")))));
    when(bundleOperation.execute()).thenReturn(patients);
    Meta bfdTransactionMeta = new Meta();
    when(mockBfdClient.requestPatientFromServer(SYNTHETIC_BENE_ID, null, null).getMeta()).thenReturn(bfdTransactionMeta);
    // Test a few seconds into the future
    WebApplicationException exception = Assertions.assertThrows(BadRequestException.class, () -> {
        String since = OffsetDateTime.now(ZoneId.of("America/Puerto_Rico")).plusSeconds(10).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        resource.export(organizationPrincipal, groupId, null, FHIRMediaTypes.NDJSON, since, "respond-async", request);
    });
    assertEquals("'_since' query parameter cannot be a future date", exception.getMessage());
    // Test a few days into the future
    exception = Assertions.assertThrows(BadRequestException.class, () -> {
        final String since = OffsetDateTime.now().plusDays(2).toString();
        resource.export(organizationPrincipal, groupId, null, FHIRMediaTypes.NDJSON, since, "respond-async", request);
    });
    assertEquals("'_since' query parameter cannot be a future date", exception.getMessage());
    // Test bad format
    exception = Assertions.assertThrows(WebApplicationException.class, () -> {
        final String since = "2020-05-2X616:43:01.780+10:00";
        resource.export(organizationPrincipal, groupId, null, FHIRMediaTypes.NDJSON, since, "respond-async", request);
    });
    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), exception.getResponse().getStatus());
    verifyNoInteractions(request);
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) OrganizationPrincipal(gov.cms.dpc.api.auth.OrganizationPrincipal) BadRequestException(javax.ws.rs.BadRequestException) UUID(java.util.UUID) Test(org.junit.jupiter.api.Test)

Example 3 with OrganizationPrincipal

use of gov.cms.dpc.api.auth.OrganizationPrincipal in project dpc-app by CMSgov.

the class GroupResourceUnitTest method testOutputFormatSetting.

@Test
public void testOutputFormatSetting() {
    UUID orgId = UUID.randomUUID();
    Organization organization = new Organization();
    organization.setId(orgId.toString());
    Identifier identifier = new Identifier();
    identifier.setSystem(DPCIdentifierSystem.NPPES.getSystem()).setValue(NPIUtil.generateNPI());
    organization.setIdentifier(List.of(identifier));
    OrganizationPrincipal organizationPrincipal = new OrganizationPrincipal(organization);
    IReadExecutable<Group> readExec = mock(IReadExecutable.class);
    Group fakeGroup = new Group();
    fakeGroup.getMember().add(new Group.GroupMemberComponent());
    fakeGroup.addCharacteristic().getCode().addCoding().setCode("attributed-to");
    CodeableConcept codeableConcept = new CodeableConcept();
    codeableConcept.addCoding().setSystem(DPCIdentifierSystem.NPPES.getSystem()).setCode(NPIUtil.generateNPI());
    fakeGroup.getCharacteristicFirstRep().setValue(codeableConcept);
    when(attributionClient.read().resource(Group.class).withId(any(IdType.class)).encodedJson()).thenReturn(readExec);
    when(readExec.execute()).thenReturn(fakeGroup);
    IReadExecutable<Organization> readExec2 = mock(IReadExecutable.class);
    when(attributionClient.read().resource(Organization.class).withId(new IdType("Organization", orgId.toString())).encodedJson()).thenReturn(readExec2);
    when(readExec2.execute()).thenReturn(organization);
    IOperationUntypedWithInput<Bundle> operationInput = mock(IOperationUntypedWithInput.class);
    Patient fakePatient = new Patient();
    fakePatient.getIdentifier().add(new Identifier().setSystem(DPCIdentifierSystem.MBI.getSystem()).setValue("2S51C00AA00"));
    Bundle fakeBundle = new Bundle();
    fakeBundle.getEntry().add(new Bundle.BundleEntryComponent().setResource(fakePatient));
    when(attributionClient.operation().onInstance(any(IdType.class)).named("patients").withParameters(any(Parameters.class)).returnResourceType(Bundle.class).useHttpGet().encodedJson()).thenReturn(operationInput);
    when(operationInput.execute()).thenReturn(fakeBundle);
    when(mockBfdClient.requestPatientFromServer(anyString(), any(), any())).thenReturn(new Bundle());
    // Mock create job
    when(mockQueue.createJob(any(), any(), any(), any(), any(), any(), any(), any(), any(), anyBoolean(), anyBoolean())).thenReturn(UUID.randomUUID());
    // Mock fetching request Url
    when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:3002/v1/Group/1234567890/$export"));
    Assertions.assertDoesNotThrow(() -> {
        resource.export(organizationPrincipal, "roster-id", "Coverage", FHIRMediaTypes.APPLICATION_NDJSON, "2017-01-01T00:00:00Z", "respond-async", request);
    });
    Assertions.assertDoesNotThrow(() -> {
        resource.export(organizationPrincipal, "roster-id", "Coverage", FHIRMediaTypes.FHIR_NDJSON, "2017-01-01T00:00:00Z", "respond-async", request);
    });
    Assertions.assertDoesNotThrow(() -> {
        resource.export(organizationPrincipal, "roster-id", "Coverage", FHIRMediaTypes.NDJSON, "2017-01-01T00:00:00Z", "respond-async", request);
    });
    Assertions.assertThrows(BadRequestException.class, () -> resource.export(organizationPrincipal, "roster-id", "Coverage", FHIR_JSON, "2017-01-01T00:00:00Z", "respond-async", request));
    Assertions.assertThrows(BadRequestException.class, () -> resource.export(organizationPrincipal, "roster-id", "Coverage", null, "2017-01-01T00:00:00Z", "respond-async", request));
    Assertions.assertThrows(BadRequestException.class, () -> resource.export(organizationPrincipal, "roster-id", "Coverage", "", "2017-01-01T00:00:00Z", "respond-async", request));
    // 3 non bad requests
    verify(request, times(3)).getHeader(HttpHeaders.X_FORWARDED_FOR);
    verify(request, times(3)).getRemoteAddr();
}
Also used : OrganizationPrincipal(gov.cms.dpc.api.auth.OrganizationPrincipal) UUID(java.util.UUID) Test(org.junit.jupiter.api.Test)

Example 4 with OrganizationPrincipal

use of gov.cms.dpc.api.auth.OrganizationPrincipal in project dpc-app by CMSgov.

the class KeyResourceUnitTest method testSubmitKey.

@Test
public void testSubmitKey() throws GeneralSecurityException, IOException {
    UUID orgId = UUID.randomUUID();
    Organization organization = new Organization();
    organization.setId(orgId.toString());
    OrganizationPrincipal organizationPrincipal = new OrganizationPrincipal(organization);
    KeyResource.KeySignature keySignature = KeyResourceTest.generateKeyAndSignature();
    String label = "A test key label";
    resource.submitKey(organizationPrincipal, keySignature, Optional.of(label));
    ArgumentCaptor<PublicKeyEntity> keyEntityArgumentCaptor = ArgumentCaptor.forClass(PublicKeyEntity.class);
    Mockito.verify(publicKeyDao).persistPublicKey(keyEntityArgumentCaptor.capture());
    PublicKeyEntity keyEntity = keyEntityArgumentCaptor.getValue();
    assertEquals(orgId, keyEntity.getOrganization_id());
    assertEquals(label, keyEntity.getLabel());
    assertTrue(keySignature.getKey().replaceAll("[\n\r]+", "").contains(Base64.getMimeEncoder().encodeToString(keyEntity.getPublicKey().parsePublicKey().getEncoded()).replaceAll("[\n\r]+", "")));
}
Also used : OrganizationPrincipal(gov.cms.dpc.api.auth.OrganizationPrincipal) Organization(org.hl7.fhir.dstu3.model.Organization) UUID(java.util.UUID) PublicKeyEntity(gov.cms.dpc.api.entities.PublicKeyEntity) Test(org.junit.jupiter.api.Test)

Example 5 with OrganizationPrincipal

use of gov.cms.dpc.api.auth.OrganizationPrincipal in project dpc-app by CMSgov.

the class PatientResourceUnitTest method testSubmitPatient.

@Test
public void testSubmitPatient() {
    UUID orgId = UUID.randomUUID();
    Organization organization = new Organization();
    organization.setId(orgId.toString());
    OrganizationPrincipal organizationPrincipal = new OrganizationPrincipal(organization);
    Patient patient = new Patient();
    ICreateTyped createExec = Mockito.mock(ICreateTyped.class);
    Mockito.when(attributionClient.create().resource(patient).encodedJson()).thenReturn(createExec);
    MethodOutcome outcome = new MethodOutcome();
    outcome.setResource(patient);
    Mockito.when(createExec.execute()).thenReturn(outcome);
    Response response = resource.submitPatient(organizationPrincipal, patient);
    Patient result = (Patient) response.getEntity();
    assertEquals(patient, result);
    assertEquals("Organization/" + orgId, result.getManagingOrganization().getReference());
}
Also used : Response(javax.ws.rs.core.Response) OrganizationPrincipal(gov.cms.dpc.api.auth.OrganizationPrincipal) Organization(org.hl7.fhir.dstu3.model.Organization) ICreateTyped(ca.uhn.fhir.rest.gclient.ICreateTyped) Patient(org.hl7.fhir.dstu3.model.Patient) UUID(java.util.UUID) MethodOutcome(ca.uhn.fhir.rest.api.MethodOutcome) Test(org.junit.jupiter.api.Test)

Aggregations

OrganizationPrincipal (gov.cms.dpc.api.auth.OrganizationPrincipal)23 UUID (java.util.UUID)15 Test (org.junit.jupiter.api.Test)15 Organization (org.hl7.fhir.dstu3.model.Organization)11 MethodOutcome (ca.uhn.fhir.rest.api.MethodOutcome)6 ICreateTyped (ca.uhn.fhir.rest.gclient.ICreateTyped)6 Response (javax.ws.rs.core.Response)5 TasksCommon.extractOrganization (gov.cms.dpc.api.tasks.TasksCommon.extractOrganization)4 PublicKeyEntity (gov.cms.dpc.api.entities.PublicKeyEntity)3 WebApplicationException (javax.ws.rs.WebApplicationException)3 TokenEntity (gov.cms.dpc.api.entities.TokenEntity)2 Endpoint (org.hl7.fhir.dstu3.model.Endpoint)2 FhirContext (ca.uhn.fhir.context.FhirContext)1 ResourceNotFoundException (ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Macaroon (com.github.nitram509.jmacaroons.Macaroon)1 DPCAuthCredentials (gov.cms.dpc.api.auth.DPCAuthCredentials)1 StaticAuthFilter (gov.cms.dpc.api.auth.staticauth.StaticAuthFilter)1 StaticAuthenticator (gov.cms.dpc.api.auth.staticauth.StaticAuthenticator)1 ChecksumConverterProvider (gov.cms.dpc.api.converters.ChecksumConverterProvider)1