Compare commits

..
Author SHA1 Message Date
Armin Schrenk 4b6afb5fd6 if linked hub vault is alread present unlock/reveal
Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-08-31 18:59:34 +02:00
Armin Schrenk d2b1f86d85 Refactor Keyloading to use only the required info
* new record KeyLoadingRef(config, name)
* masterkey vaults still need Vault.java
* hub relies on KeyLoadingRef

Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-08-31 15:53:54 +02:00
Armin Schrenk b01478f0fa Remove VaultTemplate stuff
including jdk.zipfs as dependency in jlink

Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-08-26 17:08:29 +02:00
Armin Schrenk 27eb6298ae Refactor VaultCreationEvent to OpenHubVaultEvent
and change deeplink URL scheme to org.cryptomator

Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-08-26 16:50:26 +02:00
Armin Schrenk 2c53afd70f simplify
there is no intermediate directory in the zip. Also clean up tests

Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-21 17:06:17 +02:00
Armin Schrenk ae84f2f2fd move package related tasks to the importtemplate package
keeps FXApplicationWindows slim

Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-21 16:22:52 +02:00
Armin Schrenk ad17f0b835 Extract zip once
and show error if extraction fails

Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-21 14:21:02 +02:00
Armin Schrenk e7db172a89 restrict value of name parameter in deeplink
no path separator, no invisible chars, no trailing whitespaces

Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-21 11:50:31 +02:00
Armin Schrenk 222e1f18ad use fragements section for parameters
Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-20 13:52:25 +02:00
Armin Schrenk 9a3baf7119 Move VaultTemplateExtractor to package where it is actually used.
Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-20 12:09:23 +02:00
Armin Schrenk 53baf3c648 Improve error handling
Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-15 17:25:49 +02:00
Armin Schrenk c8a6b7cf13 show dialog on VaultCreationEvent
Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-15 16:34:38 +02:00
Armin Schrenk 5d12a62e38 Replace ImportTemplate stubs with impls
Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-14 17:22:45 +02:00
Armin Schrenk 40bb0079ac add ui to import a vault from template
add scaffolding, controller are stubs for now

Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-14 17:00:25 +02:00
Armin Schrenk fbdf511f05 add jdk.zipfs to jlinked modules
Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-14 15:31:59 +02:00
Armin Schrenk 410900ed51 add contraints to the zip'ed template
at most 2MiB, at most 30 files

Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-14 13:36:55 +02:00
Armin Schrenk 1302c1fc34 add vault template extraction
Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-13 16:25:59 +02:00
Armin Schrenk ea806ec97a Refactor event handling
AppLauchEvent became a sealed interface with implemented Events RevealRunningApp-, OpenFile- and ValtCreateEvent.

Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-13 13:45:21 +02:00
Armin Schrenk 77dbf9414a Add DeeplinkAction
for handling URIs

Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-13 10:27:23 +02:00
Armin Schrenk a3fc50fc7e remove and exclude build artifact
Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-07-13 10:12:52 +02:00
Armin Schrenk 4b0e8b5841 Merge branch 'develop' into feature/deeplinking 2026-07-07 16:23:09 +02:00
Andreas OpferkuchandGitHub 688d1a4a24 README: Update JDK version from 25 to 26 (#4269)
[ci skip]
2026-07-02 21:05:18 +02:00
Tobias Hagemann 56e655c5a9 Add ApiVoid as silver sponsor [ci skip] 2026-07-01 12:15:15 +02:00
Armin Schrenk 4c9dbb60fe fix b681c26d72
Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-06-29 14:44:13 +02:00
Armin Schrenk 7ddedea5c2 [skip ci] Merge branch 'main' into develop
Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-06-29 13:54:55 +02:00
Armin Schrenk a428ae6260 Implement uri handling inside app.
Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-06-10 15:48:25 +02:00
Armin Schrenk 9c41e348fa register url scheme "cryptomator" in installers
Signed-off-by: Armin Schrenk <armin.schrenk@skymatic.de>
2026-06-10 11:53:56 +02:00
41 changed files with 1121 additions and 88 deletions
+1 -1
View File
@@ -78,7 +78,7 @@ jobs:
local-dir: ./upload/
allowlist-avast:
name: Anti Virus Allowlisting Avast
runs-on: ubuntu
runs-on: ubuntu-latest
needs: download-file
if: inputs.avast
steps:
+2 -2
View File
@@ -6,7 +6,7 @@ on:
jobs:
notify:
runs-on: ubuntu
runs-on: ubuntu-latest
steps:
- name: Notify about DEB build
uses: rtCamp/action-slack-notify@33ca3be66c6f378fe1610fd1d5258632dbed5e58 # v2.4.0
@@ -102,7 +102,7 @@ jobs:
name: Notify for winget-release
if: needs.get-asset-urls.outputs.is-windows-release == 'true' && needs.check-release.outputs.release-kind == 'stable'
needs: [check-release, get-asset-urls]
runs-on: ubuntu
runs-on: ubuntu-latest
steps:
- name: Slack Notification
uses: rtCamp/action-slack-notify@33ca3be66c6f378fe1610fd1d5258632dbed5e58 # v2.4.0
+1 -1
View File
@@ -8,7 +8,7 @@
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" project-jdk-name="25" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_26" project-jdk-name="temurin-26" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
+5
View File
@@ -8,6 +8,11 @@ The changelog starts with version 1.19.0.
Changes to prior versions can be found on the [Github release page](https://github.com/cryptomator/cryptomator/releases).
## [Unreleased](https://github.com/cryptomator/cryptomator/compare/1.19.3...HEAD)
No changes yet.
## [1.19.3](https://github.com/cryptomator/cryptomator/releases/1.19.3) - 2026-06-29
### Added
* New error dialog if importing a vault fails ([#4243](https://github.com/cryptomator/cryptomator/pull/4243))
+2 -1
View File
@@ -26,6 +26,7 @@ Become our Gold Sponsor and showcase your brand to a targeted audience! Please c
<tr>
<td><a href="https://www.gee-whiz.de/"><img src="https://cryptomator.org/img/sponsors/geewhiz.svg" alt="gee-whiz" height="56"></a></td>
<td><a href="https://www.route4me.com/"><img src="https://cryptomator.org/img/sponsors/route4me.svg" alt="Route4Me" height="56"></a></td>
<td><a href="https://www.apivoid.com/"><img src="https://cryptomator.org/img/sponsors/apivoid.svg" alt="ApiVoid" height="56"></a></td>
</tr>
</tbody>
</table>
@@ -78,7 +79,7 @@ For more information on the security details visit [cryptomator.org](https://doc
### Dependencies
* JDK 25 (e.g. temurin, zulu)
* JDK 26 (e.g. temurin, zulu)
### Run Maven
+2 -2
View File
@@ -1,11 +1,11 @@
[Desktop Entry]
Name=Cryptomator
Comment=Cloud Storage Encryption Utility
Exec=cryptomator %F
Exec=cryptomator %U
Icon=org.cryptomator.Cryptomator
Terminal=false
Type=Application
Categories=Utility;Security;FileTools;
StartupNotify=true
StartupWMClass=org.cryptomator.launcher.Cryptomator$MainApp
MimeType=application/vnd.cryptomator.encrypted;application/vnd.cryptomator.vault;
MimeType=application/vnd.cryptomator.encrypted;application/vnd.cryptomator.vault;x-scheme-handler/org.cryptomator;
+1 -1
View File
@@ -11,7 +11,7 @@ pkgdesc="Multiplatform transparent client-side encryption of your files in the c
arch=('any')
url="https://cryptomator.org/"
license=('GPL3')
depends=('fuse3' 'alsa-lib' 'hicolor-icon-theme' 'libxtst' 'libnet' 'libxrender')
depends=('fuse3' 'alsa-lib' 'hicolor-icon-theme' 'libxtst' 'libnet' 'libxrender' 'desktop-file-utils')
makedepends=('maven' 'unzip')
optdepends=('keepassxc-cryptomator: Use KeePassXC to store vault passwords' 'ttf-hanazono: Install this font when using Japanese system language')
_jdkver=26.0.1+8
+14
View File
@@ -46,6 +46,20 @@
<string>Any</string>
</dict>
</dict>
<!-- register org.cryptomator:// URL scheme -->
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>org.cryptomator.deeplink</string>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>CFBundleURLSchemes</key>
<array>
<string>org.cryptomator</string>
</array>
</dict>
</array>
<!-- register .cryptomator extension -->
<key>CFBundleDocumentTypes</key>
<array>
+1
View File
@@ -9,3 +9,4 @@ installer
*.jmod
resources/jfxJmods.zip
license.rtf
**/FAvaultFile.properties
-4
View File
@@ -1,4 +0,0 @@
mime-type=application/vnd.cryptomator.vault
extension=cryptomator
description=Cryptomator Vault File
icon=C:\\Users\\Arbeit\\Skymatic\\cryptomator-jdk26-jpackage\\dist\\win\\resources\\Cryptomator-Vault.ico
+15
View File
@@ -27,6 +27,7 @@
<?define ProgIdContentType= "application/vnd.cryptomator.encrypted" ?>
<?define CloseApplicationTarget= "cryptomator.exe" ?>
<?define LoopbackAlias= "cryptomator-vault" ?>
<?define UrlProtocolScheme= "org.cryptomator" ?>
<?include $(var.JpConfigDir)/overrides.wxi ?>
@@ -97,6 +98,19 @@
<ns0:Extension Id="c9u" Advertise="no" ContentType="$(var.ProgIdContentType)"/>
</ns0:ProgId>
</ns0:Component>
<!-- Register "org.cryptomator://" URL protocol handler -->
<ns0:Component Bitness="always64" Id="UrlProtocolHandler" Guid="*">
<ns0:RegistryKey Root="HKMU" Key="Software\Classes\$(var.UrlProtocolScheme)">
<ns0:RegistryValue Type="string" Value="URL:$(var.JpAppName) Protocol" KeyPath="yes"/>
<ns0:RegistryValue Name="URL Protocol" Type="string" Value=""/>
<ns0:RegistryKey Key="DefaultIcon">
<ns0:RegistryValue Type="string" Value="[INSTALLDIR]$(var.JpAppName).exe,0"/>
</ns0:RegistryKey>
<ns0:RegistryKey Key="shell\open\command">
<ns0:RegistryValue Type="string" Value="&quot;[INSTALLDIR]$(var.JpAppName).exe&quot; &quot;%1&quot;"/>
</ns0:RegistryKey>
</ns0:RegistryKey>
</ns0:Component>
</ns0:DirectoryRef>
<ns0:StandardDirectory Id="CommonAppDataFolder">
@@ -126,6 +140,7 @@
<ns0:ComponentGroupRef Id="FileAssociations"/>
<!-- Ref to additional ProgIDs -->
<ns0:ComponentRef Id="nonStartingProgID"/>
<ns0:ComponentRef Id="UrlProtocolHandler"/>
<ns0:ComponentRef Id="AdminConfigDir"/>
<ns0:ComponentRef Id="AdminConfigFile"/>
</ns0:Feature>
+2 -2
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.cryptomator</groupId>
<artifactId>cryptomator</artifactId>
<version>1.19.3</version>
<version>1.20.0-SNAPSHOT</version>
<name>Cryptomator Desktop App</name>
<organization>
@@ -33,7 +33,7 @@
<nonModularGroupIds>org.ow2.asm,org.apache.jackrabbit,org.apache.httpcomponents</nonModularGroupIds>
<!-- cryptomator dependencies -->
<cryptomator.cryptofs.version>2.10.0</cryptomator.cryptofs.version>
<cryptomator.cryptofs.version>2.11.0-SNAPSHOT</cryptomator.cryptofs.version>
<cryptomator.cryptolib.version>2.2.2</cryptomator.cryptolib.version>
<cryptomator.integrations.version>1.9.0</cryptomator.integrations.version>
<cryptomator.integrations.win.version>1.6.1</cryptomator.integrations.win.version>
@@ -1,13 +1,16 @@
package org.cryptomator.launcher;
import java.nio.file.Path;
import java.util.Collection;
public record AppLaunchEvent(AppLaunchEvent.EventType type, Collection<Path> pathsToOpen) {
public enum EventType {
REVEAL_APP,
OPEN_FILE
}
/**
* An event triggering an action in the running application instance.
* <p>
* Produced by the launch-argument handling (see {@link LaunchArgsParser} and the {@code *RequestHandler}s) and consumed
* by the UI's {@code AppLaunchEventHandler}. Each permitted subtype represents one supported action:
* <ul>
* <li>{@link RevealRunningEvent} - reveal the already-running app,</li>
* <li>{@link OpenFileEvent} - open one or more paths,</li>
* <li>{@link OpenHubVaultEvent} - open a Hub vault from a deeplink.</li>
* </ul>
*/
public sealed interface AppLaunchEvent permits RevealRunningEvent, OpenFileEvent, OpenHubVaultEvent {
}
@@ -25,7 +25,7 @@ class CryptomatorModule {
@Provides
@Singleton
@Named("launchEventQueue")
static BlockingQueue<AppLaunchEvent> provideFileOpenRequests() {
static BlockingQueue<AppLaunchEvent> provideLaunchEventQueue() {
return new ArrayBlockingQueue<>(10);
}
@@ -41,7 +41,7 @@ class FileOpenRequestHandler {
private void openFiles(OpenFilesEvent evt) {
Collection<Path> pathsToOpen = evt.getFiles().stream().map(File::toPath).toList();
AppLaunchEvent launchEvent = new AppLaunchEvent(AppLaunchEvent.EventType.OPEN_FILE, pathsToOpen);
AppLaunchEvent launchEvent = new OpenFileEvent(pathsToOpen);
tryToEnqueueFileOpenRequest(launchEvent);
}
@@ -60,7 +60,7 @@ class FileOpenRequestHandler {
}
}).filter(Objects::nonNull).toList();
if (!pathsToOpen.isEmpty()) {
AppLaunchEvent launchEvent = new AppLaunchEvent(AppLaunchEvent.EventType.OPEN_FILE, pathsToOpen);
AppLaunchEvent launchEvent = new OpenFileEvent(pathsToOpen);
tryToEnqueueFileOpenRequest(launchEvent);
}
}
@@ -68,7 +68,7 @@ class FileOpenRequestHandler {
private void tryToEnqueueFileOpenRequest(AppLaunchEvent launchEvent) {
if (!launchEventQueue.offer(launchEvent)) {
LOG.warn("Could not enqueue application launch event.", launchEvent);
LOG.warn("Could not enqueue application launch event {}.", launchEvent);
}
}
@@ -7,7 +7,6 @@ import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
@@ -16,24 +15,28 @@ class IpcMessageHandler implements IpcMessageListener {
private static final Logger LOG = LoggerFactory.getLogger(IpcMessageHandler.class);
private final FileOpenRequestHandler fileOpenRequestHandler;
private final LaunchArgsParser launchArgsParser;
private final BlockingQueue<AppLaunchEvent> launchEventQueue;
@Inject
public IpcMessageHandler(FileOpenRequestHandler fileOpenRequestHandler, @Named("launchEventQueue") BlockingQueue<AppLaunchEvent> launchEventQueue) {
this.fileOpenRequestHandler = fileOpenRequestHandler;
public IpcMessageHandler(LaunchArgsParser launchArgsParser, @Named("launchEventQueue") BlockingQueue<AppLaunchEvent> launchEventQueue) {
this.launchArgsParser = launchArgsParser;
this.launchEventQueue = launchEventQueue;
}
@Override
public void revealRunningApp() {
launchEventQueue.add(new AppLaunchEvent(AppLaunchEvent.EventType.REVEAL_APP, Collections.emptyList()));
launchEventQueue.add(new RevealRunningEvent());
}
@Override
public void handleLaunchArgs(List<String> args) {
LOG.debug("Received launch args: {}", args.stream().reduce((a, b) -> a + ", " + b).orElse(""));
fileOpenRequestHandler.handleLaunchArgs(args);
LOG.debug("Received launch args: {}", args);
try {
launchArgsParser.process(args);
} catch (IllegalArgumentException e) {
LOG.warn("Ignoring malformed launch args: {}", e.getMessage());
}
}
}
@@ -0,0 +1,88 @@
package org.cryptomator.launcher;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.net.URI;
import java.nio.file.Path;
import java.util.List;
import java.util.regex.Pattern;
/**
* Preprocesses the launch arguments and delegates them to the matching handler.
* <p>
* An argument is treated as a URI if it starts with a (non-{@code file}) scheme of at least two characters, e.g.
* {@code cryptomator://…}. Everything else - including plain paths and {@code file://…} URIs - is treated as a file path
* and forwarded to the {@link FileOpenRequestHandler}. The two-character minimum prevents Windows drive letters
* (e.g. {@code C:\…}) from being misinterpreted as URIs.
* <p>
* URIs and file paths must not be mixed and at most a single URI is accepted, which has to be the first argument.
*/
@Singleton
class LaunchArgsParser {
private static final Pattern SCHEME_PATTERN = Pattern.compile("^([a-zA-Z][a-zA-Z0-9+.-]+):.*");
private static final String FILE_SCHEME = "file";
private final FileOpenRequestHandler fileOpenRequestHandler;
private final URIOpenRequestHandler uriOpenRequestHandler;
private final NoopRequestHandler noopRequestHandler;
@Inject
public LaunchArgsParser(FileOpenRequestHandler fileOpenRequestHandler, URIOpenRequestHandler uriOpenRequestHandler, NoopRequestHandler noopRequestHandler) {
this.fileOpenRequestHandler = fileOpenRequestHandler;
this.uriOpenRequestHandler = uriOpenRequestHandler;
this.noopRequestHandler = noopRequestHandler;
}
/**
* Classifies the given launch arguments and delegates them to the responsible handler.
*
* @param args the raw launch arguments
* @throws IllegalArgumentException if URIs and file paths are mixed, if more than one URI is given, if a URI is not
* the first argument, or if a URI argument is malformed
*/
public void process(List<String> args) {
if(args.isEmpty()) {
noopRequestHandler.revealApp();
return;
}
var classified = args.stream().map(LaunchArgsParser::classify).toList();
var uris = classified.stream().filter(arg -> arg.kind() == Kind.URI).toList();
if (uris.isEmpty()) {
var paths = classified.stream().map(Arg::value).toList();
fileOpenRequestHandler.handleLaunchArgs(paths);
return;
}
if (uris.size() > 1) {
throw new IllegalArgumentException("Only a single URI argument is accepted, but got " + uris.size() + ".");
}
if (classified.getFirst().kind() != Kind.URI) {
throw new IllegalArgumentException("URI argument must be the first parameter.");
}
if (classified.size() > 1) {
throw new IllegalArgumentException("Mixing a URI with file paths is not supported.");
}
uriOpenRequestHandler.handleLaunchArgs(URI.create(classified.getFirst().value()));
}
private static Arg classify(String arg) {
var matcher = SCHEME_PATTERN.matcher(arg);
if (!matcher.matches()) {
return new Arg(Kind.PATH, arg);
}
var scheme = matcher.group(1);
if (FILE_SCHEME.equalsIgnoreCase(scheme)) {
// file:// URIs (e.g. passed by Linux file managers) are file paths in disguise
return new Arg(Kind.PATH, Path.of(URI.create(arg)).toString());
}
return new Arg(Kind.URI, arg);
}
private enum Kind {PATH, URI}
private record Arg(Kind kind, String value) {}
}
@@ -0,0 +1,29 @@
package org.cryptomator.launcher;
import javax.inject.Inject;
import javax.inject.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Singleton;
import java.util.concurrent.BlockingQueue;
@Singleton
public class NoopRequestHandler {
private static final Logger LOG = LoggerFactory.getLogger(NoopRequestHandler.class);
private final BlockingQueue<AppLaunchEvent> launchEventQueue;
@Inject
public NoopRequestHandler(@Named("launchEventQueue") BlockingQueue<AppLaunchEvent> launchEventQueue) {
this.launchEventQueue = launchEventQueue;
}
public void revealApp() {
AppLaunchEvent launchEvent = new RevealRunningEvent();
if (!launchEventQueue.offer(launchEvent)) {
LOG.warn("Could not enqueue application launch event {}.", launchEvent);
}
}
}
@@ -0,0 +1,13 @@
package org.cryptomator.launcher;
import java.nio.file.Path;
import java.util.Collection;
/**
* Requests that the given paths (e.g. {@code .cryptomator} vault files) are opened.
*
* @param pathsToOpen the paths to open
*/
public record OpenFileEvent(Collection<Path> pathsToOpen) implements AppLaunchEvent {
}
@@ -0,0 +1,182 @@
package org.cryptomator.launcher;
import org.cryptomator.cryptofs.VaultConfig;
import org.cryptomator.cryptofs.VaultConfigLoadException;
import org.cryptomator.ui.keyloading.hub.HubConfig;
import org.cryptomator.ui.keyloading.hub.HubKeyLoadingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
/**
* Requests opening a Hub vault from an {@code org.cryptomator://vault/open#vaultConfig=…} deeplink.
* <p>
* The single parameter is the vault's {@code vault.cryptomator}, a compact JWS embedded verbatim, carried in the fragment part.
* <p>
* Notes:
* <ul>
* <li> The config is read <em>unverified</em>, since its signature is keyed on the masterkey, which is only obtainable from Hu later on. </li>
* <li> The deeplink parsing makes a strict validation due to untrusted input</li>
* </ul>
*
* @param vaultConfig the decoded, unverified vault config
* @param vaultId the vault's id within its Hub instance, taken from the config's {@code jti} claim
*/
public record OpenHubVaultEvent(VaultConfig.UnverifiedVaultConfig vaultConfig, UUID vaultId) implements AppLaunchEvent {
private static final Logger LOG = LoggerFactory.getLogger(OpenHubVaultEvent.class);
private static final String SCHEME = "org.cryptomator";
private static final String HOST = "vault";
private static final String PATH = "/open";
private static final String PARAM_VAULT_CONFIG = "vaultConfig";
private static final String HUB_HEADER = "hub";
private static final int MAX_CONFIG_LENGTH = 8192; //real Hub vault config is ~1KB leaving some room for extensions
/**
* Attempts to interpret the given URI as an {@code org.cryptomator://vault/open#vaultConfig=…} deeplink.
*
* @param uri the deeplink URI
* @return the parsed event, or an empty optional if the URI's scheme, host or path do not identify a vault-open
* deeplink
* @throws IllegalArgumentException if the URI identifies a vault-open deeplink, but the config is missing, too
* large, not decodable, or does not describe a Hub vault
*/
public static Optional<OpenHubVaultEvent> tryParse(URI uri) {
if (!SCHEME.equalsIgnoreCase(uri.getScheme()) || !HOST.equalsIgnoreCase(uri.getHost()) || !PATH.equals(uri.getPath())) {
return Optional.empty();
}
var params = parseParams(uri.getRawFragment());
var token = params.get(PARAM_VAULT_CONFIG);
if (token == null || token.isBlank()) {
throw new IllegalArgumentException("Missing required fragment parameter '" + PARAM_VAULT_CONFIG + "'.");
}
var vaultConfig = decode(token);
requireHubVault(vaultConfig);
var vaultId = extractVaultId(vaultConfig);
var leftoverParams = params.keySet().stream().filter(k -> !k.equals(PARAM_VAULT_CONFIG)).toList();
if (!leftoverParams.isEmpty()) {
LOG.debug("Ignoring unknown parameters {}", leftoverParams);
}
return Optional.of(new OpenHubVaultEvent(vaultConfig, vaultId));
}
private static VaultConfig.UnverifiedVaultConfig decode(String token) {
// a compact JWS is ASCII, so its character count is its byte count
if (token.length() > MAX_CONFIG_LENGTH) {
throw new IllegalArgumentException("Fragment parameter '%s' must not exceed %d bytes.".formatted(PARAM_VAULT_CONFIG, MAX_CONFIG_LENGTH));
}
try {
return VaultConfig.decode(token);
} catch (VaultConfigLoadException e) {
throw new IllegalArgumentException("Fragment parameter '" + PARAM_VAULT_CONFIG + "' is not a decodable vault config.", e);
}
}
/**
* Ensures the config describes a Hub vault and that the endpoints the app will talk to are usable.
*/
private static void requireHubVault(VaultConfig.UnverifiedVaultConfig vaultConfig) {
var keyIdScheme = vaultConfig.getKeyId().getScheme();
if (keyIdScheme == null || !keyIdScheme.startsWith(HubKeyLoadingStrategy.SCHEME_PREFIX)) {
throw new IllegalArgumentException("Vault config does not describe a Hub vault, but had key id scheme '" + keyIdScheme + "'.");
}
HubConfig hubConfig;
try {
hubConfig = vaultConfig.getHeader(HUB_HEADER, HubConfig.class);
} catch (RuntimeException e) {
throw new IllegalArgumentException("Vault config contains an unreadable '" + HUB_HEADER + "' header.", e);
}
if (hubConfig == null) {
throw new IllegalArgumentException("Vault config contains no '" + HUB_HEADER + "' header.");
}
URI apiBaseUrl;
try {
apiBaseUrl = hubConfig.getApiBaseUrl();
} catch (RuntimeException e) {
throw new IllegalArgumentException("Vault config declares no usable hub api base url.", e);
}
requireUsableEndpoint("apiBaseUrl", apiBaseUrl);
requireUsableEndpoint("authEndpoint", toUri("authEndpoint", hubConfig.authEndpoint));
}
private static URI toUri(String field, String value) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("Vault config declares no hub " + field + ".");
}
try {
return URI.create(value);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Vault config's hub " + field + " is not a valid url, but was '" + value + "'.", e);
}
}
private static void requireUsableEndpoint(String field, URI uri) {
if (!uri.isAbsolute() || uri.getHost() == null) {
throw new IllegalArgumentException("Vault config's hub " + field + " is not an absolute url with a host, but was '" + uri + "'.");
}
// Whether an http host is acceptable (it is, for local development) is decided by CheckHostTrustController
// Here we only ensure the endpoint is shaped like something that decision can be made on.
var scheme = uri.getScheme();
if (!"https".equalsIgnoreCase(scheme) && !"http".equalsIgnoreCase(scheme)) {
throw new IllegalArgumentException("Vault config's hub " + field + " is neither http nor https, but was '" + uri + "'.");
}
}
/**
* Reads the vault id from the config's {@code jti} claim.
* <p>
* Requiring a UUID matters beyond well-formedness: the id is interpolated into the {@code api/vaults/{vaultId}/…}
* request path, so it must not be able to introduce a path segment. A {@code jti} is an arbitrary string, so parsing
* it as a {@link UUID} and passing that on - rather than the raw claim - is what keeps that guarantee.
* <p>
* Hub writes the same id into the key id's trailing path segment, and the two have always agreed, so a config where
* they differ is forged or broken and is rejected.
*/
private static UUID extractVaultId(VaultConfig.UnverifiedVaultConfig vaultConfig) {
var allegedVaultId = vaultConfig.allegedVaultId();
if (allegedVaultId == null || allegedVaultId.isBlank()) {
throw new IllegalArgumentException("Vault config declares no vault id.");
}
UUID vaultId;
try {
vaultId = UUID.fromString(allegedVaultId);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Vault config's vault id is not a uuid, but was '" + allegedVaultId + "'.", e);
}
var keyId = vaultConfig.getKeyId();
var path = keyId.getPath();
var lastSegment = path == null ? "" : path.substring(path.lastIndexOf('/') + 1);
if (!vaultId.toString().equalsIgnoreCase(lastSegment)) {
throw new IllegalArgumentException("Vault config's vault id '" + vaultId + "' does not match its key id '" + keyId + "'.");
}
return vaultId;
}
private static Map<String, String> parseParams(String rawParams) {
var params = new HashMap<String, String>();
if (rawParams == null || rawParams.isEmpty()) {
return params;
}
for (var pair : rawParams.split("&")) {
var idx = pair.indexOf('=');
if (idx < 0) {
continue;
}
var key = URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8);
var value = URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8);
params.put(key, value);
}
return params;
}
}
@@ -0,0 +1,8 @@
package org.cryptomator.launcher;
/**
* Requests that the already-running application instance reveals itself (brings its main window to the front).
*/
public record RevealRunningEvent() implements AppLaunchEvent {
}
@@ -0,0 +1,58 @@
package org.cryptomator.launcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.function.Function;
@Singleton
public class URIOpenRequestHandler {
private static final Logger LOG = LoggerFactory.getLogger(URIOpenRequestHandler.class);
/**
* The registered deeplink parsers, tried in order. Each returns a matching event, an empty optional if the URI is
* not its concern, or throws {@link IllegalArgumentException} if the URI is its concern but malformed.
*/
private static final List<Function<URI, Optional<? extends AppLaunchEvent>>> DEEPLINK_PARSERS = List.of( //
OpenHubVaultEvent::tryParse //
);
private final BlockingQueue<AppLaunchEvent> launchEventQueue;
@Inject
public URIOpenRequestHandler(@Named("launchEventQueue") BlockingQueue<AppLaunchEvent> launchEventQueue) {
this.launchEventQueue = launchEventQueue;
}
public void handleLaunchArgs(URI uri) {
AppLaunchEvent launchEvent = toLaunchEvent(uri);
if (!launchEventQueue.offer(launchEvent)) {
LOG.warn("Could not enqueue application launch event {}.", launchEvent);
}
}
private AppLaunchEvent toLaunchEvent(URI uri) {
try {
for (var parser : DEEPLINK_PARSERS) {
var event = parser.apply(uri);
if (event.isPresent()) {
return event.get();
}
}
} catch (IllegalArgumentException e) {
LOG.warn("Received malformed deeplink {}: {}. Revealing running app instead.", uri, e.getMessage());
return new RevealRunningEvent();
}
LOG.warn("Received unsupported deeplink {}, revealing running app instead.", uri);
return new RevealRunningEvent();
}
}
@@ -62,9 +62,9 @@ public class Dialogs {
.setOkButtonKey(BUTTON_KEY_CLOSE);
}
public SimpleDialog.Builder prepareHubVaultArchived(Stage window, Vault vault) {
public SimpleDialog.Builder prepareHubVaultArchived(Stage window, String vaultDisplayName) {
return createDialogBuilder().setOwner(window) //
.setTitleKey("unlock.title", vault.getDisplayName()) //
.setTitleKey("unlock.title", vaultDisplayName) //
.setMessageKey("hub.archived.message") //
.setDescriptionKey("hub.archived.description") //
.setIcon(FontAwesome5Icon.BAN)//
@@ -4,14 +4,19 @@ import org.cryptomator.common.vaults.NotAVaultDirectoryException;
import org.cryptomator.common.vaults.Vault;
import org.cryptomator.common.vaults.VaultListManager;
import org.cryptomator.launcher.AppLaunchEvent;
import org.cryptomator.launcher.OpenFileEvent;
import org.cryptomator.launcher.OpenHubVaultEvent;
import org.cryptomator.launcher.RevealRunningEvent;
import org.cryptomator.ui.common.VaultService;
import org.cryptomator.ui.dialogs.Dialogs;
import org.cryptomator.ui.keyloading.hub.HubVaults;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.stage.Stage;
import java.io.IOException;
import java.nio.file.Path;
@@ -31,16 +36,18 @@ class AppLaunchEventHandler {
private final ExecutorService executorService;
private final FxApplicationWindows appWindows;
private final VaultListManager vaultListManager;
private final ObservableList<Vault> vaults;
private final VaultService vaultService;
private final Stage primaryStage;
private final Dialogs dialogs;
@Inject
public AppLaunchEventHandler(@Named("launchEventQueue") BlockingQueue<AppLaunchEvent> launchEventQueue, ExecutorService executorService, FxApplicationWindows appWindows, VaultListManager vaultListManager, VaultService vaultService, @PrimaryStage Stage primaryStage, Dialogs dialogs) {
public AppLaunchEventHandler(@Named("launchEventQueue") BlockingQueue<AppLaunchEvent> launchEventQueue, ExecutorService executorService, FxApplicationWindows appWindows, VaultListManager vaultListManager, ObservableList<Vault> vaults, VaultService vaultService, @PrimaryStage Stage primaryStage, Dialogs dialogs) {
this.launchEventQueue = launchEventQueue;
this.executorService = executorService;
this.appWindows = appWindows;
this.vaultListManager = vaultListManager;
this.vaults = vaults;
this.vaultService = vaultService;
this.primaryStage = primaryStage;
this.dialogs = dialogs;
@@ -63,10 +70,32 @@ class AppLaunchEventHandler {
}
private void handleLaunchEvent(AppLaunchEvent event) {
switch (event.type()) {
case REVEAL_APP -> appWindows.showMainWindow();
case OPEN_FILE -> event.pathsToOpen().forEach(this::openPotentialVault);
default -> LOG.warn("Unsupported event type: {}", event.type());
switch (event) {
case RevealRunningEvent _ -> appWindows.showMainWindow();
case OpenFileEvent openFileEvent -> openFileEvent.pathsToOpen().forEach(this::openPotentialVault);
case OpenHubVaultEvent openHubVaultEvent -> openHubVault(openHubVaultEvent);
}
}
/**
* Whether a hub vault is set up on this machine is a purely local question - hub manages the vault's key, not where
* it lives. Only if it is not set up here do we need to ask hub about it.
*/
private void openHubVault(OpenHubVaultEvent event) {
var existing = HubVaults.findByVaultId(vaults, event.vaultId());
if (existing.isPresent()) {
var vault = existing.get();
Platform.runLater(() -> {
if (vault.isUnlocked()) {
vaultService.reveal(vault);
} else if (vault.isLocked()) {
appWindows.startUnlockWorkflow(vault, null);
}
});
} else {
//TODO: authenticate, ask hub for the vault's details and offer to add it, see docs/hub-vault-open-deeplink-plan.md
LOG.info("Hub vault {} is not set up on this machine.", event.vaultId());
appWindows.showMainWindow();
}
}
@@ -16,6 +16,7 @@ import org.cryptomator.ui.common.FxmlLoaderFactory;
import org.cryptomator.ui.common.FxmlScene;
import org.cryptomator.ui.common.StageFactory;
import org.cryptomator.ui.keyloading.KeyLoadingComponent;
import org.cryptomator.ui.keyloading.KeyLoadingRef;
import org.cryptomator.ui.keyloading.KeyLoadingStrategy;
import javax.inject.Named;
@@ -64,7 +65,11 @@ abstract class HealthCheckModule {
@HealthCheckWindow
@HealthCheckScoped
static KeyLoadingStrategy provideKeyLoadingStrategy(KeyLoadingComponent.Factory compFactory, @HealthCheckWindow Vault vault, @Named("unlockWindow") Stage window ) {
return compFactory.create(vault, window).keyloadingStrategy();
try {
return compFactory.create(KeyLoadingRef.forVault(vault), vault, window).keyloadingStrategy();
} catch (IOException e) {
return KeyLoadingStrategy.failed(e);
}
}
@Provides
@@ -2,6 +2,7 @@ package org.cryptomator.ui.keyloading;
import dagger.BindsInstance;
import dagger.Subcomponent;
import org.cryptomator.common.Nullable;
import org.cryptomator.common.vaults.Vault;
import javafx.stage.Stage;
@@ -16,7 +17,14 @@ public interface KeyLoadingComponent {
@Subcomponent.Factory
interface Factory {
KeyLoadingComponent create(@BindsInstance @KeyLoading Vault vault, @KeyLoading @BindsInstance Stage window);
/**
* @param vaultRef the {@link KeyLoadingRef} containing the info to load the key
* @param vault the local vault, or {@code null} if it is not set up on this machine.
* @param window the window to show the key loading scenes in
*/
KeyLoadingComponent create(@BindsInstance @KeyLoading KeyLoadingRef vaultRef, //
@BindsInstance @KeyLoading @Nullable Vault vault, //
@BindsInstance @KeyLoading Stage window);
}
}
@@ -2,7 +2,6 @@ package org.cryptomator.ui.keyloading;
import dagger.Module;
import dagger.Provides;
import org.cryptomator.common.vaults.Vault;
import org.cryptomator.ui.common.DefaultSceneFactory;
import org.cryptomator.ui.common.FxController;
import org.cryptomator.ui.common.FxmlLoaderFactory;
@@ -10,7 +9,6 @@ import org.cryptomator.ui.keyloading.hub.HubKeyLoadingModule;
import org.cryptomator.ui.keyloading.masterkeyfile.MasterkeyFileLoadingModule;
import javax.inject.Provider;
import java.io.IOException;
import java.util.Map;
import java.util.ResourceBundle;
@@ -27,14 +25,10 @@ abstract class KeyLoadingModule {
@Provides
@KeyLoading
@KeyLoadingScoped
static KeyLoadingStrategy provideKeyLoadingStrategy(@KeyLoading Vault vault, Map<String, Provider<KeyLoadingStrategy>> strategies) {
try {
String scheme = vault.getVaultConfigCache().get().getKeyId().getScheme();
var fallback = KeyLoadingStrategy.failed(new IllegalArgumentException("Unsupported key id " + scheme));
return strategies.getOrDefault(scheme, () -> fallback).get();
} catch (IOException e) {
return KeyLoadingStrategy.failed(e);
}
static KeyLoadingStrategy provideKeyLoadingStrategy(@KeyLoading KeyLoadingRef vaultRef, Map<String, Provider<KeyLoadingStrategy>> strategies) {
String scheme = vaultRef.keyId().getScheme();
var fallback = KeyLoadingStrategy.failed(new IllegalArgumentException("Unsupported key id " + scheme));
return strategies.getOrDefault(scheme, () -> fallback).get();
}
}
@@ -0,0 +1,50 @@
package org.cryptomator.ui.keyloading;
import org.cryptomator.common.vaults.Vault;
import org.cryptomator.cryptofs.VaultConfig;
import java.io.IOException;
import java.net.URI;
/**
* Identifies the vault a key is being loaded for, independently of whether that vault exists on this machine.
* <p>
* Key loading needs the (unverified) vault config selecting the strategy and addresses
* the vault within the strategy, and the display name titles the windows.
* <p>
* The config is <em>unverified</em>: its signature is keyed on the masterkey, which is exactly what key loading is
* about to obtain.
*
* @param vaultConfig the vault's unverified config
* @param displayName the vault's name, as shown to the user
*/
public record KeyLoadingRef(VaultConfig.UnverifiedVaultConfig vaultConfig, String displayName) {
/**
* Describes a vault that is already set up on this machine.
*
* @param vault the vault to load a key for
* @throws IOException if the vault's config cannot be read
*/
public static KeyLoadingRef forVault(Vault vault) throws IOException {
return new KeyLoadingRef(vault.getVaultConfigCache().get(), vault.getDisplayName());
}
/**
* The key id, whose scheme selects the key loading strategy.
*/
public URI keyId() {
return vaultConfig.getKeyId();
}
/**
* The vault's id, i.e. how the vault is addressed within its Hub instance.
* <p>
* Read from the config's {@code jti} claim, which is the authoritative source: the key id carries the same id in its
* trailing path segment, but only its <em>scheme</em> is a source of truth here.
*/
public String vaultId() {
return vaultConfig.allegedVaultId();
}
}
@@ -7,7 +7,6 @@ import dagger.Provides;
import dagger.multibindings.IntoMap;
import dagger.multibindings.StringKey;
import org.cryptomator.common.settings.DeviceKey;
import org.cryptomator.common.vaults.Vault;
import org.cryptomator.cryptolib.common.MessageDigestSupplier;
import org.cryptomator.ui.common.FxController;
import org.cryptomator.ui.common.FxControllerKey;
@@ -15,13 +14,12 @@ import org.cryptomator.ui.common.FxmlFile;
import org.cryptomator.ui.common.FxmlLoaderFactory;
import org.cryptomator.ui.common.FxmlScene;
import org.cryptomator.ui.keyloading.KeyLoading;
import org.cryptomator.ui.keyloading.KeyLoadingRef;
import org.cryptomator.ui.keyloading.KeyLoadingScoped;
import org.cryptomator.ui.keyloading.KeyLoadingStrategy;
import javax.inject.Named;
import javafx.scene.Scene;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;
@@ -32,19 +30,15 @@ public abstract class HubKeyLoadingModule {
@Provides
@KeyLoadingScoped
static HubConfig provideHubConfig(@KeyLoading Vault vault) {
try {
return vault.getVaultConfigCache().get().getHeader("hub", HubConfig.class);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
static HubConfig provideHubConfig(@KeyLoading KeyLoadingRef vaultRef) {
return vaultRef.vaultConfig().getHeader("hub", HubConfig.class);
}
@Provides
@KeyLoadingScoped
@Named("windowTitle")
static String provideWindowTitle(@KeyLoading Vault vault, ResourceBundle resourceBundle) {
return String.format(resourceBundle.getString("unlock.title"), vault.getDisplayName());
static String provideWindowTitle(@KeyLoading KeyLoadingRef vaultRef, ResourceBundle resourceBundle) {
return String.format(resourceBundle.getString("unlock.title"), vaultRef.displayName());
}
@@ -0,0 +1,59 @@
package org.cryptomator.ui.keyloading.hub;
import org.cryptomator.common.vaults.Vault;
import org.cryptomator.cryptofs.VaultConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Collection;
import java.util.Optional;
import java.util.UUID;
/**
* Locates Hub vaults among the vaults set up on this machine.
* <p>
* Hub manages a vault's key, not where it lives or how it is laid out, so the local vault list is the only place that
* can answer whether a given Hub vault is already set up here.
*/
public final class HubVaults {
private static final Logger LOG = LoggerFactory.getLogger(HubVaults.class);
private HubVaults() {
}
/**
* Finds the Hub vault with the given id.
* <p>
* A vault whose config cannot be read - e.g. because it sits on storage that is currently unavailable - is skipped
* rather than failing the lookup: one unreachable vault must not prevent finding a different one.
*
* @param vaults the vaults set up on this machine
* @param hubVaultId the vault's id within its Hub instance
* @return the local vault, or empty if none of them is that Hub vault
*/
public static Optional<Vault> findByVaultId(Collection<Vault> vaults, UUID hubVaultId) {
return vaults.stream() //
.filter(vault -> hasVaultId(vault, hubVaultId)) //
.findAny();
}
private static boolean hasVaultId(Vault vault, UUID hubVaultId) {
try {
return hasVaultId(vault.getVaultConfigCache().get(), hubVaultId);
} catch (IOException e) {
LOG.debug("Skipping vault {} while looking for hub vault {}, its config is not readable.", vault.getPath(), hubVaultId);
return false;
}
}
private static boolean hasVaultId(VaultConfig.UnverifiedVaultConfig config, UUID hubVaultId) {
var keyIdScheme = config.getKeyId().getScheme();
if (keyIdScheme == null || !keyIdScheme.startsWith(HubKeyLoadingStrategy.SCHEME_PREFIX)) {
return false; //not a hub vault, so it cannot be the one we are looking for
}
return hubVaultId.toString().equalsIgnoreCase(config.allegedVaultId());
}
}
@@ -7,12 +7,12 @@ import com.google.common.base.Preconditions;
import com.nimbusds.jose.JWEObject;
import dagger.Lazy;
import org.cryptomator.common.Constants;
import org.cryptomator.common.vaults.Vault;
import org.cryptomator.ui.common.FxController;
import org.cryptomator.ui.common.FxmlFile;
import org.cryptomator.ui.common.FxmlScene;
import org.cryptomator.ui.dialogs.Dialogs;
import org.cryptomator.ui.keyloading.KeyLoading;
import org.cryptomator.ui.keyloading.KeyLoadingRef;
import org.cryptomator.ui.keyloading.KeyLoadingScoped;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -60,10 +60,10 @@ public class ReceiveKeyController implements FxController {
private final Lazy<Scene> invalidLicenseScene;
private final HttpClient httpClient;
private final Dialogs dialogs;
private final Vault vault;
private final KeyLoadingRef vaultRef;
@Inject
public ReceiveKeyController(@KeyLoading Vault vault, //
public ReceiveKeyController(@KeyLoading KeyLoadingRef vaultRef, //
ExecutorService executor, //
@KeyLoading Stage window, //
HubConfig hubConfig, //
@@ -79,7 +79,7 @@ public class ReceiveKeyController implements FxController {
Dialogs dialogs) {
this.window = window;
this.hubConfig = hubConfig;
this.vaultId = extractVaultId(vault.getVaultConfigCache().getUnchecked().getKeyId()); // TODO: access vault config's JTI directly (requires changes in cryptofs)
this.vaultId = vaultRef.vaultId();
this.deviceId = deviceId;
this.bearerToken = Objects.requireNonNull(tokenRef.get());
this.fsOwnerId = fsOwnerId;
@@ -92,7 +92,7 @@ public class ReceiveKeyController implements FxController {
this.window.addEventHandler(WindowEvent.WINDOW_HIDING, this::windowClosed);
this.httpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).executor(executor).build();
this.dialogs = dialogs;
this.vault = vault;
this.vaultRef = vaultRef;
}
@FXML
@@ -313,7 +313,7 @@ public class ReceiveKeyController implements FxController {
private void accessGoneVaultArchived() {
window.close();
dialogs.prepareHubVaultArchived((Stage)window.getOwner(), vault).build().showAndWait();
dialogs.prepareHubVaultArchived((Stage)window.getOwner(), vaultRef.displayName()).build().showAndWait();
}
private void accountInitializationRequired() {
@@ -343,12 +343,6 @@ public class ReceiveKeyController implements FxController {
}
}
private static String extractVaultId(URI vaultKeyUri) {
assert vaultKeyUri.getScheme().startsWith(HubKeyLoadingStrategy.SCHEME_PREFIX);
var path = vaultKeyUri.getPath();
return path.substring(path.lastIndexOf('/') + 1);
}
@JsonIgnoreProperties(ignoreUnknown = true)
private record UserDto(@JsonProperty(value = "name", required = true) String name) {}
@@ -1,5 +1,6 @@
package org.cryptomator.ui.keyloading.masterkeyfile;
import org.cryptomator.common.Nullable;
import org.cryptomator.common.recovery.RecoveryActionType;
import org.cryptomator.common.vaults.Vault;
import org.cryptomator.ui.common.FxController;
@@ -18,6 +19,7 @@ import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import java.io.File;
import java.nio.file.Path;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;
@@ -41,12 +43,12 @@ public class ChooseMasterkeyFileController implements FxController {
@Inject
public ChooseMasterkeyFileController(@KeyLoading Stage window, //
@KeyLoading Vault vault, //
@KeyLoading @Nullable Vault vault, //
CompletableFuture<Path> result, //
RecoveryKeyComponent.Factory recoveryKeyWindow, //
ResourceBundle resourceBundle) {
this.window = window;
this.vault = vault;
this.vault = Objects.requireNonNull(vault, MasterkeyFileLoadingModule.NO_LOCAL_VAULT);
this.result = result;
this.recoveryKeyWindow = recoveryKeyWindow;
this.resourceBundle = resourceBundle;
@@ -5,6 +5,7 @@ import dagger.Module;
import dagger.Provides;
import dagger.multibindings.IntoMap;
import dagger.multibindings.StringKey;
import org.cryptomator.common.Nullable;
import org.cryptomator.common.keychain.KeychainManager;
import org.cryptomator.common.vaults.Vault;
import org.cryptomator.integrations.keychain.KeychainAccessException;
@@ -15,20 +16,27 @@ import org.cryptomator.ui.keyloading.KeyLoadingStrategy;
import org.slf4j.LoggerFactory;
import javax.inject.Named;
import java.util.Objects;
import java.util.Optional;
@Module(subcomponents = {ForgetPasswordComponent.class, PassphraseEntryComponent.class, ChooseMasterkeyFileComponent.class})
public interface MasterkeyFileLoadingModule {
/**
* Key loading may run for a yet-to-setup vault (i.e. deeplink with only a config) - Masterkey loading requires in the current implementation
* an already setup vault.
*/
String NO_LOCAL_VAULT = "masterkey file loading requires a local vault";
@Provides
@Named("savedPassword")
@KeyLoadingScoped
static Optional<char[]> provideStoredPassword(KeychainManager keychain, @KeyLoading Vault vault) {
static Optional<char[]> provideStoredPassword(KeychainManager keychain, @KeyLoading @Nullable Vault vault) {
if (!keychain.isSupported() || keychain.isLocked()) {
return Optional.empty();
} else {
try {
return Optional.ofNullable(keychain.loadPassphrase(vault.getId()));
return Optional.ofNullable(keychain.loadPassphrase(Objects.requireNonNull(vault, NO_LOCAL_VAULT).getId()));
} catch (KeychainAccessException e) {
LoggerFactory.getLogger(MasterkeyFileLoadingModule.class).error("Failed to load entry from system keychain.", e);
return Optional.empty();
@@ -2,6 +2,7 @@ package org.cryptomator.ui.keyloading.masterkeyfile;
import com.google.common.base.Preconditions;
import org.cryptomator.common.Constants;
import org.cryptomator.common.Nullable;
import org.cryptomator.common.Passphrase;
import org.cryptomator.common.keychain.KeychainManager;
import org.cryptomator.common.vaults.Vault;
@@ -25,6 +26,7 @@ import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.concurrent.CancellationException;
@@ -48,8 +50,8 @@ public class MasterkeyFileLoadingStrategy implements KeyLoadingStrategy {
private boolean wrongPassphrase;
@Inject
public MasterkeyFileLoadingStrategy(@KeyLoading Vault vault, MasterkeyFileAccess masterkeyFileAccess, @KeyLoading Stage window, @Named("savedPassword") Optional<char[]> savedPassphrase, PassphraseEntryComponent.Builder passphraseEntry, ChooseMasterkeyFileComponent.Builder masterkeyFileChoice, KeychainManager keychain, ResourceBundle resourceBundle) {
this.vault = vault;
public MasterkeyFileLoadingStrategy(@KeyLoading @Nullable Vault vault, MasterkeyFileAccess masterkeyFileAccess, @KeyLoading Stage window, @Named("savedPassword") Optional<char[]> savedPassphrase, PassphraseEntryComponent.Builder passphraseEntry, ChooseMasterkeyFileComponent.Builder masterkeyFileChoice, KeychainManager keychain, ResourceBundle resourceBundle) {
this.vault = Objects.requireNonNull(vault, MasterkeyFileLoadingModule.NO_LOCAL_VAULT);
this.masterkeyFileAccess = masterkeyFileAccess;
this.window = window;
this.passphraseEntry = passphraseEntry;
@@ -35,6 +35,7 @@ import javafx.scene.transform.Translate;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
@@ -66,9 +67,9 @@ public class PassphraseEntryController implements FxController {
public Animation unlockAnimation;
@Inject
public PassphraseEntryController(@KeyLoading Stage window, @KeyLoading Vault vault, CompletableFuture<PassphraseEntryResult> result, @Nullable @Named("savedPassword") Passphrase savedPassword, ForgetPasswordComponent.Builder forgetPassword, KeychainManager keychain, ExecutorService backgroundExecutorService) {
public PassphraseEntryController(@KeyLoading Stage window, @KeyLoading @Nullable Vault vault, CompletableFuture<PassphraseEntryResult> result, @Nullable @Named("savedPassword") Passphrase savedPassword, ForgetPasswordComponent.Builder forgetPassword, KeychainManager keychain, ExecutorService backgroundExecutorService) {
this.window = window;
this.vault = vault;
this.vault = Objects.requireNonNull(vault, MasterkeyFileLoadingModule.NO_LOCAL_VAULT);
this.result = result;
this.savedPassword = savedPassword;
this.forgetPassword = forgetPassword;
@@ -14,6 +14,7 @@ import org.cryptomator.ui.common.FxmlLoaderFactory;
import org.cryptomator.ui.common.FxmlScene;
import org.cryptomator.ui.common.StageFactory;
import org.cryptomator.ui.keyloading.KeyLoadingComponent;
import org.cryptomator.ui.keyloading.KeyLoadingRef;
import org.cryptomator.ui.keyloading.KeyLoadingStrategy;
import org.cryptomator.ui.recoverykey.RecoveryKeyComponent;
import org.jetbrains.annotations.Nullable;
@@ -25,6 +26,7 @@ import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.Scene;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.Map;
import java.util.ResourceBundle;
@@ -58,7 +60,11 @@ abstract class UnlockModule {
@UnlockWindow
@UnlockScoped
static KeyLoadingStrategy provideKeyLoadingStrategy(KeyLoadingComponent.Factory compFactory, @UnlockWindow Vault vault, @UnlockWindow Stage window) {
return compFactory.create(vault, window).keyloadingStrategy();
try {
return compFactory.create(KeyLoadingRef.forVault(vault), vault, window).keyloadingStrategy();
} catch (IOException e) {
return KeyLoadingStrategy.failed(e);
}
}
@Provides
@@ -40,8 +40,7 @@ public class FileOpenRequestHandlerTest {
public void testOpenArgsWithCorrectPaths() {
inTest.handleLaunchArgs(List.of("foo", "bar"));
AppLaunchEvent evt = queue.poll();
Assertions.assertNotNull(evt);
OpenFileEvent evt = Assertions.assertInstanceOf(OpenFileEvent.class, queue.poll());
Collection<Path> paths = evt.pathsToOpen();
MatcherAssert.assertThat(paths, CoreMatchers.hasItems(Paths.get("foo"), Paths.get("bar")));
}
@@ -60,7 +59,7 @@ public class FileOpenRequestHandlerTest {
@Test
@DisplayName("./cryptomator.exe foo (with full event queue)")
public void testOpenArgsWithFullQueue() {
queue.add(new AppLaunchEvent(AppLaunchEvent.EventType.OPEN_FILE, Collections.emptyList()));
queue.add(new OpenFileEvent(Collections.emptyList()));
Assumptions.assumeTrue(queue.remainingCapacity() == 0);
inTest.handleLaunchArgs(List.of("foo"));
@@ -0,0 +1,98 @@
package org.cryptomator.launcher;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.net.URI;
import java.util.List;
public class LaunchArgsParserTest {
private FileOpenRequestHandler fileOpenRequestHandler;
private URIOpenRequestHandler uriOpenRequestHandler;
private NoopRequestHandler noopRequestHandler;
private LaunchArgsParser inTest;
@BeforeEach
public void setup() {
fileOpenRequestHandler = Mockito.mock(FileOpenRequestHandler.class);
uriOpenRequestHandler = Mockito.mock(URIOpenRequestHandler.class);
noopRequestHandler = Mockito.mock(NoopRequestHandler.class);
inTest = new LaunchArgsParser(fileOpenRequestHandler, uriOpenRequestHandler, noopRequestHandler);
}
@Test
@DisplayName("only file paths are forwarded to the FileOpenRequestHandler")
public void testOnlyPaths() {
inTest.process(List.of("foo", "bar"));
Mockito.verify(fileOpenRequestHandler).handleLaunchArgs(List.of("foo", "bar"));
Mockito.verifyNoInteractions(uriOpenRequestHandler);
Mockito.verifyNoInteractions(noopRequestHandler);
}
@Test
@DisplayName("empty args are forwarded to the NoopRequestHandler")
public void testEmptyArgs() {
inTest.process(List.of());
Mockito.verify(noopRequestHandler).revealApp();
Mockito.verifyNoInteractions(uriOpenRequestHandler, fileOpenRequestHandler);
}
@Test
@DisplayName("a Windows path is not mistaken for a URI")
public void testWindowsPathIsNotAUri() {
inTest.process(List.of("C:\\Users\\foo\\vault.cryptomator"));
Mockito.verify(fileOpenRequestHandler).handleLaunchArgs(List.of("C:\\Users\\foo\\vault.cryptomator"));
Mockito.verifyNoInteractions(uriOpenRequestHandler, noopRequestHandler);
}
@Test
@DisplayName("a single cryptomator:// URI is forwarded to the URIOpenRequestHandler")
public void testSingleUri() {
inTest.process(List.of("cryptomator://vault/foo"));
Mockito.verify(uriOpenRequestHandler).handleLaunchArgs(URI.create("cryptomator://vault/foo"));
Mockito.verifyNoInteractions(fileOpenRequestHandler, noopRequestHandler);
}
@Test
@DisplayName("a file:// URI is converted to a path and forwarded to the FileOpenRequestHandler")
public void testFileUriIsTreatedAsPath() {
inTest.process(List.of("file:///tmp/vault.cryptomator"));
var captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(fileOpenRequestHandler).handleLaunchArgs(captor.capture());
Mockito.verifyNoInteractions(uriOpenRequestHandler, noopRequestHandler);
Assertions.assertEquals(1, captor.getValue().size());
Assertions.assertFalse(captor.getValue().getFirst().toString().startsWith("file:"));
}
@Test
@DisplayName("mixing a URI with a file path fails")
public void testMixedUriAndPathFails() {
Assertions.assertThrows(IllegalArgumentException.class, () -> inTest.process(List.of("cryptomator://vault/foo", "bar")));
Mockito.verifyNoInteractions(fileOpenRequestHandler, uriOpenRequestHandler, noopRequestHandler);
}
@Test
@DisplayName("more than one URI fails")
public void testMultipleUrisFail() {
Assertions.assertThrows(IllegalArgumentException.class, () -> inTest.process(List.of("cryptomator://vault/foo", "cryptomator://vault/bar")));
Mockito.verifyNoInteractions(fileOpenRequestHandler, uriOpenRequestHandler, noopRequestHandler);
}
@Test
@DisplayName("a URI that is not the first parameter fails")
public void testUriNotFirstFails() {
Assertions.assertThrows(IllegalArgumentException.class, () -> inTest.process(List.of("foo", "cryptomator://vault/bar")));
Mockito.verifyNoInteractions(fileOpenRequestHandler, uriOpenRequestHandler, noopRequestHandler);
}
}
@@ -0,0 +1,220 @@
package org.cryptomator.launcher;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;
import java.util.UUID;
public class OpenHubVaultEventTest {
private static final String VAULT_ID = "d3a1f0b2-7c4e-4a1d-9f3b-2e5c6a7b8c9d";
private static final String KEY_ID = "hub+https://hub.example.com/api/vaults/" + VAULT_ID;
private static final String TOKEN = hubVaultConfig(KEY_ID);
@Test
@DisplayName("a valid vault/open deeplink is parsed")
public void testValid() {
var inTest = OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://vault/open#vaultConfig=" + TOKEN)).orElseThrow();
Assertions.assertEquals(UUID.fromString(VAULT_ID), inTest.vaultId());
Assertions.assertEquals(URI.create(KEY_ID), inTest.vaultConfig().getKeyId());
}
@Test
@DisplayName("parameters in the query instead of the fragment are not accepted")
public void testQueryParamsRejected() {
var uri = URI.create("org.cryptomator://vault/open?vaultConfig=" + TOKEN);
Assertions.assertThrows(IllegalArgumentException.class, () -> OpenHubVaultEvent.tryParse(uri));
}
@Test
@DisplayName("an encoded separator inside a value cannot forge another parameter")
public void testNoParameterInjectionViaEncodedSeparator() {
// '%26' must stay part of the first value; decoding the fragment before splitting would turn it into a real
// separator and smuggle in a 'vaultConfig' the link never carried - hence getRawFragment(), decoding per value.
var uri = URI.create("org.cryptomator://vault/open#other=a%26vaultConfig=" + TOKEN);
Assertions.assertThrows(IllegalArgumentException.class, () -> OpenHubVaultEvent.tryParse(uri));
}
@Test
@DisplayName("a config exceeding the size limit is rejected")
public void testExceedsSizeLimit() {
var oversized = "a".repeat(8193);
Assertions.assertThrows(IllegalArgumentException.class, //
() -> OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://vault/open#vaultConfig=" + oversized)));
}
@Test
@DisplayName("a config that is not a decodable token is rejected")
public void testNotAToken() {
Assertions.assertThrows(IllegalArgumentException.class, //
() -> OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://vault/open#vaultConfig=not-a-jwt")));
}
@Test
@DisplayName("a config without a hub key id is rejected")
public void testNotAHubVault() {
var token = hubVaultConfig("masterkeyfile:masterkey.cryptomator");
Assertions.assertThrows(IllegalArgumentException.class, //
() -> OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://vault/open#vaultConfig=" + token)));
}
@Test
@DisplayName("a config without a hub header is rejected")
public void testNoHubHeader() {
var token = vaultConfig(KEY_ID, VAULT_ID, null);
Assertions.assertThrows(IllegalArgumentException.class, //
() -> OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://vault/open#vaultConfig=" + token)));
}
@ParameterizedTest
@DisplayName("a vault id that is not a uuid is rejected")
@ValueSource(strings = { //
"not-a-uuid", //
"", // absent
"../../evil" // must never reach the api/vaults/{vaultId}/... request path
})
public void testInvalidVaultId(String vaultId) {
var token = vaultConfig(KEY_ID, vaultId, hubHeader("https://hub.example.com/api", "https://login.example.com/auth"));
Assertions.assertThrows(IllegalArgumentException.class, //
() -> OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://vault/open#vaultConfig=" + token)));
}
@Test
@DisplayName("a vault id disagreeing with the key id is rejected")
public void testVaultIdMismatch() {
// Hub writes the same id into both, so a config where they differ is forged or broken
var token = vaultConfig(KEY_ID, "11111111-2222-3333-4444-555555555555", //
hubHeader("https://hub.example.com/api", "https://login.example.com/auth"));
Assertions.assertThrows(IllegalArgumentException.class, //
() -> OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://vault/open#vaultConfig=" + token)));
}
@ParameterizedTest
@DisplayName("an unusable hub endpoint is rejected")
@ValueSource(strings = { //
"ftp://hub.example.com/api", // neither http nor https
"/api", // not absolute
"https:///api" // no host
})
public void testUnusableApiBaseUrl(String apiBaseUrl) {
var token = vaultConfig(KEY_ID, VAULT_ID, hubHeader(apiBaseUrl, "https://login.example.com/auth"));
Assertions.assertThrows(IllegalArgumentException.class, //
() -> OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://vault/open#vaultConfig=" + token)));
}
@Test
@DisplayName("an unusable auth endpoint is rejected")
public void testUnusableAuthEndpoint() {
var token = vaultConfig(KEY_ID, VAULT_ID, hubHeader("https://hub.example.com/api", "not a url"));
Assertions.assertThrows(IllegalArgumentException.class, //
() -> OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://vault/open#vaultConfig=" + token)));
}
@Test
@DisplayName("an http endpoint is accepted here, host trust decides later")
public void testHttpEndpointAccepted() {
var token = vaultConfig(KEY_ID, VAULT_ID, hubHeader("http://localhost:8080/api", "http://localhost:8080/auth"));
Assertions.assertTrue(OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://vault/open#vaultConfig=" + token)).isPresent());
}
@Test
@DisplayName("a non-cryptomator scheme yields empty")
public void testWrongScheme() {
Assertions.assertEquals(Optional.empty(), OpenHubVaultEvent.tryParse(URI.create("foobar://vault/open#vaultConfig=" + TOKEN)));
}
@Test
@DisplayName("the bare cryptomator scheme is no longer recognized")
public void testLegacyScheme() {
Assertions.assertEquals(Optional.empty(), OpenHubVaultEvent.tryParse(URI.create("cryptomator://vault/open#vaultConfig=" + TOKEN)));
}
@Test
@DisplayName("an unknown host yields empty")
public void testWrongHost() {
Assertions.assertEquals(Optional.empty(), OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://foo/open#vaultConfig=" + TOKEN)));
}
@Test
@DisplayName("an unknown path yields empty")
public void testWrongPath() {
Assertions.assertEquals(Optional.empty(), OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://vault/create#vaultConfig=" + TOKEN)));
}
@Test
@DisplayName("a matching host is recognized case-insensitively")
public void testHostCaseInsensitive() {
Assertions.assertTrue(OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://VAULT/open#vaultConfig=" + TOKEN)).isPresent());
}
@Test
@DisplayName("a missing config fails")
public void testMissingConfig() {
Assertions.assertThrows(IllegalArgumentException.class, () -> OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://vault/open")));
}
@Test
@DisplayName("a blank config fails")
public void testBlankConfig() {
Assertions.assertThrows(IllegalArgumentException.class, () -> OpenHubVaultEvent.tryParse(URI.create("org.cryptomator://vault/open#vaultConfig=")));
}
private static String hubHeader(String apiBaseUrl, String authEndpoint) {
return """
,
"hub": {
"clientId":"cryptomator",\
"authEndpoint":"%s",\
"tokenEndpoint":"https://login.example.com/token",\
"authSuccessUrl":"https://hub.example.com/app/unlock-success",\
"authErrorUrl":"https://hub.example.com/app/unlock-error",\
"apiBaseUrl":"%s"
}""".formatted(authEndpoint, apiBaseUrl);
}
private static String hubVaultConfig(String keyId) {
return vaultConfig(keyId, VAULT_ID, hubHeader("https://hub.example.com/api", "https://login.example.com/auth"));
}
/**
* Builds a vault config token. Its signature is keyed on the masterkey, which the deeplink never carries, so a dummy
* signature is exactly what the parser operates on.
*/
private static String vaultConfig(String keyId, String vaultId, String extraHeaderFields) {
var header = """
{ "kid":"%s",\
"typ":"JWT",\
"alg":"HS256"\
%s
}""".formatted(keyId, extraHeaderFields == null ? "" : extraHeaderFields);
var payload = """
{ "jti":"%s",\
"format":8,\
"cipherCombo":"SIV_GCM",\
"shorteningThreshold":220\
}""".formatted(vaultId);
var encoder = Base64.getUrlEncoder().withoutPadding();
return encoder.encodeToString(header.getBytes(StandardCharsets.UTF_8)) //
+ "." + encoder.encodeToString(payload.getBytes(StandardCharsets.UTF_8)) //
+ "." + encoder.encodeToString("signature".getBytes(StandardCharsets.UTF_8));
}
}
@@ -0,0 +1,56 @@
package org.cryptomator.ui.fxapp;
import org.cryptomator.common.vaults.VaultListManager;
import org.cryptomator.launcher.AppLaunchEvent;
import org.cryptomator.launcher.RevealRunningEvent;
import org.cryptomator.ui.common.VaultService;
import org.cryptomator.ui.dialogs.Dialogs;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import javafx.collections.FXCollections;
import javafx.stage.Stage;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
public class AppLaunchEventHandlerTest {
private BlockingQueue<AppLaunchEvent> queue;
private ExecutorService executor;
private FxApplicationWindows appWindows;
private AppLaunchEventHandler handler;
@BeforeEach
public void setup() {
queue = new LinkedBlockingQueue<>();
executor = Executors.newSingleThreadExecutor();
appWindows = mock(FxApplicationWindows.class);
handler = new AppLaunchEventHandler(queue, executor, appWindows, mock(VaultListManager.class), FXCollections.observableArrayList(), mock(VaultService.class), mock(Stage.class), mock(Dialogs.class));
}
@AfterEach
public void teardown() {
executor.shutdownNow();
}
// TODO: Add test for OpenHubVaultEvent once the event opens the hub vault flow for real.
@Test
@DisplayName("a RevealRunningEvent reveals the main window")
public void testRevealRunningEventShowsMainWindow() {
queue.add(new RevealRunningEvent());
handler.startHandlingLaunchEvents();
verify(appWindows, timeout(2000)).showMainWindow();
}
}
@@ -0,0 +1,92 @@
package org.cryptomator.ui.keyloading.hub;
import org.cryptomator.common.vaults.Vault;
import org.cryptomator.common.vaults.VaultConfigCache;
import org.cryptomator.cryptofs.VaultConfig.UnverifiedVaultConfig;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class HubVaultsTest {
private static final UUID VAULT_ID = UUID.fromString("d3a1f0b2-7c4e-4a1d-9f3b-2e5c6a7b8c9d");
private static final UUID OTHER_VAULT_ID = UUID.fromString("11111111-2222-3333-4444-555555555555");
@Test
@DisplayName("the hub vault with the requested id is found")
public void testFindsMatchingVault() throws IOException {
var wanted = hubVault(VAULT_ID);
var vaults = List.of(hubVault(OTHER_VAULT_ID), wanted);
Assertions.assertEquals(Optional.of(wanted), HubVaults.findByVaultId(vaults, VAULT_ID));
}
@Test
@DisplayName("no vault with the requested id yields empty")
public void testNoMatch() throws IOException {
var vaults = List.of(hubVault(OTHER_VAULT_ID));
Assertions.assertEquals(Optional.empty(), HubVaults.findByVaultId(vaults, VAULT_ID));
}
@Test
@DisplayName("a password vault never matches, even carrying the same id")
public void testIgnoresPasswordVault() throws IOException {
var vaults = List.of(vault("masterkeyfile:masterkey.cryptomator", VAULT_ID));
Assertions.assertEquals(Optional.empty(), HubVaults.findByVaultId(vaults, VAULT_ID));
}
@Test
@DisplayName("a vault whose config cannot be read is skipped, not fatal")
public void testSkipsUnreadableVault() throws IOException {
// e.g. a vault on a network drive that is currently offline - it must not hide a vault further down the list
var wanted = hubVault(VAULT_ID);
var vaults = List.of(unreadableVault(), wanted);
Assertions.assertEquals(Optional.of(wanted), HubVaults.findByVaultId(vaults, VAULT_ID));
}
// setup/mock provider
private static Vault hubVault(UUID vaultId) throws IOException {
return vault("hub+https://hub.example.com/api/vaults/" + vaultId, vaultId);
}
private static Vault vault(String keyId, UUID vaultId) throws IOException {
var configCache = mock(VaultConfigCache.class);
var config = mockConfig(keyId, vaultId);
when(configCache.get()).thenReturn(config);
return vaultWith(configCache);
}
private static Vault unreadableVault() throws IOException {
var configCache = mock(VaultConfigCache.class);
when(configCache.get()).thenThrow(new IOException("vault directory unavailable"));
return vaultWith(configCache);
}
private static Vault vaultWith(VaultConfigCache configCache) {
var vault = mock(Vault.class);
when(vault.getVaultConfigCache()).thenReturn(configCache);
return vault;
}
private static UnverifiedVaultConfig mockConfig(String keyId, UUID vaultId) {
var mock = mock(UnverifiedVaultConfig.class);
when(mock.getKeyId()).thenReturn(URI.create(keyId));
when(mock.allegedVaultId()).thenReturn(vaultId.toString());
return mock;
}
}