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

Fix MM 56723 #7883

Merged
merged 11 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
10 changes: 9 additions & 1 deletion app/init/push_notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import EphemeralStore from '@store/ephemeral_store';
import NavigationStore from '@store/navigation_store';
import {isBetaApp} from '@utils/general';
import {isMainActivity, isTablet} from '@utils/helpers';
import {logInfo} from '@utils/log';
import {logDebug, logInfo} from '@utils/log';
import {convertToNotificationData} from '@utils/notification';

class PushNotifications {
Expand Down Expand Up @@ -232,6 +232,10 @@ class PushNotifications {

// This triggers when the app was in the background (iOS)
onNotificationReceivedBackground = async (incoming: Notification, completion: (response: NotificationBackgroundFetchResult) => void) => {
if (incoming.payload.verified === 'false') {
logDebug('not handling background notification because it was not verified, ackId=', incoming.payload.ackId);
return;
}
const notification = convertToNotificationData(incoming, false);
this.processNotification(notification);

Expand All @@ -241,6 +245,10 @@ class PushNotifications {
// This triggers when the app was in the foreground (Android and iOS)
// Also triggers when the app was in the background (Android)
onNotificationReceivedForeground = (incoming: Notification, completion: (response: NotificationCompletion) => void) => {
if (incoming.payload.verified === 'false') {
logDebug('not handling foreground notification because it was not verified, ackId=', incoming.payload.ackId);
return;
}
const notification = convertToNotificationData(incoming, false);
if (AppState.currentState !== 'inactive') {
notification.foreground = AppState.currentState === 'active' && isMainActivity();
Expand Down
6 changes: 4 additions & 2 deletions ios/Gekidou/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,17 @@ let package = Package(
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/stephencelis/SQLite.swift.git", from: "0.14.1")
.package(url: "https://github.com/stephencelis/SQLite.swift.git", from: "0.14.1"),
.package(url: "https://github.com/Kitura/Swift-JWT.git", from:"3.6.1")
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "Gekidou",
dependencies: [
.product(name: "SQLite", package: "SQLite.swift")
.product(name: "SQLite", package: "SQLite.swift"),
.product(name: "SwiftJWT", package: "Swift-JWT"),
]
),
.testTarget(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import Foundation
import UserNotifications
import os.log
import SwiftJWT

struct NotificationClaims : Claims {
var ack_id: String;
var device_id: String;
}

extension PushNotification {
public func verifySignatureFromNotification(_ notification: UNMutableNotificationContent) -> Bool {
return self.verifySignature(notification.userInfo)
}
public func verifySignature(_ userInfo: [AnyHashable : Any]) -> Bool {
guard let signature = userInfo["signature"] as? String
else {
os_log(
OSLogType.default,
"Mattermost Notifications: Signature verification: No signature in the notification"
)
return true
enahum marked this conversation as resolved.
Show resolved Hide resolved
}

guard let serverId = userInfo["server_id"] as? String
else {
os_log(
OSLogType.default,
"Mattermost Notifications: Signature verification: No server_id in the notification"
)
return false
}

guard let serverUrl = try? Database.default.getServerUrlForServer(serverId)
else {
os_log(
OSLogType.default,
"Mattermost Notifications: Signature verification: No server_url for server_id"
)
return false
}

if signature == "NO_SIGNATURE" {
guard let version = Database.default.getConfig(serverUrl, "Version")
else {
os_log(
OSLogType.default,
"Mattermost Notifications: Signature verification: No server version"
)
return false
}

// Verify server version
}

guard let signingKey = Database.default.getConfig(serverUrl, "AsymmetricSigningPublicKey")
else {
os_log(
OSLogType.default,
"Mattermost Notifications: Signature verification: No signing key"
)
return false
}

let keyPEM = """
-----BEGIN PUBLIC KEY-----
\(signingKey)
-----END PUBLIC KEY-----
"""
let jwtVerifier = JWTVerifier.es256(publicKey: keyPEM.data(using: .utf8)!)
guard let newJWT = try? JWT<NotificationClaims>(jwtString: signature, verifier: jwtVerifier)
else {
os_log(
OSLogType.default,
"Mattermost Notifications: Signature verification: Cannot verify the signature"
)
return false
}

guard let ackId = userInfo["ack_id"] as? String
else {
os_log(
OSLogType.default,
"Mattermost Notifications: Signature verification: No ack_id in the notification"
)
return false
}

if (ackId != newJWT.claims.ack_id) {
os_log(
OSLogType.default,
"Mattermost Notifications: Signature verification: ackId is different"
)
return false
}

guard let storedDeviceToken = Database.default.getDeviceToken()
enahum marked this conversation as resolved.
Show resolved Hide resolved
else {
os_log(
OSLogType.default,
"Mattermost Notifications: Signature verification: No device token"
)
return false
}

let tokenParts = storedDeviceToken.components(separatedBy: ":")
if (tokenParts.count != 2) {
os_log(
OSLogType.default,
"Mattermost Notifications: Signature verification: Wrong stored deviced token format"
)
return false
}
let deviceToken = tokenParts[1].dropLast(1)
if (deviceToken.isEmpty) {
os_log(
OSLogType.default,
"Mattermost Notifications: Signature verification: Empty stored deviced token"
)
return false
}

if (deviceToken != newJWT.claims.device_id) {
os_log(
OSLogType.default,
"Mattermost Notifications: Signature verification: Device token is different"
)
return false
}

return true
}
}
13 changes: 13 additions & 0 deletions ios/Gekidou/Sources/Gekidou/Storage/Database+System.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,19 @@ import Foundation
import SQLite

extension Database {
public func getDeviceToken() -> String? {
if let db = try? Connection(DEFAULT_DB_PATH) {
let idCol = Expression<String>("id")
let valueCol = Expression<String>("value")
let query = globalTable.select(valueCol).filter(idCol == "deviceToken")
if let result = try? db.pluck(query) {
return try? result.get(valueCol)
}
}

return nil
}

public func getConfig(_ serverUrl: String, _ key: String) -> String? {
if let db = try? getDatabaseForServer(serverUrl) {
let id = Expression<String>("id")
Expand Down
1 change: 1 addition & 0 deletions ios/Gekidou/Sources/Gekidou/Storage/Database.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public class Database: NSObject {
internal var defaultDB: OpaquePointer? = nil

internal var serversTable = Table("Servers")
internal var globalTable = Table("Global")
internal var systemTable = Table("System")
internal var teamTable = Table("Team")
internal var myTeamTable = Table("MyTeam")
Expand Down
4 changes: 4 additions & 0 deletions ios/GekidouWrapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ import Gekidou
})
}

@objc func verifySignature(_ notification: [AnyHashable:Any]) -> Bool {
return PushNotification.default.verifySignature(notification)
}

@objc func attachSession(_ id: String, completionHandler: @escaping () -> Void) {
let shareExtension = ShareExtension()
shareExtension.attachSession(
Expand Down
Loading
Loading