use of ch.cyberduck.core.preferences.HostPreferences in project cyberduck by iterate-ch.
the class BrickPairingSchedulerFeature method repeat.
public void repeat(final PasswordCallback callback) {
final long timeout = new HostPreferences(session.getHost()).getLong("brick.pairing.interrupt.ms");
final long start = System.currentTimeMillis();
scheduler.repeat(() -> {
try {
if (System.currentTimeMillis() - start > timeout) {
throw new ConnectionCanceledException(String.format("Interrupt polling for pairing key after %d", timeout));
}
this.operate(callback);
} catch (ConnectionCanceledException e) {
log.warn(String.format("Cancel processing scheduled task. %s", e.getMessage()), e);
callback.close(null);
this.shutdown();
} catch (BackgroundException e) {
log.warn(String.format("Failure processing scheduled task. %s", e.getMessage()), e);
callback.close(null);
this.shutdown();
}
}, new HostPreferences(session.getHost()).getLong("brick.pairing.interval.ms"), TimeUnit.MILLISECONDS);
}
use of ch.cyberduck.core.preferences.HostPreferences in project cyberduck by iterate-ch.
the class BrickPairingSchedulerFeature method operate.
/**
* Pool for pairing key from service
*
* @param callback Callback when service returns 200
*/
private void operate(final PasswordCallback callback) throws BackgroundException {
try {
final HttpPost resource = new HttpPost(String.format("%s/api/rest/v1/sessions/pairing_key/%s", new HostUrlProvider().withUsername(false).withPath(false).get(session.getHost()), token));
resource.setHeader(HttpHeaders.ACCEPT, "application/json");
resource.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
if (log.isInfoEnabled()) {
log.info(String.format("Fetch credentials for paring key %s from %s", token, resource));
}
final JsonObject json = session.getClient().execute(resource, new AbstractResponseHandler<JsonObject>() {
@Override
public JsonObject handleEntity(final HttpEntity entity) throws IOException {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(entity.getContent(), out);
return JsonParser.parseReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray()))).getAsJsonObject();
}
});
if (json.has("nickname")) {
if (new HostPreferences(session.getHost()).getBoolean("brick.pairing.nickname.configure")) {
final JsonPrimitive nickname = json.getAsJsonPrimitive("nickname");
if (StringUtils.isNotBlank(host.getNickname())) {
if (!StringUtils.equals(host.getNickname(), nickname.getAsString())) {
log.warn(String.format("Mismatch of nickname. Previously authorized as %s and now paired as %s", host.getNickname(), nickname.getAsString()));
callback.close(null);
throw new LoginCanceledException();
}
}
host.setNickname(nickname.getAsString());
}
}
final Credentials credentials = host.getCredentials();
if (json.has("user_username")) {
credentials.setUsername(json.getAsJsonPrimitive("user_username").getAsString());
} else {
throw new LoginFailureException(String.format("Invalid response for pairing key %s", token));
}
if (json.has("password")) {
credentials.setPassword(json.getAsJsonPrimitive("password").getAsString());
} else {
throw new LoginFailureException(String.format("Invalid response for pairing key %s", token));
}
if (json.has("server")) {
if (new HostPreferences(session.getHost()).getBoolean("brick.pairing.hostname.configure")) {
host.setHostname(URI.create(json.getAsJsonPrimitive("server").getAsString()).getHost());
}
}
callback.close(credentials.getUsername());
} catch (JsonParseException e) {
throw new DefaultIOExceptionMappingService().map(new IOException(e.getMessage(), e));
} catch (HttpResponseException e) {
switch(e.getStatusCode()) {
case HttpStatus.SC_NOT_FOUND:
log.warn(String.format("Missing login for pairing key %s", token));
cancel.verify();
break;
default:
throw new DefaultHttpResponseExceptionMappingService().map(e);
}
} catch (IOException e) {
throw new DefaultIOExceptionMappingService().map(e);
}
}
use of ch.cyberduck.core.preferences.HostPreferences in project cyberduck by iterate-ch.
the class SDSMissingFileKeysSchedulerFeature method deleteDeprecatedKeyPair.
private void deleteDeprecatedKeyPair(final SDSSession session) throws ApiException, BackgroundException {
if (new HostPreferences(session.getHost()).getBoolean("sds.encryption.missingkeys.delete.deprecated")) {
if (session.keyPairDeprecated() != null && !session.keyPairDeprecated().equals(session.keyPair())) {
final MissingKeysResponse missingKeys = new NodesApi(session.getClient()).requestMissingFileKeys(null, 1, null, null, session.userAccount().getId(), "previous_user_key", null);
if (missingKeys.getItems().isEmpty()) {
log.debug("No more deprecated fileKeys to migrate - deleting deprecated key pair");
new UserApi(session.getClient()).removeUserKeyPair(session.keyPairDeprecated().getPublicKeyContainer().getVersion(), null);
session.resetUserKeyPairs();
}
}
}
}
use of ch.cyberduck.core.preferences.HostPreferences in project cyberduck by iterate-ch.
the class SDSMoveFeature method move.
@Override
public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
try {
final long nodeId = Long.parseLong(nodeid.getVersionId(file, new DisabledListProgressListener()));
if (containerService.isContainer(file)) {
final Node node = new NodesApi(session.getClient()).updateRoom(new UpdateRoomRequest().name(renamed.getName()), nodeId, StringUtils.EMPTY, null);
nodeid.cache(renamed, file.attributes().getVersionId());
nodeid.cache(file, null);
return renamed.withAttributes(new SDSAttributesAdapter(session).toAttributes(node));
} else {
if (status.isExists()) {
// Handle case insensitive. Find feature will have reported target to exist if same name with different case
if (!new CaseInsensitivePathPredicate(file).test(renamed)) {
log.warn(String.format("Delete existing file %s", renamed));
new SDSDeleteFeature(session, nodeid).delete(Collections.singletonMap(renamed, status), connectionCallback, callback);
}
}
if (new SimplePathPredicate(file.getParent()).test(renamed.getParent())) {
// Rename only
if (file.isDirectory()) {
new NodesApi(session.getClient()).updateFolder(new UpdateFolderRequest().name(renamed.getName()), nodeId, StringUtils.EMPTY, null);
} else {
new NodesApi(session.getClient()).updateFile(new UpdateFileRequest().name(renamed.getName()), nodeId, StringUtils.EMPTY, null);
}
} else {
// Move to different parent
new NodesApi(session.getClient()).moveNodes(new MoveNodesRequest().resolutionStrategy(MoveNodesRequest.ResolutionStrategyEnum.OVERWRITE).addItemsItem(new MoveNode().id(nodeId).name(renamed.getName())).keepShareLinks(new HostPreferences(session.getHost()).getBoolean("sds.upload.sharelinks.keep")), Long.parseLong(nodeid.getVersionId(renamed.getParent(), new DisabledListProgressListener())), StringUtils.EMPTY, null);
}
nodeid.cache(renamed, file.attributes().getVersionId());
nodeid.cache(file, null);
// Copy original file attributes
return renamed.withAttributes(new PathAttributes(file.attributes()).withVersionId(String.valueOf(nodeId)));
}
} catch (ApiException e) {
throw new SDSExceptionMappingService(nodeid).map("Cannot rename {0}", e, file);
}
}
use of ch.cyberduck.core.preferences.HostPreferences in project cyberduck by iterate-ch.
the class SDSDirectS3MultipartWriteFeatureTest method testWriteEncrypted.
@Test
public void testWriteEncrypted() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).createRoom(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume)), true);
final byte[] content = RandomUtils.nextBytes(new HostPreferences(session.getHost()).getInteger("sds.upload.multipart.chunksize") + 1);
final Path test = new Path(room, new NFDNormalizer().normalize(String.format("รค%s", new AlphanumericRandomStringService().random())).toString(), EnumSet.of(Path.Type.file));
{
final TripleCryptWriteFeature writer = new TripleCryptWriteFeature(session, nodeid, new SDSDirectS3MultipartWriteFeature(session, nodeid));
final TransferStatus status = new TransferStatus();
status.setLength(content.length);
status.setChecksum(new MD5ChecksumCompute().compute(new ByteArrayInputStream(content), new TransferStatus()));
status.setTimestamp(1632127025217L);
final StatusOutputStream<Node> out = writer.write(test, status, new DisabledConnectionCallback());
assertNotNull(out);
new StreamCopier(status, status).transfer(new ByteArrayInputStream(content), out);
}
assertNotNull(test.attributes().getVersionId());
assertTrue(new DefaultFindFeature(session).find(test));
assertTrue(new SDSFindFeature(session, nodeid).find(test));
final PathAttributes attr = new SDSAttributesFinderFeature(session, nodeid).find(test);
assertEquals(test.attributes().getVersionId(), attr.getVersionId());
assertEquals(1632127025217L, attr.getModificationDate());
assertEquals(1632127025217L, new DefaultAttributesFinderFeature(session).find(test).getModificationDate());
final byte[] compare = new byte[content.length];
final InputStream stream = new TripleCryptReadFeature(session, nodeid, new SDSReadFeature(session, nodeid)).read(test, new TransferStatus().withLength(content.length), new DisabledConnectionCallback() {
@Override
public Credentials prompt(final Host bookmark, final String title, final String reason, final LoginOptions options) {
return new VaultCredentials("eth[oh8uv4Eesij");
}
});
IOUtils.readFully(stream, compare);
stream.close();
assertArrayEquals(content, compare);
String previousVersion = test.attributes().getVersionId();
// Overwrite
{
final byte[] change = RandomUtils.nextBytes(256);
final TransferStatus status = new TransferStatus();
status.setLength(change.length);
final TripleCryptWriteFeature writer = new TripleCryptWriteFeature(session, nodeid, new SDSDirectS3MultipartWriteFeature(session, nodeid));
final StatusOutputStream<Node> out = writer.write(test, status.exists(true), new DisabledConnectionCallback());
assertNotNull(out);
new StreamCopier(status, status).transfer(new ByteArrayInputStream(change), out);
assertNotEquals(test.attributes().getVersionId(), out.getStatus());
}
assertNotEquals(attr.getRevision(), new SDSAttributesFinderFeature(session, nodeid).find(test));
// Read with previous version must fail
try {
test.attributes().withVersionId(previousVersion);
new TripleCryptReadFeature(session, nodeid, new SDSReadFeature(session, nodeid)).read(test, new TransferStatus(), new DisabledConnectionCallback() {
@Override
public Credentials prompt(final Host bookmark, final String title, final String reason, final LoginOptions options) {
return new VaultCredentials("eth[oh8uv4Eesij");
}
});
fail();
} catch (NotfoundException e) {
// Expected
}
new SDSDeleteFeature(session, nodeid).delete(Collections.singletonList(room), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
Aggregations