Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored User Keys #282

Merged
merged 18 commits into from
Jun 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import org.cryptomator.hub.entities.LegacyAccessToken;
import org.cryptomator.hub.entities.LegacyDevice;
import org.cryptomator.hub.entities.User;
import org.cryptomator.hub.entities.events.DeviceRemovedEvent;
import org.cryptomator.hub.entities.events.EventLogger;
import org.cryptomator.hub.validation.NoHtmlOrScriptChars;
import org.cryptomator.hub.validation.OnlyBase64Chars;
Expand Down Expand Up @@ -102,7 +101,7 @@ public Response createOrUpdate(@Valid @NotNull DeviceDto dto, @PathParam("device
}
device.setName(dto.name);
device.setPublickey(dto.publicKey);
device.setUserPrivateKey(dto.userPrivateKey);
device.setUserPrivateKeys(dto.userPrivateKeys);

try {
deviceRepo.persistAndFlush(device);
Expand Down Expand Up @@ -173,12 +172,12 @@ public record DeviceDto(@JsonProperty("id") @ValidId String id,
@JsonProperty("name") @NoHtmlOrScriptChars @NotBlank String name,
@JsonProperty("type") Device.Type type,
@JsonProperty("publicKey") @NotNull @OnlyBase64Chars String publicKey,
@JsonProperty("userPrivateKey") @NotNull @ValidJWE String userPrivateKey,
@JsonProperty("userPrivateKey") @NotNull @ValidJWE String userPrivateKeys, // singular name for history reasons (don't break client compatibility)
@JsonProperty("owner") @ValidId String ownerId,
@JsonProperty("creationTime") Instant creationTime) {

public static DeviceDto fromEntity(Device entity) {
return new DeviceDto(entity.getId(), entity.getName(), entity.getType(), entity.getPublickey(), entity.getUserPrivateKey(), entity.getOwner().getId(), entity.getCreationTime().truncatedTo(ChronoUnit.MILLIS));
return new DeviceDto(entity.getId(), entity.getName(), entity.getType(), entity.getPublickey(), entity.getUserPrivateKeys(), entity.getOwner().getId(), entity.getCreationTime().truncatedTo(ChronoUnit.MILLIS));
}

}
Expand Down
26 changes: 18 additions & 8 deletions backend/src/main/java/org/cryptomator/hub/api/UserDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,34 @@ public final class UserDto extends AuthorityDto {
public final String email;
@JsonProperty("devices")
public final Set<DeviceResource.DeviceDto> devices;
@JsonProperty("publicKey")
public final String publicKey;
@JsonProperty("privateKey")
public final String privateKey;
@JsonProperty("ecdhPublicKey")
public final String ecdhPublicKey;
@JsonProperty("ecdsaPublicKey")
public final String ecdsaPublicKey;
@JsonProperty("privateKey") // singular name for history reasons (don't break client compatibility)
public final String privateKeys;
@JsonProperty("setupCode")
public final String setupCode;

@Deprecated
@JsonProperty("publicKey")
public final String legacyEcdhPublicKey;

UserDto(@JsonProperty("id") String id, @JsonProperty("name") String name, @JsonProperty("pictureUrl") String pictureUrl, @JsonProperty("email") String email, @JsonProperty("devices") Set<DeviceResource.DeviceDto> devices,
@Nullable @JsonProperty("publicKey") @OnlyBase64Chars String publicKey, @Nullable @JsonProperty("privateKey") @ValidJWE String privateKey, @Nullable @JsonProperty("setupCode") @ValidJWE String setupCode) {
@Nullable @JsonProperty("ecdhPublicKey") @OnlyBase64Chars String ecdhPublicKey, @Nullable @JsonProperty("ecdsaPublicKey") @OnlyBase64Chars String ecdsaPublicKey, @Nullable @JsonProperty("privateKeys") @ValidJWE String privateKeys, @Nullable @JsonProperty("setupCode") @ValidJWE String setupCode) {
super(id, Type.USER, name, pictureUrl);
this.email = email;
this.devices = devices;
this.publicKey = publicKey;
this.privateKey = privateKey;
this.ecdhPublicKey = ecdhPublicKey;
this.ecdsaPublicKey = ecdsaPublicKey;
this.privateKeys = privateKeys;
this.setupCode = setupCode;

// duplicate fields to maintain backwards compatibility:
this.legacyEcdhPublicKey = ecdhPublicKey;
}

public static UserDto justPublicInfo(User user) {
return new UserDto(user.getId(), user.getName(), user.getPictureUrl(), user.getEmail(), Set.of(), user.getPublicKey(), null, null);
return new UserDto(user.getId(), user.getName(), user.getPictureUrl(), user.getEmail(), Set.of(), user.getEcdhPublicKey(), user.getEcdsaPublicKey(),null, null);
}
}
36 changes: 29 additions & 7 deletions backend/src/main/java/org/cryptomator/hub/api/UsersResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import org.cryptomator.hub.entities.User;
import org.cryptomator.hub.entities.Vault;
import org.cryptomator.hub.entities.events.EventLogger;
import org.cryptomator.hub.entities.events.VaultAccessGrantedEvent;
import org.eclipse.microprofile.jwt.JsonWebToken;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
Expand Down Expand Up @@ -71,14 +70,37 @@ public Response putMe(@Nullable @Valid UserDto dto) {
user.setPictureUrl(jwt.getClaim("picture"));
user.setEmail(jwt.getClaim("email"));
if (dto != null) {
user.setPublicKey(dto.publicKey);
user.setPrivateKey(dto.privateKey);
user.setEcdhPublicKey(dto.ecdhPublicKey);
user.setEcdsaPublicKey(dto.ecdsaPublicKey);
user.setPrivateKeys(dto.privateKeys);
user.setSetupCode(dto.setupCode);
updateDevices(user, dto);
}
userRepo.persist(user);
return Response.created(URI.create(".")).build();
}

/**
* Updates those devices that are present in both the entity and the DTO. No devices are added or removed.
*
* @param userEntity The persistent entity
* @param userDto The DTO
*/
private void updateDevices(User userEntity, UserDto userDto) {
var devices = userEntity.devices.stream().collect(Collectors.toUnmodifiableMap(Device::getId, Function.identity()));
var updatedDevices = userDto.devices.stream()
.filter(d -> devices.containsKey(d.id())) // only look at DTOs for which we find a matching existing entity
.map(dto -> {
var device = devices.get(dto.id());
device.setType(dto.type());
device.setName(dto.name());
device.setPublickey(dto.publicKey());
device.setUserPrivateKeys(dto.userPrivateKeys());
return device;
});
deviceRepo.persist(updatedDevices);
}

@POST
@Path("/me/access-tokens")
@RolesAllowed("user")
Expand Down Expand Up @@ -117,9 +139,9 @@ public Response updateMyAccessTokens(@NotNull Map<UUID, String> tokens) {
@APIResponse(responseCode = "404", description = "no user matching the subject of the JWT passed as Bearer Token")
public UserDto getMe(@QueryParam("withDevices") boolean withDevices) {
User user = userRepo.findById(jwt.getSubject());
Function<Device, DeviceResource.DeviceDto> mapDevices = d -> new DeviceResource.DeviceDto(d.getId(), d.getName(), d.getType(), d.getPublickey(), d.getUserPrivateKey(), d.getOwner().getId(), d.getCreationTime().truncatedTo(ChronoUnit.MILLIS));
Function<Device, DeviceResource.DeviceDto> mapDevices = d -> new DeviceResource.DeviceDto(d.getId(), d.getName(), d.getType(), d.getPublickey(), d.getUserPrivateKeys(), d.getOwner().getId(), d.getCreationTime().truncatedTo(ChronoUnit.MILLIS));
var devices = withDevices ? user.devices.stream().map(mapDevices).collect(Collectors.toSet()) : Set.<DeviceResource.DeviceDto>of();
return new UserDto(user.getId(), user.getName(), user.getPictureUrl(), user.getEmail(), devices, user.getPublicKey(), user.getPrivateKey(), user.getSetupCode());
return new UserDto(user.getId(), user.getName(), user.getPictureUrl(), user.getEmail(), devices, user.getEcdhPublicKey(), user.getEcdsaPublicKey(), user.getPrivateKeys(), user.getSetupCode());
}

@POST
Expand All @@ -131,8 +153,8 @@ public UserDto getMe(@QueryParam("withDevices") boolean withDevices) {
@APIResponse(responseCode = "204", description = "deleted keys, devices and access permissions")
public Response resetMe() {
User user = userRepo.findById(jwt.getSubject());
user.setPublicKey(null);
user.setPrivateKey(null);
user.setEcdhPublicKey(null);
user.setPrivateKeys(null);
user.setSetupCode(null);
userRepo.persist(user);
deviceRepo.deleteByOwner(user.getId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ public Response unlock(@PathParam("vaultId") UUID vaultId, @QueryParam("evenIfAr
}

var user = userRepo.findById(jwt.getSubject());
if (user.getPublicKey() == null) {
if (user.getEcdhPublicKey() == null) {
overheadhunter marked this conversation as resolved.
Show resolved Hide resolved
throw new ActionRequiredException("User account not initialized.");
}

overheadhunter marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
18 changes: 9 additions & 9 deletions backend/src/main/java/org/cryptomator/hub/entities/Device.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ public enum Type {
@Column(name = "publickey", nullable = false)
private String publickey;

@Column(name = "user_privatekey", nullable = false)
private String userPrivateKey;
@Column(name = "user_privatekeys", nullable = false)
private String userPrivateKeys;

@Column(name = "creation_time", nullable = false)
private Instant creationTime;
Expand Down Expand Up @@ -102,12 +102,12 @@ public void setPublickey(String publickey) {
this.publickey = publickey;
}

public String getUserPrivateKey() {
return userPrivateKey;
public String getUserPrivateKeys() {
return userPrivateKeys;
}

public void setUserPrivateKey(String userPrivateKey) {
this.userPrivateKey = userPrivateKey;
public void setUserPrivateKeys(String userPrivateKeys) {
this.userPrivateKeys = userPrivateKeys;
}

public Instant getCreationTime() {
Expand All @@ -126,7 +126,7 @@ public String toString() {
", name='" + name + '\'' +
", type='" + type + '\'' +
", publickey='" + publickey + '\'' +
", userPrivateKey='" + userPrivateKey + '\'' +
", userPrivateKey='" + userPrivateKeys + '\'' +
", creationTime='" + creationTime + '\'' +
'}';
}
Expand All @@ -141,13 +141,13 @@ public boolean equals(Object o) {
&& Objects.equals(this.name, other.name)
&& Objects.equals(this.type, other.type)
&& Objects.equals(this.publickey, other.publickey)
&& Objects.equals(this.userPrivateKey, other.userPrivateKey)
&& Objects.equals(this.userPrivateKeys, other.userPrivateKeys)
&& Objects.equals(this.creationTime, other.creationTime);
}

@Override
public int hashCode() {
return Objects.hash(id, owner, name, type, publickey, userPrivateKey, creationTime);
return Objects.hash(id, owner, name, type, publickey, userPrivateKeys, creationTime);
}

@ApplicationScoped
Expand Down
44 changes: 28 additions & 16 deletions backend/src/main/java/org/cryptomator/hub/entities/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
FROM User u
INNER JOIN EffectiveVaultAccess perm ON u.id = perm.id.authorityId
LEFT JOIN u.accessTokens token ON token.id.vaultId = :vaultId AND token.id.userId = u.id
WHERE perm.id.vaultId = :vaultId AND token.vault IS NULL AND u.publicKey IS NOT NULL
WHERE perm.id.vaultId = :vaultId AND token.vault IS NULL AND u.ecdhPublicKey IS NOT NULL
"""
)
@NamedQuery(name = "User.getEffectiveGroupUsers", query = """
Expand All @@ -49,11 +49,14 @@ public class User extends Authority {
@Column(name = "email")
private String email;

@Column(name = "publickey")
private String publicKey;
@Column(name = "ecdh_publickey")
private String ecdhPublicKey;

@Column(name = "privatekey")
private String privateKey;
@Column(name = "ecdsa_publickey")
private String ecdsaPublicKey;

@Column(name = "privatekeys")
private String privateKeys;

@Column(name = "setupcode")
private String setupCode;
Expand All @@ -74,20 +77,28 @@ public void setEmail(String email) {
this.email = email;
}

public String getPublicKey() {
return publicKey;
public String getEcdhPublicKey() {
return ecdhPublicKey;
}

public void setEcdhPublicKey(String ecdhPublicKey) {
this.ecdhPublicKey = ecdhPublicKey;
}

public String getEcdsaPublicKey() {
return ecdsaPublicKey;
}

public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
public void setEcdsaPublicKey(String ecdsaPublicKey) {
this.ecdsaPublicKey = ecdsaPublicKey;
}

public String getPrivateKey() {
return privateKey;
public String getPrivateKeys() {
return privateKeys;
}

public void setPrivateKey(String privateKey) {
this.privateKey = privateKey;
public void setPrivateKeys(String privateKeys) {
this.privateKeys = privateKeys;
}

public String getSetupCode() {
Expand Down Expand Up @@ -128,14 +139,15 @@ public boolean equals(Object o) {
return super.equals(that) //
&& Objects.equals(pictureUrl, that.pictureUrl) //
&& Objects.equals(email, that.email) //
&& Objects.equals(publicKey, that.publicKey) //
&& Objects.equals(privateKey, that.privateKey) //
&& Objects.equals(ecdhPublicKey, that.ecdhPublicKey) //
&& Objects.equals(ecdsaPublicKey, that.ecdsaPublicKey) //
&& Objects.equals(privateKeys, that.privateKeys) //
&& Objects.equals(setupCode, that.setupCode);
}

@Override
public int hashCode() {
return Objects.hash(super.getId(), pictureUrl, email, publicKey, privateKey, setupCode);
return Objects.hash(super.getId(), pictureUrl, email, ecdhPublicKey, privateKeys, setupCode);
}

@ApplicationScoped
Expand Down
Binary file modified backend/src/main/resources/org/cryptomator/hub/flyway/ERM.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
ALTER TABLE "user_details" RENAME COLUMN "publickey" TO "ecdh_publickey";
ALTER TABLE "user_details" RENAME COLUMN "privatekey" TO "privatekeys";
ALTER TABLE "user_details" ADD "ecdsa_publickey" VARCHAR;
ALTER TABLE "device" RENAME COLUMN "user_privatekey" TO "user_privatekeys";
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ public void testGetUsersRequiringAccess1() throws SQLException {
try (var c = dataSource.getConnection(); var s = c.createStatement()) {
s.execute("""
UPDATE "user_details"
SET publickey='public2', privatekey='private2', setupcode='setup2'
SET ecdh_publickey='public2', ecdsa_publickey='ecdsa_public2', privatekeys='private2', setupcode='setup2'
WHERE id='user2';
""");
}
Expand All @@ -458,7 +458,7 @@ public void testGetUsersRequiringAccess1() throws SQLException {
try (var c = dataSource.getConnection(); var s = c.createStatement()) {
s.execute("""
UPDATE
"user_details" SET publickey=NULL, privatekey=NULL, setupcode=NULL
"user_details" SET ecdh_publickey=NULL, ecdsa_publickey=NULL, privatekeys=NULL, setupcode=NULL
WHERE id='user2';
""");
}
Expand Down Expand Up @@ -488,7 +488,7 @@ public void testGetUsersRequiringAccess2() throws SQLException {
try (var c = dataSource.getConnection(); var s = c.createStatement()) {
s.execute("""
UPDATE
"user_details" SET publickey='public2', privatekey='private2', setupcode='setup2'
"user_details" SET ecdh_publickey='ecdh_public2', ecdsa_publickey='ecdsa_public2', privatekeys='private2', setupcode='setup2'
WHERE id='user2';
""");
}
Expand All @@ -500,7 +500,7 @@ public void testGetUsersRequiringAccess2() throws SQLException {
try (var c = dataSource.getConnection(); var s = c.createStatement()) {
s.execute("""
UPDATE
"user_details" SET publickey=NULL, privatekey=NULL, setupcode=NULL
"user_details" SET ecdh_publickey=NULL, ecdsa_publickey=NULL, privatekeys=NULL, setupcode=NULL
WHERE id='user2';
""");
}
Expand Down Expand Up @@ -559,7 +559,7 @@ public void setup() throws SQLException {
// user999 will be deleted in #cleanup()
s.execute("""
INSERT INTO "authority" ("id", "type", "name") VALUES ('user999', 'USER', 'User 999');
INSERT INTO "user_details" ("id", "publickey", "privatekey", "setupcode") VALUES ('user999', 'public999', 'private999', 'setup999');
INSERT INTO "user_details" ("id", "ecdh_publickey", "ecdsa_publickey", "privatekeys", "setupcode") VALUES ('user999', 'ecdh_public999', 'ecdsa_public999', 'private999', 'setup999');
INSERT INTO "group_membership" ("group_id", "member_id") VALUES ('group2', 'user999')
""");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ VALUES
('group1', 'GROUP', 'Group Name 1'),
('group2', 'GROUP', 'Group Name 2');

INSERT INTO "user_details" ("id", "publickey", "privatekey", "setupcode")
INSERT INTO "user_details" ("id", "ecdh_publickey", "ecdsa_publickey", "privatekeys", "setupcode")
VALUES
('user1', 'public1', 'private1', 'setup1'),
('user2', NULL, NULL, NULL);
('user1', 'ecdh_public1', 'ecdsa_public1', 'private1', 'setup1'),
('user2', NULL, NULL, NULL, NULL);

INSERT INTO "group_details" ("id")
VALUES
Expand Down Expand Up @@ -52,7 +52,7 @@ VALUES
('7E57C0DE-0000-4000-8000-000100002222', 'group2', 'OWNER'),
('7E57C0DE-0000-4000-8000-000100002222', 'group1', 'MEMBER');

INSERT INTO "device" ("id", "owner_id", "name", "type", "publickey", "creation_time", "user_privatekey")
INSERT INTO "device" ("id", "owner_id", "name", "type", "publickey", "creation_time", "user_privatekeys")
VALUES
('device1', 'user1', 'Computer 1', 'DESKTOP', 'publickey1', '2020-02-20 20:20:20', 'jwe.jwe.jwe.user1.device1'),
('device2', 'user2', 'Computer 2', 'DESKTOP', 'publickey2', '2020-02-20 20:20:20', 'jwe.jwe.jwe.user2.device2'),
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/common/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ export type UserDto = {
email: string;
devices: DeviceDto[];
accessibleVaults: VaultDto[];
publicKey?: string;
ecdhPublicKey?: string;
ecdsaPublicKey?: string;
privateKey?: string;
setupCode?: string;
}
Expand Down
Loading