]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/helper/GroupV2Helper.java
Move group store to database
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / helper / GroupV2Helper.java
1 package org.asamk.signal.manager.helper;
2
3 import com.google.protobuf.ByteString;
4 import com.google.protobuf.InvalidProtocolBufferException;
5
6 import org.asamk.signal.manager.SignalDependencies;
7 import org.asamk.signal.manager.api.Pair;
8 import org.asamk.signal.manager.groups.GroupLinkPassword;
9 import org.asamk.signal.manager.groups.GroupLinkState;
10 import org.asamk.signal.manager.groups.GroupPermission;
11 import org.asamk.signal.manager.groups.GroupUtils;
12 import org.asamk.signal.manager.groups.NotAGroupMemberException;
13 import org.asamk.signal.manager.storage.groups.GroupInfoV2;
14 import org.asamk.signal.manager.storage.recipients.RecipientId;
15 import org.asamk.signal.manager.util.IOUtils;
16 import org.asamk.signal.manager.util.Utils;
17 import org.signal.libsignal.zkgroup.InvalidInputException;
18 import org.signal.libsignal.zkgroup.VerificationFailedException;
19 import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse;
20 import org.signal.libsignal.zkgroup.groups.GroupMasterKey;
21 import org.signal.libsignal.zkgroup.groups.GroupSecretParams;
22 import org.signal.libsignal.zkgroup.groups.UuidCiphertext;
23 import org.signal.libsignal.zkgroup.profiles.ProfileKey;
24 import org.signal.storageservice.protos.groups.AccessControl;
25 import org.signal.storageservice.protos.groups.GroupChange;
26 import org.signal.storageservice.protos.groups.Member;
27 import org.signal.storageservice.protos.groups.local.DecryptedGroup;
28 import org.signal.storageservice.protos.groups.local.DecryptedGroupChange;
29 import org.signal.storageservice.protos.groups.local.DecryptedGroupJoinInfo;
30 import org.signal.storageservice.protos.groups.local.DecryptedMember;
31 import org.signal.storageservice.protos.groups.local.DecryptedPendingMember;
32 import org.signal.storageservice.protos.groups.local.DecryptedRequestingMember;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.whispersystems.signalservice.api.groupsv2.DecryptedGroupUtil;
36 import org.whispersystems.signalservice.api.groupsv2.GroupCandidate;
37 import org.whispersystems.signalservice.api.groupsv2.GroupHistoryPage;
38 import org.whispersystems.signalservice.api.groupsv2.GroupLinkNotActiveException;
39 import org.whispersystems.signalservice.api.groupsv2.GroupsV2AuthorizationString;
40 import org.whispersystems.signalservice.api.groupsv2.GroupsV2Operations;
41 import org.whispersystems.signalservice.api.groupsv2.InvalidGroupStateException;
42 import org.whispersystems.signalservice.api.groupsv2.NotAbleToApplyGroupV2ChangeException;
43 import org.whispersystems.signalservice.api.push.ACI;
44 import org.whispersystems.signalservice.api.push.PNI;
45 import org.whispersystems.signalservice.api.push.ServiceId;
46 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
47 import org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException;
48 import org.whispersystems.signalservice.api.util.UuidUtil;
49
50 import java.io.File;
51 import java.io.FileInputStream;
52 import java.io.IOException;
53 import java.io.InputStream;
54 import java.util.ArrayList;
55 import java.util.Arrays;
56 import java.util.HashMap;
57 import java.util.List;
58 import java.util.Optional;
59 import java.util.Set;
60 import java.util.UUID;
61 import java.util.concurrent.TimeUnit;
62 import java.util.function.Function;
63 import java.util.stream.Collectors;
64 import java.util.stream.Stream;
65
66 class GroupV2Helper {
67
68 private final static Logger logger = LoggerFactory.getLogger(GroupV2Helper.class);
69
70 private final SignalDependencies dependencies;
71 private final Context context;
72
73 private HashMap<Long, AuthCredentialWithPniResponse> groupApiCredentials;
74
75 GroupV2Helper(final Context context) {
76 this.dependencies = context.getDependencies();
77 this.context = context;
78 }
79
80 DecryptedGroup getDecryptedGroup(final GroupSecretParams groupSecretParams) throws NotAGroupMemberException {
81 try {
82 final var groupsV2AuthorizationString = getGroupAuthForToday(groupSecretParams);
83 return dependencies.getGroupsV2Api().getGroup(groupSecretParams, groupsV2AuthorizationString);
84 } catch (NonSuccessfulResponseCodeException e) {
85 if (e.getCode() == 403) {
86 throw new NotAGroupMemberException(GroupUtils.getGroupIdV2(groupSecretParams), null);
87 }
88 logger.warn("Failed to retrieve Group V2 info, ignoring: {}", e.getMessage());
89 return null;
90 } catch (IOException | VerificationFailedException | InvalidGroupStateException e) {
91 logger.warn("Failed to retrieve Group V2 info, ignoring: {}", e.getMessage());
92 return null;
93 }
94 }
95
96 DecryptedGroupJoinInfo getDecryptedGroupJoinInfo(
97 GroupMasterKey groupMasterKey, GroupLinkPassword password
98 ) throws IOException, GroupLinkNotActiveException {
99 var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
100
101 return dependencies.getGroupsV2Api()
102 .getGroupJoinInfo(groupSecretParams,
103 Optional.ofNullable(password).map(GroupLinkPassword::serialize),
104 getGroupAuthForToday(groupSecretParams));
105 }
106
107 GroupHistoryPage getDecryptedGroupHistoryPage(
108 final GroupSecretParams groupSecretParams, int fromRevision
109 ) throws NotAGroupMemberException {
110 try {
111 final var groupsV2AuthorizationString = getGroupAuthForToday(groupSecretParams);
112 return dependencies.getGroupsV2Api()
113 .getGroupHistoryPage(groupSecretParams, fromRevision, groupsV2AuthorizationString, false);
114 } catch (NonSuccessfulResponseCodeException e) {
115 if (e.getCode() == 403) {
116 throw new NotAGroupMemberException(GroupUtils.getGroupIdV2(groupSecretParams), null);
117 }
118 logger.warn("Failed to retrieve Group V2 history, ignoring: {}", e.getMessage());
119 return null;
120 } catch (IOException | VerificationFailedException | InvalidGroupStateException e) {
121 logger.warn("Failed to retrieve Group V2 history, ignoring: {}", e.getMessage());
122 return null;
123 }
124 }
125
126 int findRevisionWeWereAdded(DecryptedGroup partialDecryptedGroup) {
127 ByteString bytes = UuidUtil.toByteString(getSelfAci().uuid());
128 for (DecryptedMember decryptedMember : partialDecryptedGroup.getMembersList()) {
129 if (decryptedMember.getUuid().equals(bytes)) {
130 return decryptedMember.getJoinedAtRevision();
131 }
132 }
133 return partialDecryptedGroup.getRevision();
134 }
135
136 Pair<GroupInfoV2, DecryptedGroup> createGroup(
137 String name, Set<RecipientId> members, File avatarFile
138 ) throws IOException {
139 final var avatarBytes = readAvatarBytes(avatarFile);
140 final var newGroup = buildNewGroup(name, members, avatarBytes);
141 if (newGroup == null) {
142 return null;
143 }
144
145 final var groupSecretParams = newGroup.getGroupSecretParams();
146
147 final GroupsV2AuthorizationString groupAuthForToday;
148 final DecryptedGroup decryptedGroup;
149 try {
150 groupAuthForToday = getGroupAuthForToday(groupSecretParams);
151 dependencies.getGroupsV2Api().putNewGroup(newGroup, groupAuthForToday);
152 decryptedGroup = dependencies.getGroupsV2Api().getGroup(groupSecretParams, groupAuthForToday);
153 } catch (IOException | VerificationFailedException | InvalidGroupStateException e) {
154 logger.warn("Failed to create V2 group: {}", e.getMessage());
155 return null;
156 }
157 if (decryptedGroup == null) {
158 logger.warn("Failed to create V2 group, unknown error!");
159 return null;
160 }
161
162 final var groupId = GroupUtils.getGroupIdV2(groupSecretParams);
163 final var masterKey = groupSecretParams.getMasterKey();
164 var g = new GroupInfoV2(groupId, masterKey, context.getAccount().getRecipientResolver());
165
166 return new Pair<>(g, decryptedGroup);
167 }
168
169 private byte[] readAvatarBytes(final File avatarFile) throws IOException {
170 final byte[] avatarBytes;
171 try (InputStream avatar = avatarFile == null ? null : new FileInputStream(avatarFile)) {
172 avatarBytes = avatar == null ? null : IOUtils.readFully(avatar);
173 }
174 return avatarBytes;
175 }
176
177 private GroupsV2Operations.NewGroup buildNewGroup(
178 String name, Set<RecipientId> members, byte[] avatar
179 ) {
180 final var profileKeyCredential = context.getProfileHelper()
181 .getExpiringProfileKeyCredential(context.getAccount().getSelfRecipientId());
182 if (profileKeyCredential == null) {
183 logger.warn("Cannot create a V2 group as self does not have a versioned profile");
184 return null;
185 }
186
187 final var self = new GroupCandidate(getSelfAci().uuid(), Optional.of(profileKeyCredential));
188 final var memberList = new ArrayList<>(members);
189 final var credentials = context.getProfileHelper().getExpiringProfileKeyCredential(memberList).stream();
190 final var uuids = memberList.stream()
191 .map(member -> context.getRecipientHelper().resolveSignalServiceAddress(member).getServiceId().uuid());
192 var candidates = Utils.zip(uuids,
193 credentials,
194 (uuid, credential) -> new GroupCandidate(uuid, Optional.ofNullable(credential)))
195 .collect(Collectors.toSet());
196
197 final var groupSecretParams = GroupSecretParams.generate();
198 return dependencies.getGroupsV2Operations()
199 .createNewGroup(groupSecretParams,
200 name,
201 Optional.ofNullable(avatar),
202 self,
203 candidates,
204 Member.Role.DEFAULT,
205 0);
206 }
207
208 Pair<DecryptedGroup, GroupChange> updateGroup(
209 GroupInfoV2 groupInfoV2, String name, String description, File avatarFile
210 ) throws IOException {
211 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
212 var groupOperations = dependencies.getGroupsV2Operations().forGroup(groupSecretParams);
213
214 var change = name != null ? groupOperations.createModifyGroupTitle(name) : GroupChange.Actions.newBuilder();
215
216 if (description != null) {
217 change.setModifyDescription(groupOperations.createModifyGroupDescriptionAction(description));
218 }
219
220 if (avatarFile != null) {
221 final var avatarBytes = readAvatarBytes(avatarFile);
222 var avatarCdnKey = dependencies.getGroupsV2Api()
223 .uploadAvatar(avatarBytes, groupSecretParams, getGroupAuthForToday(groupSecretParams));
224 change.setModifyAvatar(GroupChange.Actions.ModifyAvatarAction.newBuilder().setAvatar(avatarCdnKey));
225 }
226
227 change.setSourceUuid(getSelfAci().toByteString());
228
229 return commitChange(groupInfoV2, change);
230 }
231
232 Pair<DecryptedGroup, GroupChange> addMembers(
233 GroupInfoV2 groupInfoV2, Set<RecipientId> newMembers
234 ) throws IOException {
235 GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
236
237 final var memberList = new ArrayList<>(newMembers);
238 final var credentials = context.getProfileHelper().getExpiringProfileKeyCredential(memberList).stream();
239 final var uuids = memberList.stream()
240 .map(member -> context.getRecipientHelper().resolveSignalServiceAddress(member).getServiceId().uuid());
241 var candidates = Utils.zip(uuids,
242 credentials,
243 (uuid, credential) -> new GroupCandidate(uuid, Optional.ofNullable(credential)))
244 .collect(Collectors.toSet());
245 final var bannedUuids = groupInfoV2.getBannedMembers()
246 .stream()
247 .map(member -> context.getRecipientHelper().resolveSignalServiceAddress(member).getServiceId().uuid())
248 .collect(Collectors.toSet());
249
250 final var aci = getSelfAci();
251 final var change = groupOperations.createModifyGroupMembershipChange(candidates, bannedUuids, aci.uuid());
252
253 change.setSourceUuid(getSelfAci().toByteString());
254
255 return commitChange(groupInfoV2, change);
256 }
257
258 Pair<DecryptedGroup, GroupChange> leaveGroup(
259 GroupInfoV2 groupInfoV2, Set<RecipientId> membersToMakeAdmin
260 ) throws IOException {
261 var pendingMembersList = groupInfoV2.getGroup().getPendingMembersList();
262 final var selfAci = getSelfAci();
263 var selfPendingMember = DecryptedGroupUtil.findPendingByUuid(pendingMembersList, selfAci.uuid());
264
265 if (selfPendingMember.isPresent()) {
266 return revokeInvites(groupInfoV2, Set.of(selfPendingMember.get()));
267 }
268
269 final var adminUuids = membersToMakeAdmin.stream()
270 .map(context.getRecipientHelper()::resolveSignalServiceAddress)
271 .map(SignalServiceAddress::getServiceId)
272 .map(ServiceId::uuid)
273 .toList();
274 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
275 return commitChange(groupInfoV2,
276 groupOperations.createLeaveAndPromoteMembersToAdmin(selfAci.uuid(), adminUuids));
277 }
278
279 Pair<DecryptedGroup, GroupChange> removeMembers(
280 GroupInfoV2 groupInfoV2, Set<RecipientId> members
281 ) throws IOException {
282 final var memberUuids = members.stream()
283 .map(context.getRecipientHelper()::resolveSignalServiceAddress)
284 .map(SignalServiceAddress::getServiceId)
285 .map(ServiceId::uuid)
286 .collect(Collectors.toSet());
287 return ejectMembers(groupInfoV2, memberUuids);
288 }
289
290 Pair<DecryptedGroup, GroupChange> revokeInvitedMembers(
291 GroupInfoV2 groupInfoV2, Set<RecipientId> members
292 ) throws IOException {
293 var pendingMembersList = groupInfoV2.getGroup().getPendingMembersList();
294 final var memberUuids = members.stream()
295 .map(context.getRecipientHelper()::resolveSignalServiceAddress)
296 .map(SignalServiceAddress::getServiceId)
297 .map(ServiceId::uuid)
298 .map(uuid -> DecryptedGroupUtil.findPendingByUuid(pendingMembersList, uuid))
299 .filter(Optional::isPresent)
300 .map(Optional::get)
301 .collect(Collectors.toSet());
302 return revokeInvites(groupInfoV2, memberUuids);
303 }
304
305 Pair<DecryptedGroup, GroupChange> banMembers(
306 GroupInfoV2 groupInfoV2, Set<RecipientId> block
307 ) throws IOException {
308 GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
309
310 final var uuids = block.stream()
311 .map(member -> context.getRecipientHelper().resolveSignalServiceAddress(member).getServiceId().uuid())
312 .collect(Collectors.toSet());
313
314 final var change = groupOperations.createBanUuidsChange(uuids,
315 false,
316 groupInfoV2.getGroup().getBannedMembersList());
317
318 change.setSourceUuid(getSelfAci().toByteString());
319
320 return commitChange(groupInfoV2, change);
321 }
322
323 Pair<DecryptedGroup, GroupChange> unbanMembers(
324 GroupInfoV2 groupInfoV2, Set<RecipientId> block
325 ) throws IOException {
326 GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
327
328 final var uuids = block.stream()
329 .map(member -> context.getRecipientHelper().resolveSignalServiceAddress(member).getServiceId().uuid())
330 .collect(Collectors.toSet());
331
332 final var change = groupOperations.createUnbanUuidsChange(uuids);
333
334 change.setSourceUuid(getSelfAci().toByteString());
335
336 return commitChange(groupInfoV2, change);
337 }
338
339 Pair<DecryptedGroup, GroupChange> resetGroupLinkPassword(GroupInfoV2 groupInfoV2) throws IOException {
340 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
341 final var newGroupLinkPassword = GroupLinkPassword.createNew().serialize();
342 final var change = groupOperations.createModifyGroupLinkPasswordChange(newGroupLinkPassword);
343 return commitChange(groupInfoV2, change);
344 }
345
346 Pair<DecryptedGroup, GroupChange> setGroupLinkState(
347 GroupInfoV2 groupInfoV2, GroupLinkState state
348 ) throws IOException {
349 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
350
351 final var accessRequired = toAccessControl(state);
352 final var requiresNewPassword = state != GroupLinkState.DISABLED && groupInfoV2.getGroup()
353 .getInviteLinkPassword()
354 .isEmpty();
355
356 final var change = requiresNewPassword ? groupOperations.createModifyGroupLinkPasswordAndRightsChange(
357 GroupLinkPassword.createNew().serialize(),
358 accessRequired) : groupOperations.createChangeJoinByLinkRights(accessRequired);
359 return commitChange(groupInfoV2, change);
360 }
361
362 Pair<DecryptedGroup, GroupChange> setEditDetailsPermission(
363 GroupInfoV2 groupInfoV2, GroupPermission permission
364 ) throws IOException {
365 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
366
367 final var accessRequired = toAccessControl(permission);
368 final var change = groupOperations.createChangeAttributesRights(accessRequired);
369 return commitChange(groupInfoV2, change);
370 }
371
372 Pair<DecryptedGroup, GroupChange> setAddMemberPermission(
373 GroupInfoV2 groupInfoV2, GroupPermission permission
374 ) throws IOException {
375 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
376
377 final var accessRequired = toAccessControl(permission);
378 final var change = groupOperations.createChangeMembershipRights(accessRequired);
379 return commitChange(groupInfoV2, change);
380 }
381
382 Pair<DecryptedGroup, GroupChange> updateSelfProfileKey(GroupInfoV2 groupInfoV2) throws IOException {
383 Optional<DecryptedMember> selfInGroup = groupInfoV2.getGroup() == null
384 ? Optional.empty()
385 : DecryptedGroupUtil.findMemberByUuid(groupInfoV2.getGroup().getMembersList(), getSelfAci().uuid());
386 if (selfInGroup.isEmpty()) {
387 logger.trace("Not updating group, self not in group " + groupInfoV2.getGroupId().toBase64());
388 return null;
389 }
390
391 final var profileKey = context.getAccount().getProfileKey();
392 if (Arrays.equals(profileKey.serialize(), selfInGroup.get().getProfileKey().toByteArray())) {
393 logger.trace("Not updating group, own Profile Key is already up to date in group "
394 + groupInfoV2.getGroupId().toBase64());
395 return null;
396 }
397 logger.debug("Updating own profile key in group " + groupInfoV2.getGroupId().toBase64());
398
399 final var selfRecipientId = context.getAccount().getSelfRecipientId();
400 final var profileKeyCredential = context.getProfileHelper().getExpiringProfileKeyCredential(selfRecipientId);
401 if (profileKeyCredential == null) {
402 logger.trace("Cannot update profile key as self does not have a versioned profile");
403 return null;
404 }
405
406 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
407 final var change = groupOperations.createUpdateProfileKeyCredentialChange(profileKeyCredential);
408 change.setSourceUuid(getSelfAci().toByteString());
409 return commitChange(groupInfoV2, change);
410 }
411
412 GroupChange joinGroup(
413 GroupMasterKey groupMasterKey,
414 GroupLinkPassword groupLinkPassword,
415 DecryptedGroupJoinInfo decryptedGroupJoinInfo
416 ) throws IOException {
417 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
418 final var groupOperations = dependencies.getGroupsV2Operations().forGroup(groupSecretParams);
419
420 final var selfRecipientId = context.getAccount().getSelfRecipientId();
421 final var profileKeyCredential = context.getProfileHelper().getExpiringProfileKeyCredential(selfRecipientId);
422 if (profileKeyCredential == null) {
423 throw new IOException("Cannot join a V2 group as self does not have a versioned profile");
424 }
425
426 var requestToJoin = decryptedGroupJoinInfo.getAddFromInviteLink() == AccessControl.AccessRequired.ADMINISTRATOR;
427 var change = requestToJoin
428 ? groupOperations.createGroupJoinRequest(profileKeyCredential)
429 : groupOperations.createGroupJoinDirect(profileKeyCredential);
430
431 change.setSourceUuid(context.getRecipientHelper()
432 .resolveSignalServiceAddress(selfRecipientId)
433 .getServiceId()
434 .toByteString());
435
436 return commitChange(groupSecretParams, decryptedGroupJoinInfo.getRevision(), change, groupLinkPassword);
437 }
438
439 Pair<DecryptedGroup, GroupChange> acceptInvite(GroupInfoV2 groupInfoV2) throws IOException {
440 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
441
442 final var selfRecipientId = context.getAccount().getSelfRecipientId();
443 final var profileKeyCredential = context.getProfileHelper().getExpiringProfileKeyCredential(selfRecipientId);
444 if (profileKeyCredential == null) {
445 throw new IOException("Cannot join a V2 group as self does not have a versioned profile");
446 }
447
448 final var change = groupOperations.createAcceptInviteChange(profileKeyCredential);
449
450 final var aci = context.getRecipientHelper().resolveSignalServiceAddress(selfRecipientId).getServiceId();
451 change.setSourceUuid(aci.toByteString());
452
453 return commitChange(groupInfoV2, change);
454 }
455
456 Pair<DecryptedGroup, GroupChange> setMemberAdmin(
457 GroupInfoV2 groupInfoV2, RecipientId recipientId, boolean admin
458 ) throws IOException {
459 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
460 final var address = context.getRecipientHelper().resolveSignalServiceAddress(recipientId);
461 final var newRole = admin ? Member.Role.ADMINISTRATOR : Member.Role.DEFAULT;
462 final var change = groupOperations.createChangeMemberRole(address.getServiceId().uuid(), newRole);
463 return commitChange(groupInfoV2, change);
464 }
465
466 Pair<DecryptedGroup, GroupChange> setMessageExpirationTimer(
467 GroupInfoV2 groupInfoV2, int messageExpirationTimer
468 ) throws IOException {
469 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
470 final var change = groupOperations.createModifyGroupTimerChange(messageExpirationTimer);
471 return commitChange(groupInfoV2, change);
472 }
473
474 Pair<DecryptedGroup, GroupChange> setIsAnnouncementGroup(
475 GroupInfoV2 groupInfoV2, boolean isAnnouncementGroup
476 ) throws IOException {
477 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
478 final var change = groupOperations.createAnnouncementGroupChange(isAnnouncementGroup);
479 return commitChange(groupInfoV2, change);
480 }
481
482 private AccessControl.AccessRequired toAccessControl(final GroupLinkState state) {
483 return switch (state) {
484 case DISABLED -> AccessControl.AccessRequired.UNSATISFIABLE;
485 case ENABLED -> AccessControl.AccessRequired.ANY;
486 case ENABLED_WITH_APPROVAL -> AccessControl.AccessRequired.ADMINISTRATOR;
487 };
488 }
489
490 private AccessControl.AccessRequired toAccessControl(final GroupPermission permission) {
491 return switch (permission) {
492 case EVERY_MEMBER -> AccessControl.AccessRequired.MEMBER;
493 case ONLY_ADMINS -> AccessControl.AccessRequired.ADMINISTRATOR;
494 };
495 }
496
497 private GroupsV2Operations.GroupOperations getGroupOperations(final GroupInfoV2 groupInfoV2) {
498 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
499 return dependencies.getGroupsV2Operations().forGroup(groupSecretParams);
500 }
501
502 private Pair<DecryptedGroup, GroupChange> revokeInvites(
503 GroupInfoV2 groupInfoV2, Set<DecryptedPendingMember> pendingMembers
504 ) throws IOException {
505 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
506 final var uuidCipherTexts = pendingMembers.stream().map(member -> {
507 try {
508 return new UuidCiphertext(member.getUuidCipherText().toByteArray());
509 } catch (InvalidInputException e) {
510 throw new AssertionError(e);
511 }
512 }).collect(Collectors.toSet());
513 return commitChange(groupInfoV2, groupOperations.createRemoveInvitationChange(uuidCipherTexts));
514 }
515
516 private Pair<DecryptedGroup, GroupChange> ejectMembers(
517 GroupInfoV2 groupInfoV2, Set<UUID> uuids
518 ) throws IOException {
519 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
520 return commitChange(groupInfoV2, groupOperations.createRemoveMembersChange(uuids, false, List.of()));
521 }
522
523 private Pair<DecryptedGroup, GroupChange> commitChange(
524 GroupInfoV2 groupInfoV2, GroupChange.Actions.Builder change
525 ) throws IOException {
526 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
527 final var groupOperations = dependencies.getGroupsV2Operations().forGroup(groupSecretParams);
528 final var previousGroupState = groupInfoV2.getGroup();
529 final var nextRevision = previousGroupState.getRevision() + 1;
530 final var changeActions = change.setRevision(nextRevision).build();
531 final DecryptedGroupChange decryptedChange;
532 final DecryptedGroup decryptedGroupState;
533
534 try {
535 decryptedChange = groupOperations.decryptChange(changeActions, getSelfAci().uuid());
536 decryptedGroupState = DecryptedGroupUtil.apply(previousGroupState, decryptedChange);
537 } catch (VerificationFailedException | InvalidGroupStateException | NotAbleToApplyGroupV2ChangeException e) {
538 throw new IOException(e);
539 }
540
541 var signedGroupChange = dependencies.getGroupsV2Api()
542 .patchGroup(changeActions, getGroupAuthForToday(groupSecretParams), Optional.empty());
543
544 return new Pair<>(decryptedGroupState, signedGroupChange);
545 }
546
547 private GroupChange commitChange(
548 GroupSecretParams groupSecretParams,
549 int currentRevision,
550 GroupChange.Actions.Builder change,
551 GroupLinkPassword password
552 ) throws IOException {
553 final var nextRevision = currentRevision + 1;
554 final var changeActions = change.setRevision(nextRevision).build();
555
556 return dependencies.getGroupsV2Api()
557 .patchGroup(changeActions,
558 getGroupAuthForToday(groupSecretParams),
559 Optional.ofNullable(password).map(GroupLinkPassword::serialize));
560 }
561
562 Pair<ServiceId, ProfileKey> getAuthoritativeProfileKeyFromChange(final DecryptedGroupChange change) {
563 UUID editor = UuidUtil.fromByteStringOrNull(change.getEditor());
564 final var editorProfileKeyBytes = Stream.concat(Stream.of(change.getNewMembersList().stream(),
565 change.getPromotePendingMembersList().stream(),
566 change.getModifiedProfileKeysList().stream())
567 .flatMap(Function.identity())
568 .filter(m -> UuidUtil.fromByteString(m.getUuid()).equals(editor))
569 .map(DecryptedMember::getProfileKey),
570 change.getNewRequestingMembersList()
571 .stream()
572 .filter(m -> UuidUtil.fromByteString(m.getUuid()).equals(editor))
573 .map(DecryptedRequestingMember::getProfileKey)).findFirst();
574
575 if (editorProfileKeyBytes.isEmpty()) {
576 return null;
577 }
578
579 ProfileKey profileKey;
580 try {
581 profileKey = new ProfileKey(editorProfileKeyBytes.get().toByteArray());
582 } catch (InvalidInputException e) {
583 logger.debug("Bad profile key in group");
584 return null;
585 }
586
587 return new Pair<>(ServiceId.from(editor), profileKey);
588 }
589
590 DecryptedGroup getUpdatedDecryptedGroup(DecryptedGroup group, DecryptedGroupChange decryptedGroupChange) {
591 try {
592 return DecryptedGroupUtil.apply(group, decryptedGroupChange);
593 } catch (NotAbleToApplyGroupV2ChangeException e) {
594 return null;
595 }
596 }
597
598 DecryptedGroupChange getDecryptedGroupChange(byte[] signedGroupChange, GroupMasterKey groupMasterKey) {
599 if (signedGroupChange != null) {
600 var groupOperations = dependencies.getGroupsV2Operations()
601 .forGroup(GroupSecretParams.deriveFromMasterKey(groupMasterKey));
602
603 try {
604 return groupOperations.decryptChange(GroupChange.parseFrom(signedGroupChange), true).orElse(null);
605 } catch (VerificationFailedException | InvalidGroupStateException | InvalidProtocolBufferException e) {
606 return null;
607 }
608 }
609
610 return null;
611 }
612
613 private static long currentDaySeconds() {
614 return TimeUnit.DAYS.toSeconds(TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis()));
615 }
616
617 private GroupsV2AuthorizationString getGroupAuthForToday(
618 final GroupSecretParams groupSecretParams
619 ) throws IOException {
620 final var todaySeconds = currentDaySeconds();
621 if (groupApiCredentials == null || !groupApiCredentials.containsKey(todaySeconds)) {
622 // Returns credentials for the next 7 days
623 groupApiCredentials = dependencies.getGroupsV2Api().getCredentials(todaySeconds);
624 // TODO cache credentials on disk until they expire
625 }
626 try {
627 return getAuthorizationString(groupSecretParams, todaySeconds);
628 } catch (VerificationFailedException e) {
629 logger.debug("Group api credentials invalid, renewing and trying again.");
630 groupApiCredentials.clear();
631 }
632
633 groupApiCredentials = dependencies.getGroupsV2Api().getCredentials(todaySeconds);
634 try {
635 return getAuthorizationString(groupSecretParams, todaySeconds);
636 } catch (VerificationFailedException e) {
637 throw new IOException(e);
638 }
639 }
640
641 private GroupsV2AuthorizationString getAuthorizationString(
642 final GroupSecretParams groupSecretParams, final long todaySeconds
643 ) throws VerificationFailedException {
644 var authCredentialResponse = groupApiCredentials.get(todaySeconds);
645 final var aci = getSelfAci();
646 final var pni = getSelfPni();
647 return dependencies.getGroupsV2Api()
648 .getGroupsV2AuthorizationString(aci, pni, todaySeconds, groupSecretParams, authCredentialResponse);
649 }
650
651 private ACI getSelfAci() {
652 return context.getAccount().getAci();
653 }
654
655 private PNI getSelfPni() {
656 return context.getAccount().getPni();
657 }
658 }