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

Clen 1435 #137

Merged
merged 5 commits into from
Aug 14, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
5 changes: 2 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,12 @@ dependencies {
implementation "com.squareup.retrofit2:converter-gson:2.9.0"

implementation 'org.json:json:20230227'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.14.2'
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-cbor:2.14.2'
implementation 'com.fasterxml.jackson.module:jackson-module-kotlin:2.14.2'

implementation "org.slf4j:slf4j-api:1.7.30"

api 'com.squareup.okhttp3:logging-interceptor:4.9.3'
api 'com.google.code.gson:gson:2.9.0'
implementation 'co.nstant.in:cbor:0.9'

allTest "com.github.tomakehurst:wiremock:2.27.2"

Expand All @@ -84,6 +82,7 @@ dependencies {
testImplementation group: 'io.cucumber', name: 'cucumber-java', version: '6.10.4'
testImplementation group: 'io.cucumber', name: 'cucumber-junit', version: '6.10.4'
testImplementation group: 'io.cucumber', name: 'cucumber-picocontainer', version: '6.10.4'
testImplementation 'com.fasterxml.jackson.core:jackson-databind:2.14.2'
integrationTestImplementation(testFixtures(project(":")))

allTest "org.awaitility:awaitility-kotlin:4.0.3"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@ open class PublishFileMessage(

@Throws(PubNubException::class)
override fun doWork(queryParams: HashMap<String, String>): Call<List<Any>> {
val stringifiedMessage: String = pubnub.mapper.toJsonUsingJackson(FileUploadNotification(message, pnFile))
val stringifiedMessage: String = pubnub.mapper.toJson(FileUploadNotification(message, pnFile))
val messageAsString = if (pubnub.configuration.cipherKey.isValid()) {
val crypto = Crypto(pubnub.configuration.cipherKey, pubnub.configuration.useRandomInitializationVector)
crypto.encrypt(stringifiedMessage).quoted()
} else {
stringifiedMessage
}
meta?.let {
val stringifiedMeta: String = pubnub.mapper.toJsonUsingJackson(it)
val stringifiedMeta: String = pubnub.mapper.toJson(it)
queryParams["meta"] = stringifiedMeta
}
shouldStore?.numericString?.let { queryParams["store"] = it }
Expand Down
12 changes: 0 additions & 12 deletions src/main/kotlin/com/pubnub/api/managers/MapperManager.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.pubnub.api.managers

import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonArray
Expand Down Expand Up @@ -29,7 +27,6 @@ class MapperManager {

private val objectMapper: Gson
internal val converterFactory: Converter.Factory
private val jacksonObjectMapper = jacksonObjectMapper()

init {
val booleanAsIntAdapter = object : TypeAdapter<Boolean>() {
Expand Down Expand Up @@ -63,15 +60,6 @@ class MapperManager {
converterFactory = GsonConverterFactory.create(objectMapper)
}

@Throws(PubNubException::class)
fun toJsonUsingJackson(input: Any): String {
return try {
this.jacksonObjectMapper.writeValueAsString(input)
} catch (e: JsonProcessingException) {
throw PubNubException(PubNubError.JSON_ERROR).copy(errorMessage = e.message ?: PubNubError.JSON_ERROR.message)
}
}

fun hasField(element: JsonElement, field: String) = element.asJsonObject.has(field)

fun getField(element: JsonElement?, field: String): JsonElement? {
Expand Down
120 changes: 106 additions & 14 deletions src/main/kotlin/com/pubnub/api/managers/TokenParser.kt
Original file line number Diff line number Diff line change
@@ -1,29 +1,121 @@
package com.pubnub.api.managers

import com.fasterxml.jackson.annotation.JsonSetter
import com.fasterxml.jackson.annotation.Nulls
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.cbor.CBORFactory
import co.nstant.`in`.cbor.CborDecoder
import co.nstant.`in`.cbor.model.ByteString
import co.nstant.`in`.cbor.model.NegativeInteger
import co.nstant.`in`.cbor.model.UnsignedInteger
import com.pubnub.api.PubNubError
import com.pubnub.api.PubNubException
import com.pubnub.api.models.consumer.access_manager.v3.PNToken
import com.pubnub.api.vendor.Base64
import java.io.IOException
import java.math.BigInteger
import java.nio.charset.StandardCharsets
import kotlin.collections.Map
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.set
import co.nstant.`in`.cbor.model.Map as CborMap

internal class TokenParser {
private val mapper = ObjectMapper(CBORFactory()).apply {
configOverride(Map::class.java).setterInfo = JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY)
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
}

fun unwrapToken(token: String): PNToken {
val byteArray = Base64.decode(token.toByteArray(StandardCharsets.UTF_8), Base64.URL_SAFE)
val firstElement = CborDecoder(byteArray.inputStream()).decode().firstOrNull() ?: throw PubNubException(
pubnubError = PubNubError.INVALID_ACCESS_TOKEN, errorMessage = "Empty token"
)
val firstLevelMap = (firstElement as? CborMap)?.toJvmMap() ?: throw PubNubException(
pubnubError = PubNubError.INVALID_ACCESS_TOKEN, errorMessage = "First element is not a map"
)
val version = firstLevelMap[VERSION_KEY]?.toString()?.toInt() ?: throw PubNubException(
pubnubError = PubNubError.INVALID_ACCESS_TOKEN, errorMessage = "Couldn't parse version"
)
val timestamp = firstLevelMap[TIMESTAMP_KEY]?.toString()?.toLong() ?: throw PubNubException(
pubnubError = PubNubError.INVALID_ACCESS_TOKEN, errorMessage = "Couldn't parse timestamp"
)
val ttl = firstLevelMap[TTL_KEY]?.toString()?.toLong() ?: throw PubNubException(
pubnubError = PubNubError.INVALID_ACCESS_TOKEN, errorMessage = "Couldn't parse ttl"
)
val resourcesValue = firstLevelMap[RESOURCES_KEY] as? Map<*, *> ?: throw PubNubException(
pubnubError = PubNubError.INVALID_ACCESS_TOKEN, errorMessage = "Resources are not present or are not map"
)
val patternsValue = firstLevelMap[PATTERNS_KEY] as? Map<*, *> ?: throw PubNubException(
pubnubError = PubNubError.INVALID_ACCESS_TOKEN, errorMessage = "Patterns are not present or are not map"
)

return try {
val byteArray = Base64.decode(token.toByteArray(StandardCharsets.UTF_8), Base64.URL_SAFE)
mapper.readValue(byteArray, PNToken::class.java)
} catch (e: IOException) {
throw PubNubException(pubnubError = PubNubError.INVALID_ACCESS_TOKEN, errorMessage = e.message)

PNToken(
version = version,
timestamp = timestamp,
ttl = ttl,
authorizedUUID = firstLevelMap[AUTHORIZED_UUID_KEY]?.toString(),
resources = resourcesValue.toPNTokenResources(),
patterns = patternsValue.toPNTokenResources(),
meta = firstLevelMap[META_KEY]
)
} catch (e: Exception) {
if (e is PubNubException) throw e
throw PubNubException(
pubnubError = PubNubError.INVALID_ACCESS_TOKEN, errorMessage = "Couldn't parse token: ${e.message}"
)
}
}

private fun CborMap.toJvmMap(depth: Int = 0): MutableMap<String, Any> {
if (depth > 3) {
throw PubNubException(pubnubError = PubNubError.INVALID_ACCESS_TOKEN, errorMessage = "Token is too deep")
}
val result = mutableMapOf<String, Any>()
for (key in this.keys) {
val value = this.get(key)
val keyString = when (key) {
is ByteString -> key.bytes.toString(StandardCharsets.UTF_8)
else -> key.toString()
}

when (value) {
is CborMap -> result[keyString] = value.toJvmMap(depth + 1)
is ByteString -> result[keyString] = value.bytes
is List<*> -> result[keyString] = value.map { it.toString() }
is UnsignedInteger -> result[keyString] = value.value
is NegativeInteger -> result[keyString] = value.value
else -> result[keyString] = value.toString()
}
}
return result
}

private fun Map<*, *>.toMapOfStringToInt(): Map<String, Int> {
return mapNotNull { (k, v) ->
when (v) {
is BigInteger -> k.toString() to v.toInt()
else -> v.toString().toIntOrNull()?.let { k.toString() to it }
}
}.toMap()
}

private fun Map<*, *>.toPNTokenResources(): PNToken.PNTokenResources {
val channels = (this[CHANNELS_KEY] as? Map<*, *>)?.toMapOfStringToInt() ?: emptyMap()
val groups = (this[GROUPS_KEY] as? Map<*, *>)?.toMapOfStringToInt() ?: emptyMap()
val uuids = (this[UUIDS_KEY] as? Map<*, *>)?.toMapOfStringToInt() ?: emptyMap()

return PNToken.PNTokenResources(
channels = channels.mapValues { (_, v) -> PNToken.PNResourcePermissions(v) },
channelGroups = groups.mapValues { (_, v) -> PNToken.PNResourcePermissions(v) },
uuids = uuids.mapValues { (_, v) -> PNToken.PNResourcePermissions(v) }
)
}

companion object {
private const val VERSION_KEY = "v"
private const val TIMESTAMP_KEY = "t"
private const val TTL_KEY = "ttl"
private const val AUTHORIZED_UUID_KEY = "uuid"
private const val RESOURCES_KEY = "res"
private const val PATTERNS_KEY = "pat"
private const val META_KEY = "meta"
private const val CHANNELS_KEY = "chan"
private const val GROUPS_KEY = "grp"
private const val UUIDS_KEY = "uuid"
}
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
package com.pubnub.api.models.consumer.access_manager.v3

import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
import com.pubnub.api.models.TokenBitmask

data class PNToken(
@JsonProperty("v") val version: Int = 0,
@JsonProperty("t") val timestamp: Long = 0,
@JsonProperty("ttl") val ttl: Long = 0,
@JsonProperty("uuid") val authorizedUUID: String? = null,
@JsonProperty("res") val resources: PNTokenResources,
@JsonProperty("pat") val patterns: PNTokenResources,
@JsonProperty("meta") val meta: Any? = null
val version: Int = 0,
val timestamp: Long = 0,
val ttl: Long = 0,
val authorizedUUID: String? = null,
val resources: PNTokenResources,
val patterns: PNTokenResources,
val meta: Any? = null
) {

data class PNTokenResources(
@JsonProperty("chan") val channels: Map<String, PNResourcePermissions> = emptyMap(),
@JsonProperty("grp") val channelGroups: Map<String, PNResourcePermissions> = emptyMap(),
@JsonProperty("uuid") val uuids: Map<String, PNResourcePermissions> = emptyMap()
val channels: Map<String, PNResourcePermissions> = emptyMap(),
val channelGroups: Map<String, PNResourcePermissions> = emptyMap(),
val uuids: Map<String, PNResourcePermissions> = emptyMap()
)

data class PNResourcePermissions(
Expand All @@ -30,7 +28,6 @@ data class PNToken(
val join: Boolean = false
) {

@JsonCreator
constructor(grant: Int) : this(
grant and TokenBitmask.READ != 0,
grant and TokenBitmask.WRITE != 0,
Expand Down
50 changes: 45 additions & 5 deletions src/test/kotlin/com/pubnub/api/managers/TokenParserTest.kt
Original file line number Diff line number Diff line change
@@ -1,16 +1,56 @@
package com.pubnub.api.managers

import org.junit.Assert
import com.pubnub.api.models.consumer.access_manager.v3.PNToken
import org.junit.Test
import org.junit.jupiter.api.Assertions.assertEquals
import java.math.BigInteger

class TokenParserTest {

@Test
fun parseTokenWithMeta() {
val tokenWithMeta = "qEF2AkF0GmFLd-NDdHRsGQWgQ3Jlc6VEY2hhbqFjY2gxGP9DZ3JwoWNjZzEY_0N1c3KgQ3NwY6BEdXVpZKFldXVpZDEY_0NwYXSlRGNoYW6gQ2dycKBDdXNyoENzcGOgRHV1aWShYl4kAURtZXRho2VzY29yZRhkZWNvbG9yY3JlZGZhdXRob3JlcGFuZHVEdXVpZGtteWF1dGh1dWlkMUNzaWdYIP2vlxHik0EPZwtgYxAW3-LsBaX_WgWdYvtAXpYbKll3"
val expectedParsedToken = PNToken(
version = 2,
timestamp = 1632335843,
ttl = 1440,
authorizedUUID = "myauthuuid1",
resources = PNToken.PNTokenResources(
channels = mapOf(
"ch1" to PNToken.PNResourcePermissions(
read = true, write = true, manage = true, delete = true, get = true, update = true, join = true
)
),
channelGroups = mapOf(
"cg1" to PNToken.PNResourcePermissions(
read = true, write = true, manage = true, delete = true, get = true, update = true, join = true
)
),
uuids = mapOf(
"uuid1" to PNToken.PNResourcePermissions(
read = true, write = true, manage = true, delete = true, get = true, update = true, join = true
)
)
),
patterns = PNToken.PNTokenResources(
uuids = mapOf(
"^\$" to PNToken.PNResourcePermissions(
read = true,
write = false,
manage = false,
delete = false,
get = false,
update = false,
join = false
)
)
),
meta = mapOf(
"score" to BigInteger.valueOf(100), "color" to "red", "author" to "pandu"
)
)
val tokenWithMeta =
"qEF2AkF0GmFLd-NDdHRsGQWgQ3Jlc6VEY2hhbqFjY2gxGP9DZ3JwoWNjZzEY_0N1c3KgQ3NwY6BEdXVpZKFldXVpZDEY_0NwYXSlRGNoYW6gQ2dycKBDdXNyoENzcGOgRHV1aWShYl4kAURtZXRho2VzY29yZRhkZWNvbG9yY3JlZGZhdXRob3JlcGFuZHVEdXVpZGtteWF1dGh1dWlkMUNzaWdYIP2vlxHik0EPZwtgYxAW3-LsBaX_WgWdYvtAXpYbKll3"
val parsed = TokenParser().unwrapToken(tokenWithMeta)
Assert.assertNotNull(parsed.meta)
Assert.assertTrue(parsed.meta is Map<*, *>)
Assert.assertTrue((parsed.meta as Map<*, *>).isNotEmpty())
assertEquals(expectedParsedToken, parsed)
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.pubnub.contract.subscribe.eventEngine.state

import com.fasterxml.jackson.databind.PropertyNamingStrategies.SnakeCaseStrategy
import com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy
import com.pubnub.api.eventengine.EffectInvocation
import com.pubnub.api.eventengine.Event
import com.pubnub.api.eventengine.QueueSinkSource
Expand Down
Loading