Search in sources :

Example 1 with JSON

use of ch.cyberduck.core.sds.io.swagger.client.JSON in project cyberduck by iterate-ch.

the class SDSSession method connect.

@Override
protected SDSApiClient connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    if (preferences.getBoolean("sds.oauth.migrate.enable")) {
        if (host.getProtocol().isDeprecated()) {
            final Credentials credentials = host.getCredentials();
            if (!host.getCredentials().validate(host.getProtocol(), new LoginOptions(host.getProtocol()))) {
                log.warn(String.format("Skip migration with missing credentials for %s", host));
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Attempt migration to OAuth flow for %s", host));
                }
                try {
                    // Search for installed connection profile using OAuth authorization method
                    for (Protocol oauth : ProtocolFactory.get().find(new OAuthFinderPredicate(host.getProtocol().getIdentifier()))) {
                        // Run password flow to attempt to migrate to OAuth
                        final TokenResponse response = new PasswordTokenRequest(new ApacheHttpTransport(builder.build(proxy, this, prompt).build()), new GsonFactory(), new GenericUrl(Scheme.isURL(oauth.getOAuthTokenUrl()) ? oauth.getOAuthTokenUrl() : new HostUrlProvider().withUsername(false).withPath(true).get(oauth.getScheme(), host.getPort(), null, host.getHostname(), oauth.getOAuthTokenUrl())), host.getCredentials().getUsername(), host.getCredentials().getPassword()).setClientAuthentication(new BasicAuthentication(oauth.getOAuthClientId(), oauth.getOAuthClientSecret())).setRequestInitializer(new UserAgentHttpRequestInitializer(new PreferencesUseragentProvider())).execute();
                        final long expiryInMilliseconds = System.currentTimeMillis() + response.getExpiresInSeconds() * 1000;
                        credentials.setOauth(new OAuthTokens(response.getAccessToken(), response.getRefreshToken(), expiryInMilliseconds));
                        credentials.setSaved(true);
                        log.warn(String.format("Switch bookmark %s to protocol %s", host, oauth));
                        host.setProtocol(oauth);
                        break;
                    }
                } catch (IOException e) {
                    log.warn(String.format("Failure %s running password flow to migrate to OAuth", e));
                }
            }
        }
    }
    switch(SDSProtocol.Authorization.valueOf(host.getProtocol().getAuthorization())) {
        case oauth:
        case password:
            authorizationService = new OAuth2RequestInterceptor(builder.build(proxy, this, prompt).addInterceptorLast(new HttpRequestInterceptor() {

                @Override
                public void process(final HttpRequest request, final HttpContext context) {
                    if (request instanceof HttpRequestWrapper) {
                        final HttpRequestWrapper wrapper = (HttpRequestWrapper) request;
                        if (null != wrapper.getTarget()) {
                            if (StringUtils.equals(wrapper.getTarget().getHostName(), host.getHostname())) {
                                request.addHeader(HttpHeaders.AUTHORIZATION, String.format("Basic %s", Base64.encodeToString(String.format("%s:%s", host.getProtocol().getOAuthClientId(), host.getProtocol().getOAuthClientSecret()).getBytes(StandardCharsets.UTF_8), false)));
                            }
                        }
                    }
                }
            }).build(), host) {

                @Override
                public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
                    if (request instanceof HttpRequestWrapper) {
                        final HttpRequestWrapper wrapper = (HttpRequestWrapper) request;
                        if (null != wrapper.getTarget()) {
                            if (StringUtils.equals(wrapper.getTarget().getHostName(), host.getHostname())) {
                                super.process(request, context);
                            }
                        }
                    }
                }
            }.withRedirectUri(CYBERDUCK_REDIRECT_URI.equals(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() : Scheme.isURL(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() : new HostUrlProvider().withUsername(false).withPath(true).get(host.getProtocol().getScheme(), host.getPort(), null, host.getHostname(), host.getProtocol().getOAuthRedirectUrl()));
            try {
                authorizationService.withParameter("user_agent_info", Base64.encodeToString(InetAddress.getLocalHost().getHostName().getBytes(StandardCharsets.UTF_8), false));
            } catch (UnknownHostException e) {
                throw new DefaultIOExceptionMappingService().map(e);
            }
            configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
            configuration.addInterceptorLast(authorizationService);
            configuration.addInterceptorLast(new HttpRequestInterceptor() {

                @Override
                public void process(final HttpRequest request, final HttpContext context) {
                    request.removeHeaders(SDSSession.SDS_AUTH_TOKEN_HEADER);
                }
            });
            break;
        default:
            retryHandler = new SDSErrorResponseInterceptor(this, nodeid);
            configuration.setServiceUnavailableRetryStrategy(retryHandler);
            configuration.addInterceptorLast(retryHandler);
            break;
    }
    final CloseableHttpClient apache = configuration.build();
    final SDSApiClient client = new SDSApiClient(apache);
    client.setBasePath(new HostUrlProvider().withUsername(false).withPath(true).get(host.getProtocol().getScheme(), host.getPort(), null, host.getHostname(), host.getProtocol().getContext()));
    client.setHttpClient(ClientBuilder.newClient(new ClientConfig().register(new InputStreamProvider()).register(MultiPartFeature.class).register(new JSON()).register(JacksonFeature.class).connectorProvider(new HttpComponentsProvider(apache))));
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    client.setConnectTimeout(timeout);
    client.setReadTimeout(timeout);
    client.setUserAgent(new PreferencesUseragentProvider().get());
    return client;
}
Also used : UserAgentHttpRequestInitializer(ch.cyberduck.core.http.UserAgentHttpRequestInitializer) JSON(ch.cyberduck.core.sds.io.swagger.client.JSON) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) GenericUrl(com.google.api.client.http.GenericUrl) JacksonFeature(org.glassfish.jersey.jackson.JacksonFeature) OAuth2RequestInterceptor(ch.cyberduck.core.oauth.OAuth2RequestInterceptor) HttpRequestWrapper(org.apache.http.client.methods.HttpRequestWrapper) ClientConfig(org.glassfish.jersey.client.ClientConfig) HttpRequest(org.apache.http.HttpRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) GsonFactory(com.google.api.client.json.gson.GsonFactory) UnknownHostException(java.net.UnknownHostException) InputStreamProvider(org.glassfish.jersey.message.internal.InputStreamProvider) HttpContext(org.apache.http.protocol.HttpContext) OAuth2ErrorResponseInterceptor(ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor) IOException(java.io.IOException) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) MultiPartFeature(org.glassfish.jersey.media.multipart.MultiPartFeature) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) BasicAuthentication(com.google.api.client.http.BasicAuthentication) PasswordTokenRequest(com.google.api.client.auth.oauth2.PasswordTokenRequest) ApacheHttpTransport(com.google.api.client.http.apache.v2.ApacheHttpTransport) HttpComponentsProvider(ch.cyberduck.core.jersey.HttpComponentsProvider)

Example 2 with JSON

use of ch.cyberduck.core.sds.io.swagger.client.JSON in project cyberduck by iterate-ch.

the class TripleCryptConverterTest method testFileKey.

@Test
public void testFileKey() throws Exception {
    final JSON json = new JSON();
    final FileKey fileKey = TripleCryptConverter.toSwaggerFileKey(Crypto.generateFileKey(PlainFileKey.Version.AES256GCM));
    assertNotNull(fileKey.getIv());
    assertNotNull(fileKey.getKey());
    assertNull(fileKey.getTag());
    assertNotNull(fileKey.getVersion());
    final ObjectWriter writer = json.getContext(null).writerFor(FileKey.class);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    writer.writeValue(out, fileKey);
    final ByteBuffer buffer = ByteBuffer.wrap(out.toByteArray());
    final ObjectReader reader = json.getContext(null).readerFor(FileKey.class);
    assertEquals(fileKey, reader.readValue(buffer.array()));
}
Also used : PlainFileKey(com.dracoon.sdk.crypto.model.PlainFileKey) FileKey(ch.cyberduck.core.sds.io.swagger.client.model.FileKey) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JSON(ch.cyberduck.core.sds.io.swagger.client.JSON) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Aggregations

JSON (ch.cyberduck.core.sds.io.swagger.client.JSON)2 UserAgentHttpRequestInitializer (ch.cyberduck.core.http.UserAgentHttpRequestInitializer)1 HttpComponentsProvider (ch.cyberduck.core.jersey.HttpComponentsProvider)1 OAuth2ErrorResponseInterceptor (ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor)1 OAuth2RequestInterceptor (ch.cyberduck.core.oauth.OAuth2RequestInterceptor)1 FileKey (ch.cyberduck.core.sds.io.swagger.client.model.FileKey)1 PlainFileKey (com.dracoon.sdk.crypto.model.PlainFileKey)1 ObjectReader (com.fasterxml.jackson.databind.ObjectReader)1 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)1 PasswordTokenRequest (com.google.api.client.auth.oauth2.PasswordTokenRequest)1 TokenResponse (com.google.api.client.auth.oauth2.TokenResponse)1 BasicAuthentication (com.google.api.client.http.BasicAuthentication)1 GenericUrl (com.google.api.client.http.GenericUrl)1 ApacheHttpTransport (com.google.api.client.http.apache.v2.ApacheHttpTransport)1 GsonFactory (com.google.api.client.json.gson.GsonFactory)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 UnknownHostException (java.net.UnknownHostException)1 ByteBuffer (java.nio.ByteBuffer)1 HttpRequest (org.apache.http.HttpRequest)1