Support misconfigured room encryption

This commit is contained in:
Valere 2021-12-10 15:52:04 +01:00
parent 3251463410
commit 6b05e7a6bb
30 changed files with 288 additions and 53 deletions

1
changelog.d/4711.bugfix Normal file
View File

@ -0,0 +1 @@
Better handling of misconfigured room encryption

View File

@ -29,7 +29,7 @@ interface RoomCryptoService {
/**
* Enable encryption of the room
*/
suspend fun enableEncryption(algorithm: String = MXCRYPTO_ALGORITHM_MEGOLM)
suspend fun enableEncryption(algorithm: String = MXCRYPTO_ALGORITHM_MEGOLM, force: Boolean = false)
/**
* Ensures all members of the room are loaded and outbound session keys are shared.

View File

@ -0,0 +1,28 @@
/*
* Copyright (c) 2021 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.android.sdk.api.session.room.model
import org.matrix.android.sdk.internal.crypto.MXCRYPTO_ALGORITHM_MEGOLM
sealed class RoomEncryptionAlgorithm {
abstract class SupportedAlgorithm(val alg: String) : RoomEncryptionAlgorithm()
object Megolm : SupportedAlgorithm(MXCRYPTO_ALGORITHM_MEGOLM)
data class UnsupportedAlgorithm(val name: String?) : RoomEncryptionAlgorithm()
}

View File

@ -62,7 +62,8 @@ data class RoomSummary(
val roomType: String? = null,
val spaceParents: List<SpaceParentInfo>? = null,
val spaceChildren: List<SpaceChildInfo>? = null,
val flattenParentIds: List<String> = emptyList()
val flattenParentIds: List<String> = emptyList(),
val roomEncryptionAlgorithm: RoomEncryptionAlgorithm? = null
) {
val isVersioned: Boolean

View File

@ -37,7 +37,6 @@ internal class CryptoSessionInfoProvider @Inject constructor(
fun isRoomEncrypted(roomId: String): Boolean {
val encryptionEvent = monarchy.fetchCopied { realm ->
EventEntity.whereType(realm, roomId = roomId, type = EventType.STATE_ROOM_ENCRYPTION)
.contains(EventEntityFields.CONTENT, "\"algorithm\":\"$MXCRYPTO_ALGORITHM_MEGOLM\"")
.isEmpty(EventEntityFields.STATE_KEY)
.findFirst()
}

View File

@ -177,7 +177,7 @@ internal class DefaultCryptoService @Inject constructor(
private val isStarted = AtomicBoolean(false)
fun onStateEvent(roomId: String, event: Event) {
when (event.getClearType()) {
when (event.type) {
EventType.STATE_ROOM_ENCRYPTION -> onRoomEncryptionEvent(roomId, event)
EventType.STATE_ROOM_MEMBER -> onRoomMembershipEvent(roomId, event)
EventType.STATE_ROOM_HISTORY_VISIBILITY -> onRoomHistoryVisibilityEvent(roomId, event)
@ -185,10 +185,13 @@ internal class DefaultCryptoService @Inject constructor(
}
fun onLiveEvent(roomId: String, event: Event) {
when (event.getClearType()) {
EventType.STATE_ROOM_ENCRYPTION -> onRoomEncryptionEvent(roomId, event)
EventType.STATE_ROOM_MEMBER -> onRoomMembershipEvent(roomId, event)
EventType.STATE_ROOM_HISTORY_VISIBILITY -> onRoomHistoryVisibilityEvent(roomId, event)
// handle state events
if (event.isStateEvent()) {
when (event.type) {
EventType.STATE_ROOM_ENCRYPTION -> onRoomEncryptionEvent(roomId, event)
EventType.STATE_ROOM_MEMBER -> onRoomMembershipEvent(roomId, event)
EventType.STATE_ROOM_HISTORY_VISIBILITY -> onRoomHistoryVisibilityEvent(roomId, event)
}
}
}
@ -575,26 +578,31 @@ internal class DefaultCryptoService @Inject constructor(
// (for now at least. Maybe we should alert the user somehow?)
val existingAlgorithm = cryptoStore.getRoomAlgorithm(roomId)
if (!existingAlgorithm.isNullOrEmpty() && existingAlgorithm != algorithm) {
Timber.tag(loggerTag.value).e("setEncryptionInRoom() : Ignoring m.room.encryption event which requests a change of config in $roomId")
if (existingAlgorithm == algorithm) {
// ignore
Timber.tag(loggerTag.value).e("setEncryptionInRoom() : Ignoring m.room.encryption for same alg ($algorithm) in $roomId")
return false
}
val encryptingClass = MXCryptoAlgorithms.hasEncryptorClassForAlgorithm(algorithm)
// Always store even if not supported
cryptoStore.storeRoomAlgorithm(roomId, algorithm)
if (!encryptingClass) {
Timber.tag(loggerTag.value).e("setEncryptionInRoom() : Unable to encrypt room $roomId with $algorithm")
return false
}
cryptoStore.storeRoomAlgorithm(roomId, algorithm!!)
val alg: IMXEncrypting = when (algorithm) {
val alg: IMXEncrypting? = when (algorithm) {
MXCRYPTO_ALGORITHM_MEGOLM -> megolmEncryptionFactory.create(roomId)
else -> olmEncryptionFactory.create(roomId)
MXCRYPTO_ALGORITHM_OLM -> olmEncryptionFactory.create(roomId)
else -> null
}
roomEncryptorsStore.put(roomId, alg)
if (alg != null) {
roomEncryptorsStore.put(roomId, alg)
}
// if encryption was not previously enabled in this room, we will have been
// ignoring new device events for these users so far. We may well have
@ -927,6 +935,7 @@ internal class DefaultCryptoService @Inject constructor(
}
private fun onRoomHistoryVisibilityEvent(roomId: String, event: Event) {
if (!event.isStateEvent()) return
val eventContent = event.content.toModel<RoomHistoryVisibilityContent>()
eventContent?.historyVisibility?.let {
cryptoStore.setShouldEncryptForInvitedMembers(roomId, it != RoomHistoryVisibility.JOINED)

View File

@ -27,7 +27,7 @@ data class EncryptionEventContent(
* Required. The encryption algorithm to be used to encrypt messages sent in this room. Must be 'm.megolm.v1.aes-sha2'.
*/
@Json(name = "algorithm")
val algorithm: String,
val algorithm: String?,
/**
* How long the session should be used before changing it. 604800000 (a week) is the recommended default.

View File

@ -230,7 +230,7 @@ internal interface IMXCryptoStore {
* @param roomId the id of the room.
* @param algorithm the algorithm.
*/
fun storeRoomAlgorithm(roomId: String, algorithm: String)
fun storeRoomAlgorithm(roomId: String, algorithm: String?)
/**
* Provides the algorithm used in a dedicated room.

View File

@ -629,7 +629,7 @@ internal class RealmCryptoStore @Inject constructor(
}
}
override fun storeRoomAlgorithm(roomId: String, algorithm: String) {
override fun storeRoomAlgorithm(roomId: String, algorithm: String?) {
doRealmTransaction(realmConfiguration) {
CryptoRoomEntity.getOrCreate(it, roomId).algorithm = algorithm
}

View File

@ -25,6 +25,7 @@ import org.matrix.android.sdk.api.session.room.model.RoomJoinRulesContent
import org.matrix.android.sdk.api.session.room.model.VersioningState
import org.matrix.android.sdk.api.session.room.model.create.RoomCreateContent
import org.matrix.android.sdk.api.session.room.model.tag.RoomTag
import org.matrix.android.sdk.internal.crypto.model.event.EncryptionEventContent
import org.matrix.android.sdk.internal.database.model.ChunkEntityFields
import org.matrix.android.sdk.internal.database.model.CurrentStateEventEntityFields
import org.matrix.android.sdk.internal.database.model.EditAggregatedSummaryEntityFields
@ -395,6 +396,7 @@ internal class RealmSessionStoreMigration @Inject constructor(
private fun migrateTo20(realm: DynamicRealm) {
Timber.d("Step 19 -> 20")
realm.schema.get("ChunkEntity")?.apply {
if (hasField("numberOfTimelineEvents")) {
removeField("numberOfTimelineEvents")
@ -413,5 +415,29 @@ internal class RealmSessionStoreMigration @Inject constructor(
chunkEntities.deleteAllFromRealm()
}
}
realm.schema.get("RoomSummaryEntity")
?.addField(RoomSummaryEntityFields.E2E_ALGORITHM, String::class.java)
?.transform { obj ->
val encryptionContentAdapter = MoshiProvider.providesMoshi().adapter(EncryptionEventContent::class.java)
val encryptionEvent = realm.where("CurrentStateEventEntity")
.equalTo(CurrentStateEventEntityFields.ROOM_ID, obj.getString(RoomSummaryEntityFields.ROOM_ID))
.equalTo(CurrentStateEventEntityFields.TYPE, EventType.STATE_ROOM_ENCRYPTION)
.findFirst()
val encryptionEventRoot = encryptionEvent?.getObject(CurrentStateEventEntityFields.ROOT.`$`)
val algorithm = encryptionEventRoot
?.getString(EventEntityFields.CONTENT)?.let {
encryptionContentAdapter.fromJson(it)?.algorithm
}
obj.setString(RoomSummaryEntityFields.E2E_ALGORITHM, algorithm)
obj.setBoolean(RoomSummaryEntityFields.IS_ENCRYPTED, encryptionEvent != null)
encryptionEventRoot?.getLong(EventEntityFields.ORIGIN_SERVER_TS)?.let {
obj.setLong(RoomSummaryEntityFields.ENCRYPTION_EVENT_TS, it)
}
}
}
}

View File

@ -16,12 +16,14 @@
package org.matrix.android.sdk.internal.database.mapper
import org.matrix.android.sdk.api.session.room.model.RoomEncryptionAlgorithm
import org.matrix.android.sdk.api.session.room.model.RoomJoinRules
import org.matrix.android.sdk.api.session.room.model.RoomSummary
import org.matrix.android.sdk.api.session.room.model.SpaceChildInfo
import org.matrix.android.sdk.api.session.room.model.SpaceParentInfo
import org.matrix.android.sdk.api.session.room.model.tag.RoomTag
import org.matrix.android.sdk.api.session.typing.TypingUsersTracker
import org.matrix.android.sdk.internal.crypto.MXCRYPTO_ALGORITHM_MEGOLM
import org.matrix.android.sdk.internal.database.model.RoomSummaryEntity
import org.matrix.android.sdk.internal.database.model.presence.toUserPresence
import javax.inject.Inject
@ -99,7 +101,13 @@ internal class RoomSummaryMapper @Inject constructor(private val timelineEventMa
worldReadable = it.childSummaryEntity?.joinRules == RoomJoinRules.PUBLIC
)
},
flattenParentIds = roomSummaryEntity.flattenParentIds?.split("|") ?: emptyList()
flattenParentIds = roomSummaryEntity.flattenParentIds?.split("|") ?: emptyList(),
roomEncryptionAlgorithm = when (val alg = roomSummaryEntity.e2eAlgorithm) {
// I should probably use #hasEncryptorClassForAlgorithm but it says it supports
// OLM which is some legacy? Now only megolm allowed in rooms
MXCRYPTO_ALGORITHM_MEGOLM -> RoomEncryptionAlgorithm.Megolm
else -> RoomEncryptionAlgorithm.UnsupportedAlgorithm(alg)
}
)
}
}

View File

@ -205,6 +205,11 @@ internal open class RoomSummaryEntity(
if (value != field) field = value
}
var e2eAlgorithm: String? = null
set(value) {
if (value != field) field = value
}
var encryptionEventTs: Long? = 0
set(value) {
if (value != field) field = value

View File

@ -119,15 +119,15 @@ internal class DefaultRoom(override val roomId: String,
}
}
override suspend fun enableEncryption(algorithm: String) {
override suspend fun enableEncryption(algorithm: String, force: Boolean) {
when {
isEncrypted() -> {
(!force && isEncrypted() && encryptionAlgorithm() == MXCRYPTO_ALGORITHM_MEGOLM) -> {
throw IllegalStateException("Encryption is already enabled for this room")
}
algorithm != MXCRYPTO_ALGORITHM_MEGOLM -> {
(!force && algorithm != MXCRYPTO_ALGORITHM_MEGOLM) -> {
throw InvalidParameterException("Only MXCRYPTO_ALGORITHM_MEGOLM algorithm is supported")
}
else -> {
else -> {
val params = SendStateTask.Params(
roomId = roomId,
stateKey = null,

View File

@ -38,13 +38,11 @@ import org.matrix.android.sdk.api.session.room.send.SendState
import org.matrix.android.sdk.api.session.sync.model.RoomSyncSummary
import org.matrix.android.sdk.api.session.sync.model.RoomSyncUnreadNotifications
import org.matrix.android.sdk.internal.crypto.EventDecryptor
import org.matrix.android.sdk.internal.crypto.MXCRYPTO_ALGORITHM_MEGOLM
import org.matrix.android.sdk.internal.crypto.crosssigning.DefaultCrossSigningService
import org.matrix.android.sdk.internal.crypto.model.event.EncryptionEventContent
import org.matrix.android.sdk.internal.database.mapper.ContentMapper
import org.matrix.android.sdk.internal.database.mapper.asDomain
import org.matrix.android.sdk.internal.database.model.CurrentStateEventEntity
import org.matrix.android.sdk.internal.database.model.EventEntity
import org.matrix.android.sdk.internal.database.model.EventEntityFields
import org.matrix.android.sdk.internal.database.model.GroupSummaryEntity
import org.matrix.android.sdk.internal.database.model.RoomMemberSummaryEntityFields
import org.matrix.android.sdk.internal.database.model.RoomSummaryEntity
@ -57,7 +55,6 @@ import org.matrix.android.sdk.internal.database.query.getOrCreate
import org.matrix.android.sdk.internal.database.query.getOrNull
import org.matrix.android.sdk.internal.database.query.isEventRead
import org.matrix.android.sdk.internal.database.query.where
import org.matrix.android.sdk.internal.database.query.whereType
import org.matrix.android.sdk.internal.di.UserId
import org.matrix.android.sdk.internal.extensions.clearWith
import org.matrix.android.sdk.internal.query.process
@ -123,10 +120,8 @@ internal class RoomSummaryUpdater @Inject constructor(
Timber.v("## Space: Updating summary room [$roomId] roomType: [$roomType]")
// Don't use current state for this one as we are only interested in having MXCRYPTO_ALGORITHM_MEGOLM event in the room
val encryptionEvent = EventEntity.whereType(realm, roomId = roomId, type = EventType.STATE_ROOM_ENCRYPTION)
.contains(EventEntityFields.CONTENT, "\"algorithm\":\"$MXCRYPTO_ALGORITHM_MEGOLM\"")
.isNotNull(EventEntityFields.STATE_KEY)
.findFirst()
val encryptionEvent = CurrentStateEventEntity.getOrNull(realm, roomId, type = EventType.STATE_ROOM_ENCRYPTION, stateKey = "")?.root
Timber.v("## CRYPTO: currentEncryptionEvent is $encryptionEvent")
val latestPreviewableEvent = RoomSummaryEventsHelper.getLatestPreviewableEvent(realm, roomId)
@ -152,6 +147,11 @@ internal class RoomSummaryUpdater @Inject constructor(
.orEmpty()
roomSummaryEntity.updateAliases(roomAliases)
roomSummaryEntity.isEncrypted = encryptionEvent != null
roomSummaryEntity.e2eAlgorithm = ContentMapper.map(encryptionEvent?.content)
?.toModel<EncryptionEventContent>()
?.algorithm
roomSummaryEntity.encryptionEventTs = encryptionEvent?.originServerTs
if (roomSummaryEntity.membership == Membership.INVITE && inviterId != null) {

View File

@ -221,6 +221,7 @@ internal class RoomSyncHandler @Inject constructor(private val readReceiptHandle
}
val ageLocalTs = event.unsignedData?.age?.let { syncLocalTimestampMillis - it }
val eventEntity = event.toEntity(roomId, SendState.SYNCED, ageLocalTs).copyToRealmOrIgnore(realm, insertType)
Timber.v("## received state event ${event.type} and key ${event.stateKey}")
CurrentStateEventEntity.getOrCreate(realm, roomId, event.stateKey, event.type).apply {
// Timber.v("## Space state event: $eventEntity")
eventId = event.eventId
@ -393,6 +394,7 @@ internal class RoomSyncHandler @Inject constructor(private val readReceiptHandle
roomMemberEventHandler.handle(realm, roomEntity.roomId, event.stateKey, fixedContent, aggregator)
}
}
roomMemberContentsByUser.getOrPut(event.senderId) {
// If we don't have any new state on this user, get it from db
val rootStateEvent = CurrentStateEventEntity.getOrNull(realm, roomId, event.senderId, EventType.STATE_ROOM_MEMBER)?.root

View File

@ -73,6 +73,7 @@ class NotificationAreaView @JvmOverloads constructor(
is State.Default -> renderDefault()
is State.Hidden -> renderHidden()
is State.NoPermissionToPost -> renderNoPermissionToPost()
is State.UnsupportedAlgorithm -> renderUnsupportedAlgorithm()
is State.Tombstone -> renderTombstone()
is State.ResourceLimitExceededError -> renderResourceLimitExceededError(newState)
}.exhaustive
@ -106,6 +107,18 @@ class NotificationAreaView @JvmOverloads constructor(
views.roomNotificationMessage.setTextColor(ThemeUtils.getColor(context, R.attr.vctr_content_secondary))
}
private fun renderUnsupportedAlgorithm() {
visibility = View.VISIBLE
views.roomNotificationIcon.setImageResource(R.drawable.ic_shield_warning_small)
val message = span {
italic {
+resources.getString(R.string.room_unsupported_e2e_algorithm)
}
}
views.roomNotificationMessage.text = message
views.roomNotificationMessage.setTextColor(ThemeUtils.getColor(context, R.attr.vctr_content_secondary))
}
private fun renderResourceLimitExceededError(state: State.ResourceLimitExceededError) {
visibility = View.VISIBLE
val resourceLimitErrorFormatter = ResourceLimitErrorFormatter(context)
@ -163,6 +176,7 @@ class NotificationAreaView @JvmOverloads constructor(
// User can't post messages to room because his power level doesn't allow it.
object NoPermissionToPost : State()
object UnsupportedAlgorithm : State()
// View will be Gone
object Hidden : State()

View File

@ -133,12 +133,14 @@ import im.vector.app.features.command.Command
import im.vector.app.features.crypto.keysbackup.restore.KeysBackupRestoreActivity
import im.vector.app.features.crypto.verification.VerificationBottomSheet
import im.vector.app.features.home.AvatarRenderer
import im.vector.app.features.home.room.detail.composer.CanSendStatus
import im.vector.app.features.home.room.detail.composer.MessageComposerAction
import im.vector.app.features.home.room.detail.composer.MessageComposerView
import im.vector.app.features.home.room.detail.composer.MessageComposerViewEvents
import im.vector.app.features.home.room.detail.composer.MessageComposerViewModel
import im.vector.app.features.home.room.detail.composer.MessageComposerViewState
import im.vector.app.features.home.room.detail.composer.SendMode
import im.vector.app.features.home.room.detail.composer.boolean
import im.vector.app.features.home.room.detail.composer.voice.VoiceMessageRecorderView
import im.vector.app.features.home.room.detail.composer.voice.VoiceMessageRecorderView.RecordingUiState
import im.vector.app.features.home.room.detail.readreceipts.DisplayReadReceiptsBottomSheet
@ -392,7 +394,7 @@ class RoomDetailFragment @Inject constructor(
}
messageComposerViewModel.onEach(MessageComposerViewState::sendMode, MessageComposerViewState::canSendMessage) { mode, canSend ->
if (!canSend) {
if (!canSend.boolean()) {
return@onEach
}
when (mode) {
@ -1268,7 +1270,7 @@ class RoomDetailFragment @Inject constructor(
val canSendMessage = withState(messageComposerViewModel) {
it.canSendMessage
}
if (!canSendMessage) {
if (!canSendMessage.boolean()) {
return false
}
return when (model) {
@ -1446,10 +1448,18 @@ class RoomDetailFragment @Inject constructor(
views.voiceMessageRecorderView.render(messageComposerState.voiceRecordingUiState)
views.composerLayout.setRoomEncrypted(summary.isEncrypted)
// views.composerLayout.alwaysShowSendButton = false
if (messageComposerState.canSendMessage) {
views.notificationAreaView.render(NotificationAreaView.State.Hidden)
} else {
views.notificationAreaView.render(NotificationAreaView.State.NoPermissionToPost)
when (messageComposerState.canSendMessage) {
CanSendStatus.Allowed -> {
NotificationAreaView.State.Hidden
}
CanSendStatus.NoPermission -> {
NotificationAreaView.State.NoPermissionToPost
}
is CanSendStatus.UnSupportedE2eAlgorithm -> {
NotificationAreaView.State.UnsupportedAlgorithm
}
}.let {
views.notificationAreaView.render(it)
}
} else {
views.hideComposerViews()

View File

@ -38,6 +38,7 @@ import im.vector.app.features.session.coroutineScope
import im.vector.app.features.settings.VectorPreferences
import im.vector.app.features.voice.VoicePlayerHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.query.QueryStringValue
import org.matrix.android.sdk.api.session.Session
@ -47,6 +48,7 @@ import org.matrix.android.sdk.api.session.events.model.toContent
import org.matrix.android.sdk.api.session.events.model.toModel
import org.matrix.android.sdk.api.session.room.model.PowerLevelsContent
import org.matrix.android.sdk.api.session.room.model.RoomAvatarContent
import org.matrix.android.sdk.api.session.room.model.RoomEncryptionAlgorithm
import org.matrix.android.sdk.api.session.room.model.RoomMemberContent
import org.matrix.android.sdk.api.session.room.model.message.MessageType
import org.matrix.android.sdk.api.session.room.powerlevels.PowerLevelsHelper
@ -55,6 +57,8 @@ import org.matrix.android.sdk.api.session.room.timeline.getLastMessageContent
import org.matrix.android.sdk.api.session.room.timeline.getRelationContent
import org.matrix.android.sdk.api.session.room.timeline.getTextEditableContent
import org.matrix.android.sdk.api.session.space.CreateSpaceParams
import org.matrix.android.sdk.flow.flow
import org.matrix.android.sdk.flow.unwrap
import timber.log.Timber
class MessageComposerViewModel @AssistedInject constructor(
@ -74,7 +78,7 @@ class MessageComposerViewModel @AssistedInject constructor(
init {
loadDraftIfAny()
observePowerLevel()
observePowerLevelAndEncryption()
subscribeToStateInternal()
}
@ -137,12 +141,30 @@ class MessageComposerViewModel @AssistedInject constructor(
}
}
private fun observePowerLevel() {
PowerLevelsFlowFactory(room).createFlow()
.setOnEach {
val canSendMessage = PowerLevelsHelper(it).isUserAllowedToSend(session.myUserId, false, EventType.MESSAGE)
copy(canSendMessage = canSendMessage)
private fun observePowerLevelAndEncryption() {
combine(
PowerLevelsFlowFactory(room).createFlow(),
room.flow().liveRoomSummary().unwrap()
) { pl, sum ->
val canSendMessage = PowerLevelsHelper(pl).isUserAllowedToSend(session.myUserId, false, EventType.MESSAGE)
if (canSendMessage) {
val isE2E = sum.isEncrypted
if (isE2E) {
val roomEncryptionAlgorithm = sum.roomEncryptionAlgorithm
if (roomEncryptionAlgorithm is RoomEncryptionAlgorithm.UnsupportedAlgorithm) {
CanSendStatus.UnSupportedE2eAlgorithm(roomEncryptionAlgorithm.name)
} else {
CanSendStatus.Allowed
}
} else {
CanSendStatus.Allowed
}
} else {
CanSendStatus.NoPermission
}
}.setOnEach {
copy(canSendMessage = it)
}
}
private fun handleEnterQuoteMode(action: MessageComposerAction.EnterQuoteMode) {

View File

@ -43,9 +43,23 @@ sealed interface SendMode {
data class Voice(val text: String) : SendMode
}
sealed class CanSendStatus {
object Allowed : CanSendStatus()
object NoPermission : CanSendStatus()
data class UnSupportedE2eAlgorithm(val algorithm: String?) : CanSendStatus()
}
fun CanSendStatus.boolean(): Boolean {
return when (this) {
CanSendStatus.Allowed -> true
CanSendStatus.NoPermission -> false
is CanSendStatus.UnSupportedE2eAlgorithm -> false
}
}
data class MessageComposerViewState(
val roomId: String,
val canSendMessage: Boolean = true,
val canSendMessage: CanSendStatus = CanSendStatus.Allowed,
val isSendButtonVisible: Boolean = false,
val sendMode: SendMode = SendMode.Regular("", false),
val voiceRecordingUiState: VoiceMessageRecorderView.RecordingUiState = VoiceMessageRecorderView.RecordingUiState.Idle
@ -60,8 +74,8 @@ data class MessageComposerViewState(
val isVoiceMessageIdle = !isVoiceRecording
val isComposerVisible = canSendMessage && !isVoiceRecording
val isVoiceMessageRecorderVisible = canSendMessage && !isSendButtonVisible
val isComposerVisible = canSendMessage.boolean() && !isVoiceRecording
val isVoiceMessageRecorderVisible = canSendMessage.boolean() && !isSendButtonVisible
@Suppress("UNUSED") // needed by mavericks
constructor(args: RoomDetailArgs) : this(roomId = args.roomId)

View File

@ -63,7 +63,7 @@ class EncryptionItemFactory @Inject constructor(
)
shield = StatusTileTimelineItem.ShieldUIState.BLACK
} else {
title = stringProvider.getString(R.string.encryption_not_enabled)
title = stringProvider.getString(R.string.encryption_misconfigured)
description = stringProvider.getString(R.string.encryption_unknown_algorithm_tile_description)
shield = StatusTileTimelineItem.ShieldUIState.RED
}

View File

@ -95,11 +95,14 @@ class RoomMemberProfileController @Inject constructor(
private fun buildSecuritySection(state: RoomMemberProfileViewState) {
// Security
buildProfileSection(stringProvider.getString(R.string.room_profile_section_security))
val host = this
if (state.isRoomEncrypted) {
if (state.userMXCrossSigningInfo != null) {
if (!state.isAlgorithmSupported) {
// TODO find sensible message to display here
// For now we just remove the verify actions as well as the Security status
} else if (state.userMXCrossSigningInfo != null) {
buildProfileSection(stringProvider.getString(R.string.room_profile_section_security))
// Cross signing is enabled for this user
if (state.userMXCrossSigningInfo.isTrusted()) {
// User is trusted
@ -152,6 +155,8 @@ class RoomMemberProfileController @Inject constructor(
}
}
} else {
buildProfileSection(stringProvider.getString(R.string.room_profile_section_security))
buildProfileAction(
id = "learn_more",
title = stringProvider.getString(R.string.room_profile_section_security_learn_more),
@ -162,6 +167,8 @@ class RoomMemberProfileController @Inject constructor(
)
}
} else {
buildProfileSection(stringProvider.getString(R.string.room_profile_section_security))
genericFooterItem {
id("verify_footer_not_encrypted")
text(host.stringProvider.getString(R.string.room_profile_not_encrypted_subtitle))

View File

@ -52,6 +52,7 @@ import org.matrix.android.sdk.api.session.profile.ProfileService
import org.matrix.android.sdk.api.session.room.Room
import org.matrix.android.sdk.api.session.room.members.roomMemberQueryParams
import org.matrix.android.sdk.api.session.room.model.Membership
import org.matrix.android.sdk.api.session.room.model.RoomEncryptionAlgorithm
import org.matrix.android.sdk.api.session.room.model.RoomType
import org.matrix.android.sdk.api.session.room.powerlevels.PowerLevelsHelper
import org.matrix.android.sdk.api.session.room.powerlevels.Role
@ -344,7 +345,15 @@ class RoomMemberProfileViewModel @AssistedInject constructor(
}.launchIn(viewModelScope)
roomSummaryLive.execute {
copy(isRoomEncrypted = it.invoke()?.isEncrypted == true)
val summary = it.invoke() ?: return@execute this
if (summary.isEncrypted) {
copy(
isRoomEncrypted = true,
isAlgorithmSupported = summary.roomEncryptionAlgorithm is RoomEncryptionAlgorithm.SupportedAlgorithm
)
} else {
copy(isRoomEncrypted = false)
}
}
roomSummaryLive.combine(powerLevelsContentLive) { roomSummary, powerLevelsContent ->
val roomName = roomSummary.toMatrixItem().getBestName()

View File

@ -33,6 +33,7 @@ data class RoomMemberProfileViewState(
val isMine: Boolean = false,
val isIgnored: Async<Boolean> = Uninitialized,
val isRoomEncrypted: Boolean = false,
val isAlgorithmSupported: Boolean = true,
val powerLevelsContent: PowerLevelsContent? = null,
val userPowerLevelString: Async<String> = Uninitialized,
val userMatrixItem: Async<MatrixItem> = Uninitialized,

View File

@ -26,4 +26,5 @@ sealed class RoomProfileAction : VectorViewModelAction {
data class ChangeRoomNotificationState(val notificationState: RoomNotificationState) : RoomProfileAction()
object ShareRoomProfile : RoomProfileAction()
object CreateShortcut : RoomProfileAction()
object RestoreEncryptionState : RoomProfileAction()
}

View File

@ -23,6 +23,7 @@ import im.vector.app.core.epoxy.expandableTextItem
import im.vector.app.core.epoxy.profiles.buildProfileAction
import im.vector.app.core.epoxy.profiles.buildProfileSection
import im.vector.app.core.resources.ColorProvider
import im.vector.app.core.resources.DrawableProvider
import im.vector.app.core.resources.StringProvider
import im.vector.app.core.ui.list.genericFooterItem
import im.vector.app.core.ui.list.genericPositiveButtonItem
@ -30,7 +31,10 @@ import im.vector.app.features.home.ShortcutCreator
import im.vector.app.features.home.room.detail.timeline.TimelineEventController
import im.vector.app.features.home.room.detail.timeline.tools.createLinkMovementMethod
import im.vector.app.features.settings.VectorPreferences
import me.gujun.android.span.image
import me.gujun.android.span.span
import org.matrix.android.sdk.api.crypto.RoomEncryptionTrustLevel
import org.matrix.android.sdk.api.session.room.model.RoomEncryptionAlgorithm
import org.matrix.android.sdk.api.session.room.model.RoomSummary
import javax.inject.Inject
@ -38,6 +42,7 @@ class RoomProfileController @Inject constructor(
private val stringProvider: StringProvider,
private val colorProvider: ColorProvider,
private val vectorPreferences: VectorPreferences,
private val drawableProvider: DrawableProvider,
private val shortcutCreator: ShortcutCreator
) : TypedEpoxyController<RoomProfileViewState>() {
@ -59,6 +64,7 @@ class RoomProfileController @Inject constructor(
fun onRoomDevToolsClicked()
fun onUrlInTopicLongClicked(url: String)
fun doMigrateToVersion(newVersion: String)
fun restoreEncryptionState()
}
override fun buildModels(data: RoomProfileViewState?) {
@ -113,15 +119,44 @@ class RoomProfileController @Inject constructor(
}
}
var encryptionMisconfigured = false
val learnMoreSubtitle = if (roomSummary.isEncrypted) {
if (roomSummary.isDirect) R.string.direct_room_profile_encrypted_subtitle else R.string.room_profile_encrypted_subtitle
if (roomSummary.roomEncryptionAlgorithm is RoomEncryptionAlgorithm.SupportedAlgorithm) {
if (roomSummary.isDirect) R.string.direct_room_profile_encrypted_subtitle else R.string.room_profile_encrypted_subtitle
} else {
encryptionMisconfigured = true
if (roomSummary.isDirect) R.string.direct_room_profile_encrypted_misconfigured_subtitle else R.string.room_profile_encrypted_misconfigured_subtitle
}
} else {
if (roomSummary.isDirect) R.string.direct_room_profile_not_encrypted_subtitle else R.string.room_profile_not_encrypted_subtitle
}
genericFooterItem {
id("e2e info")
centered(false)
text(host.stringProvider.getString(learnMoreSubtitle))
text(
span {
apply {
if (encryptionMisconfigured) {
host.drawableProvider.getDrawable(R.drawable.ic_warning_badge)?.let {
image(it, "baseline")
}
+" "
}
}
+host.stringProvider.getString(learnMoreSubtitle)
}
)
}
if (encryptionMisconfigured && data.canUpdateRoomState) {
genericPositiveButtonItem {
id("restore_encryption")
text(host.stringProvider.getString(R.string.room_profile_section_restore_security))
iconRes(R.drawable.ic_shield_black_no_border)
buttonClickAction {
host.callback?.restoreEncryptionState()
}
}
}
buildEncryptionAction(data.actionPermissions, roomSummary)

View File

@ -121,6 +121,7 @@ class RoomProfileFragment @Inject constructor(
is RoomProfileViewEvents.Failure -> showFailure(it.throwable)
is RoomProfileViewEvents.ShareRoomProfile -> onShareRoomProfile(it.permalink)
is RoomProfileViewEvents.OnShortcutReady -> addShortcut(it)
RoomProfileViewEvents.DismissLoading -> dismissLoadingDialog()
}.exhaustive
}
roomListQuickActionsSharedActionViewModel
@ -299,6 +300,10 @@ class RoomProfileFragment @Inject constructor(
roomProfileSharedActionViewModel.post(RoomProfileSharedAction.OpenRoomPermissionsSettings)
}
override fun restoreEncryptionState() {
roomProfileViewModel.handle(RoomProfileAction.RestoreEncryptionState)
}
override fun onRoomIdClicked() {
copyToClipboard(requireContext(), roomProfileArgs.roomId)
}

View File

@ -24,6 +24,7 @@ import im.vector.app.core.platform.VectorViewEvents
*/
sealed class RoomProfileViewEvents : VectorViewEvents {
data class Loading(val message: CharSequence? = null) : RoomProfileViewEvents()
object DismissLoading : RoomProfileViewEvents()
data class Failure(val throwable: Throwable) : RoomProfileViewEvents()
data class ShareRoomProfile(val permalink: String) : RoomProfileViewEvents()

View File

@ -29,7 +29,10 @@ import im.vector.app.core.platform.VectorViewModel
import im.vector.app.core.resources.StringProvider
import im.vector.app.features.home.ShortcutCreator
import im.vector.app.features.powerlevel.PowerLevelsFlowFactory
import im.vector.app.features.session.coroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.query.QueryStringValue
import org.matrix.android.sdk.api.session.Session
@ -44,6 +47,7 @@ import org.matrix.android.sdk.flow.FlowRoom
import org.matrix.android.sdk.flow.flow
import org.matrix.android.sdk.flow.mapOptional
import org.matrix.android.sdk.flow.unwrap
import timber.log.Timber
class RoomProfileViewModel @AssistedInject constructor(
@Assisted private val initialState: RoomProfileViewState,
@ -67,6 +71,19 @@ class RoomProfileViewModel @AssistedInject constructor(
observeRoomCreateContent(flowRoom)
observeBannedRoomMembers(flowRoom)
observePermissions()
obeservePowerLevels()
}
private fun obeservePowerLevels() {
val powerLevelsContentLive = PowerLevelsFlowFactory(room).createFlow()
powerLevelsContentLive
.onEach {
val powerLevelsHelper = PowerLevelsHelper(it)
val canUpdateRoomState = powerLevelsHelper.isUserAllowedToSend(session.myUserId, true, EventType.STATE_ROOM_ENCRYPTION)
setState {
copy(canUpdateRoomState = canUpdateRoomState)
}
}.launchIn(viewModelScope)
}
private fun observeRoomCreateContent(flowRoom: FlowRoom) {
@ -119,6 +136,7 @@ class RoomProfileViewModel @AssistedInject constructor(
is RoomProfileAction.ChangeRoomNotificationState -> handleChangeNotificationMode(action)
is RoomProfileAction.ShareRoomProfile -> handleShareRoomProfile()
RoomProfileAction.CreateShortcut -> handleCreateShortcut()
RoomProfileAction.RestoreEncryptionState -> restoreEncryptionState()
}.exhaustive
}
@ -182,4 +200,17 @@ class RoomProfileViewModel @AssistedInject constructor(
_viewEvents.post(RoomProfileViewEvents.ShareRoomProfile(permalink))
}
}
private fun restoreEncryptionState() {
_viewEvents.post(RoomProfileViewEvents.Loading())
session.coroutineScope.launch {
try {
room.enableEncryption(force = true)
} catch (failure: Throwable) {
Timber.e(failure, "Failed to restore encryption state in room ${room.roomId}")
} finally {
_viewEvents.post(RoomProfileViewEvents.DismissLoading)
}
}
}
}

View File

@ -34,7 +34,8 @@ data class RoomProfileViewState(
val isUsingUnstableRoomVersion: Boolean = false,
val recommendedRoomVersion: String? = null,
val canUpgradeRoom: Boolean = false,
val isTombstoned: Boolean = false
val isTombstoned: Boolean = false,
val canUpdateRoomState: Boolean = false
) : MavericksState {
constructor(args: RoomProfileArgs) : this(roomId = args.roomId)

View File

@ -962,6 +962,7 @@
<string name="room_delete_unsent_messages">Delete unsent messages</string>
<string name="room_message_file_not_found">File not found</string>
<string name="room_do_not_have_permission_to_post">You do not have permission to post to this room.</string>
<string name="room_unsupported_e2e_algorithm">Encryption has been misconfigured. You can\'t send messages, please contact an admin to restore the room to a valid state.</string>
<plurals name="room_new_messages_notification">
<item quantity="one">%d new message</item>
<item quantity="other">%d new messages</item>
@ -2790,8 +2791,11 @@
<string name="room_profile_not_encrypted_subtitle">Messages in this room are not end-to-end encrypted.</string>
<string name="direct_room_profile_not_encrypted_subtitle">Messages here are not end-to-end encrypted.</string>
<string name="room_profile_encrypted_subtitle">Messages in this room are end-to-end encrypted.\n\nYour messages are secured with locks and only you and the recipient have the unique keys to unlock them.</string>
<string name="room_profile_encrypted_misconfigured_subtitle">Encryption has been misconfigured. Please contact an admin to restore the room to a valid state.</string>
<string name="direct_room_profile_encrypted_misconfigured_subtitle">Encryption has been misconfigured. Please contact an admin to restore room.</string>
<string name="direct_room_profile_encrypted_subtitle">Messages here are end-to-end encrypted.\n\nYour messages are secured with locks and only you and the recipient have the unique keys to unlock them.</string>
<string name="room_profile_section_security">Security</string>
<string name="room_profile_section_restore_security">Restore Encryption</string>
<string name="room_profile_section_security_learn_more">Learn more</string>
<string name="room_profile_section_more">More</string>
<string name="room_profile_section_admin">Admin Actions</string>
@ -3052,6 +3056,7 @@
<string name="encryption_enabled_tile_description">Messages in this room are end-to-end encrypted. Learn more &amp; verify users in their profile.</string>
<string name="direct_room_encryption_enabled_tile_description">Messages in this room are end-to-end encrypted.</string>
<string name="encryption_not_enabled">Encryption not enabled</string>
<string name="encryption_misconfigured">Encryption is misconfigured</string>
<string name="encryption_unknown_algorithm_tile_description">The encryption used by this room is not supported</string>
<string name="room_created_summary_item">%s created and configured the room.</string>