Search in sources :

Example 1 with AuthDataGenerator

use of org.dataportabilityproject.spi.gateway.auth.AuthDataGenerator in project data-transfer-project by google.

the class OauthCallbackHandler method handleExchange.

private String handleExchange(HttpExchange exchange) throws IOException {
    String redirect = "/error";
    try {
        Headers requestHeaders = exchange.getRequestHeaders();
        // Get the URL for the request - needed for the authorization.
        String requestURL = ReferenceApiUtils.createURL(requestHeaders.getFirst(HttpHeaders.HOST), exchange.getRequestURI().toString(), IS_LOCAL);
        Map<String, String> requestParams = ReferenceApiUtils.getRequestParams(exchange);
        String encodedIdCookie = ReferenceApiUtils.getCookie(requestHeaders, JsonKeys.ID_COOKIE_KEY);
        Preconditions.checkArgument(!Strings.isNullOrEmpty(encodedIdCookie), "Missing encodedIdCookie");
        String oauthToken = requestParams.get("oauth_token");
        Preconditions.checkArgument(!Strings.isNullOrEmpty(oauthToken), "Missing oauth_token");
        String oauthVerifier = requestParams.get("oauth_verifier");
        Preconditions.checkArgument(!Strings.isNullOrEmpty(oauthVerifier), "Missing oauth_verifier");
        // Valid job must be present
        Preconditions.checkArgument(!Strings.isNullOrEmpty(encodedIdCookie), "Encoded Id cookie required");
        UUID jobId = ReferenceApiUtils.decodeJobId(encodedIdCookie);
        PortabilityJob job = store.findJob(jobId);
        logger.debug("Found job: {}->{} in OCH", jobId, job);
        Preconditions.checkNotNull(job, "existing job not found for jobId: %s", jobId);
        // TODO: Determine service from job or from authUrl path?
        AuthMode authMode = ReferenceApiUtils.getAuthMode(exchange.getRequestHeaders());
        String service = (authMode == AuthMode.EXPORT) ? job.exportService() : job.importService();
        Preconditions.checkState(!Strings.isNullOrEmpty(service), "service not found, service: %s authMode: %s, jobId: %s", service, authMode, jobId.toString());
        AuthDataGenerator generator = registry.getAuthDataGenerator(service, job.transferDataType(), authMode);
        Preconditions.checkNotNull(generator, "Generator not found for type: %s, service: %s", job.transferDataType(), service);
        // Obtain the session key for this job
        String encodedSessionKey = job.jobAuthorization().sessionSecretKey();
        SecretKey key = symmetricKeyGenerator.parse(BaseEncoding.base64Url().decode(encodedSessionKey));
        // Retrieve initial auth data, if it existed
        AuthData initialAuthData = null;
        String encryptedInitialAuthData = (authMode == AuthMode.EXPORT) ? job.jobAuthorization().encryptedInitialExportAuthData() : job.jobAuthorization().encryptedInitialImportAuthData();
        if (encryptedInitialAuthData != null) {
            // Retrieve and parse the session key from the job
            // Decrypt and deserialize the object
            String serialized = DecrypterFactory.create(key).decrypt(encryptedInitialAuthData);
            initialAuthData = objectMapper.readValue(serialized, AuthData.class);
        }
        Preconditions.checkNotNull(initialAuthData, "Initial AuthData expected during Oauth 1.0 flow");
        // TODO: Use UUID instead of UUID.toString()
        // Generate auth data
        AuthData authData = generator.generateAuthData(baseApiUrl, oauthVerifier, jobId.toString(), initialAuthData, null);
        Preconditions.checkNotNull(authData, "Auth data should not be null");
        // Serialize and encrypt the auth data
        String serialized = objectMapper.writeValueAsString(authData);
        String encryptedAuthData = EncrypterFactory.create(key).encrypt(serialized);
        // Set new cookie
        ReferenceApiUtils.setCookie(exchange.getResponseHeaders(), encryptedAuthData, authMode);
        redirect = baseUrl + ((authMode == AuthMode.EXPORT) ? FrontendConstantUrls.URL_NEXT_PAGE : FrontendConstantUrls.URL_COPY_PAGE);
    } catch (Exception e) {
        logger.error("Error handling request", e);
        throw e;
    }
    return redirect;
}
Also used : PortabilityJob(org.dataportabilityproject.spi.cloud.types.PortabilityJob) AuthDataGenerator(org.dataportabilityproject.spi.gateway.auth.AuthDataGenerator) SecretKey(javax.crypto.SecretKey) AuthData(org.dataportabilityproject.types.transfer.auth.AuthData) HttpHeaders(com.google.common.net.HttpHeaders) Headers(com.sun.net.httpserver.Headers) UUID(java.util.UUID) AuthMode(org.dataportabilityproject.spi.gateway.auth.AuthServiceProviderRegistry.AuthMode) IOException(java.io.IOException)

Example 2 with AuthDataGenerator

use of org.dataportabilityproject.spi.gateway.auth.AuthDataGenerator in project data-transfer-project by google.

the class SimpleLoginSubmitHandler method handleExchange.

DataTransferResponse handleExchange(HttpExchange exchange) throws IOException {
    Headers requestHeaders = exchange.getRequestHeaders();
    try {
        SimpleLoginRequest request = objectMapper.readValue(exchange.getRequestBody(), SimpleLoginRequest.class);
        String encodedIdCookie = ReferenceApiUtils.getCookie(requestHeaders, JsonKeys.ID_COOKIE_KEY);
        Preconditions.checkArgument(!Strings.isNullOrEmpty(encodedIdCookie), "Missing encodedIdCookie");
        // Valid job must be present
        Preconditions.checkArgument(!Strings.isNullOrEmpty(encodedIdCookie), "Encoded Id cookie required");
        UUID jobId = ReferenceApiUtils.decodeJobId(encodedIdCookie);
        PortabilityJob job = store.findJob(jobId);
        Preconditions.checkNotNull(job, "existing job not found for jobId: %s", jobId);
        // TODO: Determine service from job or from authUrl path?
        AuthMode authMode = ReferenceApiUtils.getAuthMode(exchange.getRequestHeaders());
        // TODO: Determine service from job or from authUrl path?
        String service = (authMode == AuthMode.EXPORT) ? job.exportService() : job.importService();
        Preconditions.checkState(!Strings.isNullOrEmpty(service), "service not found, service: %s authMode: %s, jobId: %s", service, authMode, jobId);
        Preconditions.checkArgument(!Strings.isNullOrEmpty(request.getUsername()), "Missing valid username");
        Preconditions.checkArgument(!Strings.isNullOrEmpty(request.getPassword()), "Missing password");
        AuthDataGenerator generator = registry.getAuthDataGenerator(service, job.transferDataType(), AuthMode.EXPORT);
        Preconditions.checkNotNull(generator, "Generator not found for type: %s, service: %s", job.transferDataType(), service);
        // TODO: change signature to pass UUID
        // Generate and store auth data
        AuthData authData = generator.generateAuthData(baseApiUrl, request.getUsername(), jobId.toString(), null, request.getPassword());
        Preconditions.checkNotNull(authData, "Auth data should not be null");
        // Obtain the session key for this job
        String encodedSessionKey = job.jobAuthorization().sessionSecretKey();
        SecretKey key = symmetricKeyGenerator.parse(BaseEncoding.base64Url().decode(encodedSessionKey));
        // Serialize and encrypt the auth data
        String serialized = objectMapper.writeValueAsString(authData);
        String encryptedAuthData = EncrypterFactory.create(key).encrypt(serialized);
        // Set new cookie
        ReferenceApiUtils.setCookie(exchange.getResponseHeaders(), encryptedAuthData, authMode);
        return new DataTransferResponse(job.exportService(), job.importService(), job.transferDataType(), Status.INPROCESS, baseUrl + (authMode == AuthMode.EXPORT ? FrontendConstantUrls.URL_NEXT_PAGE : FrontendConstantUrls.URL_COPY_PAGE));
    } catch (Exception e) {
        logger.debug("Exception occurred while trying to handle request: {}", e);
        throw e;
    }
}
Also used : PortabilityJob(org.dataportabilityproject.spi.cloud.types.PortabilityJob) AuthDataGenerator(org.dataportabilityproject.spi.gateway.auth.AuthDataGenerator) SecretKey(javax.crypto.SecretKey) AuthData(org.dataportabilityproject.types.transfer.auth.AuthData) Headers(com.sun.net.httpserver.Headers) HttpHeaders(org.apache.http.HttpHeaders) SimpleLoginRequest(org.dataportabilityproject.types.client.transfer.SimpleLoginRequest) DataTransferResponse(org.dataportabilityproject.types.client.transfer.DataTransferResponse) UUID(java.util.UUID) AuthMode(org.dataportabilityproject.spi.gateway.auth.AuthServiceProviderRegistry.AuthMode) IOException(java.io.IOException)

Example 3 with AuthDataGenerator

use of org.dataportabilityproject.spi.gateway.auth.AuthDataGenerator in project data-transfer-project by google.

the class Oauth2CallbackHandler method handleExchange.

private String handleExchange(HttpExchange exchange) throws IOException {
    String redirect = "/error";
    try {
        Headers requestHeaders = exchange.getRequestHeaders();
        String requestURL = ReferenceApiUtils.createURL(requestHeaders.getFirst(HttpHeaders.HOST), exchange.getRequestURI().toString(), IS_LOCAL);
        AuthorizationCodeResponseUrl authResponse = new AuthorizationCodeResponseUrl(requestURL);
        // check for user-denied error
        if (authResponse.getError() != null) {
            logger.warn("Authorization DENIED: {} Redirecting to /error", authResponse.getError());
            return redirect;
        }
        // retrieve cookie from exchange
        Map<String, HttpCookie> httpCookies = ReferenceApiUtils.getCookies(requestHeaders);
        HttpCookie encodedIdCookie = httpCookies.get(JsonKeys.ID_COOKIE_KEY);
        Preconditions.checkArgument(encodedIdCookie != null && !Strings.isNullOrEmpty(encodedIdCookie.getValue()), "Encoded Id cookie required");
        UUID jobId = ReferenceApiUtils.decodeJobId(encodedIdCookie.getValue());
        logger.debug("State token: {}", authResponse.getState());
        // TODO(#258): Check job ID in state token, was broken during local demo
        // UUID jobIdFromState = ReferenceApiUtils.decodeJobId(authResponse.getState());
        // // TODO: Remove sanity check
        // Preconditions.checkState(
        // jobIdFromState.equals(jobId),
        // "Job id in cookie [%s] and request [%s] should match",
        // jobId,
        // jobIdFromState);
        PortabilityJob job = store.findJob(jobId);
        Preconditions.checkNotNull(job, "existing job not found for jobId: %s", jobId);
        // TODO: Determine service from job or from authUrl path?
        AuthMode authMode = ReferenceApiUtils.getAuthMode(exchange.getRequestHeaders());
        String service = (authMode == AuthMode.EXPORT) ? job.exportService() : job.importService();
        Preconditions.checkState(!Strings.isNullOrEmpty(service), "service not found, service: %s authMode: %s, jobId: %s", service, authMode, jobId.toString());
        AuthDataGenerator generator = registry.getAuthDataGenerator(service, job.transferDataType(), authMode);
        Preconditions.checkNotNull(generator, "Generator not found for type: %s, service: %s", job.transferDataType(), service);
        // Obtain the session key for this job
        String encodedSessionKey = job.jobAuthorization().sessionSecretKey();
        SecretKey key = symmetricKeyGenerator.parse(BaseEncoding.base64Url().decode(encodedSessionKey));
        // Retrieve initial auth data, if it existed
        AuthData initialAuthData = null;
        String encryptedInitialAuthData = (authMode == AuthMode.EXPORT) ? job.jobAuthorization().encryptedInitialExportAuthData() : job.jobAuthorization().encryptedInitialImportAuthData();
        if (encryptedInitialAuthData != null) {
            // Retrieve and parse the session key from the job
            // Decrypt and deserialize the object
            String serialized = DecrypterFactory.create(key).decrypt(encryptedInitialAuthData);
            initialAuthData = objectMapper.readValue(serialized, AuthData.class);
        }
        // TODO: Use UUID instead of UUID.toString()
        // Generate auth data
        AuthData authData = generator.generateAuthData(baseApiUrl, authResponse.getCode(), jobId.toString(), initialAuthData, null);
        Preconditions.checkNotNull(authData, "Auth data should not be null");
        // Serialize and encrypt the auth data
        String serialized = objectMapper.writeValueAsString(authData);
        String encryptedAuthData = EncrypterFactory.create(key).encrypt(serialized);
        // Set new cookie
        ReferenceApiUtils.setCookie(exchange.getResponseHeaders(), encryptedAuthData, authMode);
        redirect = baseUrl + ((authMode == AuthMode.EXPORT) ? FrontendConstantUrls.URL_NEXT_PAGE : FrontendConstantUrls.URL_COPY_PAGE);
    } catch (Exception e) {
        logger.error("Error handling request: {}", e);
        throw e;
    }
    return redirect;
}
Also used : PortabilityJob(org.dataportabilityproject.spi.cloud.types.PortabilityJob) AuthDataGenerator(org.dataportabilityproject.spi.gateway.auth.AuthDataGenerator) SecretKey(javax.crypto.SecretKey) AuthData(org.dataportabilityproject.types.transfer.auth.AuthData) HttpHeaders(com.google.common.net.HttpHeaders) Headers(com.sun.net.httpserver.Headers) AuthorizationCodeResponseUrl(com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl) UUID(java.util.UUID) HttpCookie(java.net.HttpCookie) AuthMode(org.dataportabilityproject.spi.gateway.auth.AuthServiceProviderRegistry.AuthMode) IOException(java.io.IOException)

Example 4 with AuthDataGenerator

use of org.dataportabilityproject.spi.gateway.auth.AuthDataGenerator in project data-transfer-project by google.

the class SetupHandler method handleImportSetup.

private DataTransferResponse handleImportSetup(Headers headers, PortabilityJob job, UUID jobId) throws IOException {
    String exportAuthCookie = ReferenceApiUtils.getCookie(headers, JsonKeys.EXPORT_AUTH_DATA_COOKIE_KEY);
    Preconditions.checkArgument(!Strings.isNullOrEmpty(exportAuthCookie), "Export auth cookie required");
    // Initial auth flow url
    AuthDataGenerator generator = registry.getAuthDataGenerator(job.importService(), job.transferDataType(), AuthMode.IMPORT);
    Preconditions.checkNotNull(generator, "Generator not found for type: %s, service: %s", job.transferDataType(), job.importService());
    String encodedJobId = ReferenceApiUtils.encodeJobId(jobId);
    AuthFlowConfiguration authFlowConfiguration = generator.generateConfiguration(baseApiUrl, encodedJobId);
    Preconditions.checkNotNull(authFlowConfiguration, "AuthFlowConfiguration not found for type: %s, service: %s", job.transferDataType(), job.importService());
    // If present, store initial auth data for export services, e.g. used for oauth1
    if (authFlowConfiguration.getInitialAuthData() != null) {
        // Retrieve and parse the session key from the job
        String sessionKey = job.jobAuthorization().sessionSecretKey();
        SecretKey key = symmetricKeyGenerator.parse(BaseEncoding.base64Url().decode(sessionKey));
        // Ensure intial auth data for import has not already been set
        Preconditions.checkState(Strings.isNullOrEmpty(job.jobAuthorization().encryptedInitialImportAuthData()));
        // Serialize and encrypt the initial auth data
        String serialized = objectMapper.writeValueAsString(authFlowConfiguration.getInitialAuthData());
        String encryptedInitialAuthData = EncrypterFactory.create(key).encrypt(serialized);
        // Add the serialized and encrypted initial auth data to the job authorization
        JobAuthorization updatedJobAuthorization = job.jobAuthorization().toBuilder().setEncryptedInitialImportAuthData(encryptedInitialAuthData).build();
        // Persist the updated PortabilityJob with the updated JobAuthorization
        PortabilityJob updatedPortabilityJob = job.toBuilder().setAndValidateJobAuthorization(updatedJobAuthorization).build();
        store.updateJob(jobId, updatedPortabilityJob);
    }
    return new DataTransferResponse(job.exportService(), job.importService(), job.transferDataType(), Status.INPROCESS, // Redirect to auth page of import service
    authFlowConfiguration.getUrl());
}
Also used : AuthFlowConfiguration(org.dataportabilityproject.spi.gateway.types.AuthFlowConfiguration) AuthDataGenerator(org.dataportabilityproject.spi.gateway.auth.AuthDataGenerator) JobAuthorization(org.dataportabilityproject.spi.cloud.types.JobAuthorization) PortabilityJob(org.dataportabilityproject.spi.cloud.types.PortabilityJob) SecretKey(javax.crypto.SecretKey) DataTransferResponse(org.dataportabilityproject.types.client.transfer.DataTransferResponse)

Example 5 with AuthDataGenerator

use of org.dataportabilityproject.spi.gateway.auth.AuthDataGenerator in project data-transfer-project by google.

the class DataTransferHandler method handle.

/**
 * Services the {@link CreateJobAction} via the {@link HttpExchange}.
 */
@Override
public void handle(HttpExchange exchange) throws IOException {
    Preconditions.checkArgument(ReferenceApiUtils.validateRequest(exchange, HttpMethods.POST, PATH), PATH + " only supports POST.");
    logger.debug("received request: {}", exchange.getRequestURI());
    DataTransferRequest request = objectMapper.readValue(exchange.getRequestBody(), DataTransferRequest.class);
    CreateJobActionRequest actionRequest = new CreateJobActionRequest(request.getSource(), request.getDestination(), request.getTransferDataType());
    CreateJobActionResponse actionResponse = createJobAction.handle(actionRequest);
    DataTransferResponse dataTransferResponse;
    if (actionResponse.getErrorMsg() != null) {
        logger.warn("Error during action: {}", actionResponse.getErrorMsg());
        handleError(exchange, request);
        return;
    }
    // Set new cookie
    String encodedJobId = ReferenceApiUtils.encodeJobId(actionResponse.getId());
    HttpCookie cookie = new HttpCookie(JsonKeys.ID_COOKIE_KEY, encodedJobId);
    exchange.getResponseHeaders().add(HttpHeaders.SET_COOKIE, cookie.toString() + ReferenceApiUtils.COOKIE_ATTRIBUTES);
    // Initial auth flow url
    AuthDataGenerator generator = registry.getAuthDataGenerator(request.getSource(), request.getTransferDataType(), AuthMode.EXPORT);
    Preconditions.checkNotNull(generator, "Generator not found for type: %s, service: %s", request.getTransferDataType(), request.getSource());
    AuthFlowConfiguration authFlowConfiguration = generator.generateConfiguration(baseApiUrl, encodedJobId);
    Preconditions.checkNotNull(authFlowConfiguration, "AuthFlowConfiguration not found for type: %s, service: %s", request.getTransferDataType(), request.getSource());
    PortabilityJob job = store.findJob(actionResponse.getId());
    logger.debug("Found job: {} in DTH", job);
    // If present, store initial auth data for export services, e.g. used for oauth1
    if (authFlowConfiguration.getInitialAuthData() != null) {
        // Retrieve and parse the session key from the job
        String sessionKey = job.jobAuthorization().sessionSecretKey();
        SecretKey key = symmetricKeyGenerator.parse(BaseEncoding.base64Url().decode(sessionKey));
        // Ensure intial auth data for export has not already been set
        Preconditions.checkState(Strings.isNullOrEmpty(job.jobAuthorization().encryptedInitialExportAuthData()));
        // Serialize and encrypt the initial auth data
        String serialized = objectMapper.writeValueAsString(authFlowConfiguration.getInitialAuthData());
        String encryptedInitialAuthData = EncrypterFactory.create(key).encrypt(serialized);
        // Add the serialized and encrypted initial auth data to the job authorization
        JobAuthorization updatedJobAuthorization = job.jobAuthorization().toBuilder().setEncryptedInitialExportAuthData(encryptedInitialAuthData).build();
        // Persist the updated PortabilityJob with the updated JobAuthorization
        PortabilityJob updatedPortabilityJob = job.toBuilder().setAndValidateJobAuthorization(updatedJobAuthorization).build();
        store.updateJob(actionResponse.getId(), updatedPortabilityJob);
        logger.debug("Updated job is: {}", updatedPortabilityJob);
        PortabilityJob storejob = store.findJob(actionResponse.getId());
        logger.debug("Job looked up in jobstore is: {} -> {}", actionResponse.getId(), storejob);
    }
    dataTransferResponse = new DataTransferResponse(request.getSource(), request.getDestination(), request.getTransferDataType(), Status.INPROCESS, authFlowConfiguration.getUrl());
    logger.debug("redirecting to: {}", authFlowConfiguration.getUrl());
    // Mark the response as type Json and send
    exchange.getResponseHeaders().set(CONTENT_TYPE, "application/json; charset=" + StandardCharsets.UTF_8.name());
    exchange.sendResponseHeaders(200, 0);
    objectMapper.writeValue(exchange.getResponseBody(), dataTransferResponse);
}
Also used : AuthFlowConfiguration(org.dataportabilityproject.spi.gateway.types.AuthFlowConfiguration) AuthDataGenerator(org.dataportabilityproject.spi.gateway.auth.AuthDataGenerator) PortabilityJob(org.dataportabilityproject.spi.cloud.types.PortabilityJob) JobAuthorization(org.dataportabilityproject.spi.cloud.types.JobAuthorization) SecretKey(javax.crypto.SecretKey) DataTransferRequest(org.dataportabilityproject.types.client.transfer.DataTransferRequest) DataTransferResponse(org.dataportabilityproject.types.client.transfer.DataTransferResponse) HttpCookie(java.net.HttpCookie) CreateJobActionRequest(org.dataportabilityproject.gateway.action.createjob.CreateJobActionRequest) CreateJobActionResponse(org.dataportabilityproject.gateway.action.createjob.CreateJobActionResponse)

Aggregations

SecretKey (javax.crypto.SecretKey)5 PortabilityJob (org.dataportabilityproject.spi.cloud.types.PortabilityJob)5 AuthDataGenerator (org.dataportabilityproject.spi.gateway.auth.AuthDataGenerator)5 Headers (com.sun.net.httpserver.Headers)3 IOException (java.io.IOException)3 UUID (java.util.UUID)3 AuthMode (org.dataportabilityproject.spi.gateway.auth.AuthServiceProviderRegistry.AuthMode)3 DataTransferResponse (org.dataportabilityproject.types.client.transfer.DataTransferResponse)3 AuthData (org.dataportabilityproject.types.transfer.auth.AuthData)3 HttpHeaders (com.google.common.net.HttpHeaders)2 HttpCookie (java.net.HttpCookie)2 JobAuthorization (org.dataportabilityproject.spi.cloud.types.JobAuthorization)2 AuthFlowConfiguration (org.dataportabilityproject.spi.gateway.types.AuthFlowConfiguration)2 AuthorizationCodeResponseUrl (com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl)1 HttpHeaders (org.apache.http.HttpHeaders)1 CreateJobActionRequest (org.dataportabilityproject.gateway.action.createjob.CreateJobActionRequest)1 CreateJobActionResponse (org.dataportabilityproject.gateway.action.createjob.CreateJobActionResponse)1 DataTransferRequest (org.dataportabilityproject.types.client.transfer.DataTransferRequest)1 SimpleLoginRequest (org.dataportabilityproject.types.client.transfer.SimpleLoginRequest)1