-
Notifications
You must be signed in to change notification settings - Fork 15
issue #1317 WKD client #1377
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
Merged
Merged
issue #1317 WKD client #1377
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
95 changes: 95 additions & 0 deletions
95
FlowCrypt/src/main/java/com/flowcrypt/email/api/wkd/WkdClient.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| /* | ||
| * © 2021-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com | ||
| * Contributors: | ||
| * Ivan Pizhenko | ||
| */ | ||
|
|
||
| package com.flowcrypt.email.api.wkd | ||
|
|
||
| import com.flowcrypt.email.extensions.kotlin.isValidEmail | ||
| import com.flowcrypt.email.util.BetterInternetAddress | ||
| import okhttp3.OkHttpClient | ||
| import okhttp3.Request | ||
| import org.apache.commons.codec.binary.ZBase32 | ||
| import org.apache.commons.codec.digest.DigestUtils | ||
| import org.bouncycastle.openpgp.PGPPublicKeyRingCollection | ||
| import org.bouncycastle.openpgp.jcajce.JcaPGPPublicKeyRingCollection | ||
| import java.net.URLEncoder | ||
| import java.net.UnknownHostException | ||
| import java.util.Locale | ||
| import java.util.concurrent.TimeUnit | ||
|
|
||
| object WkdClient { | ||
| private const val DEFAULT_REQUEST_TIMEOUT = 4 | ||
|
|
||
| fun lookupEmail( | ||
| email: String, | ||
| timeout: Int = DEFAULT_REQUEST_TIMEOUT, | ||
| wkdPort: Int? = null | ||
| ): PGPPublicKeyRingCollection? { | ||
| val keys = rawLookupEmail(email, timeout, wkdPort) ?: return null | ||
| val lowerCaseEmail = email.toLowerCase(Locale.ROOT) | ||
| val matchingKeys = keys.keyRings.asSequence().filter { | ||
| for (userId in it.publicKey.userIDs) { | ||
| try { | ||
| val parsed = BetterInternetAddress(userId) | ||
| if (parsed.emailAddress.toLowerCase(Locale.ROOT) == lowerCaseEmail) return@filter true | ||
| } catch (ex: Exception) { | ||
| // ignore | ||
| } | ||
| } | ||
| false | ||
| }.toList() | ||
| return if (matchingKeys.isNotEmpty()) PGPPublicKeyRingCollection(matchingKeys) else null | ||
| } | ||
|
|
||
| @Suppress("private") | ||
| fun rawLookupEmail( | ||
| email: String, | ||
| timeout: Int = DEFAULT_REQUEST_TIMEOUT, | ||
| wkdPort: Int? = null | ||
| ): PGPPublicKeyRingCollection? { | ||
| if (!email.isValidEmail()) throw IllegalArgumentException("Invalid email address") | ||
| val parts = email.split('@') | ||
| val user = parts[0].toLowerCase(Locale.ROOT) | ||
| val hu = ZBase32().encodeAsString(DigestUtils.sha1(user.toByteArray())) | ||
| val directDomain = parts[1].toLowerCase(Locale.ROOT) | ||
| val advancedDomainPrefix = if (directDomain == "localhost") "" else "openpgpkey." | ||
| val directHost = if (wkdPort == null) directDomain else "${directDomain}:${wkdPort}" | ||
| val advancedHost = "$advancedDomainPrefix$directHost" | ||
| val advancedUrl = "https://${advancedHost}/.well-known/openpgpkey/${directDomain}" | ||
| val directUrl = "https://${directHost}/.well-known/openpgpkey" | ||
| val userPart = "hu/$hu?l=${URLEncoder.encode(user, "UTF-8")}" | ||
| try { | ||
| val result = urlLookup(advancedUrl, userPart, timeout) | ||
| // Do not retry "direct" if "advanced" had a policy file | ||
| if (result.hasPolicy) return result.keys | ||
| } catch (ex: Exception) { | ||
| // ignore | ||
| } | ||
| return try { | ||
| urlLookup(directUrl, userPart, timeout).keys | ||
| } catch (ex: UnknownHostException) { | ||
| null | ||
| } | ||
| } | ||
|
|
||
| private data class UrlLookupResult( | ||
| val hasPolicy: Boolean = false, | ||
| val keys: PGPPublicKeyRingCollection? = null | ||
| ) | ||
|
|
||
| private fun urlLookup(methodUrlBase: String, userPart: String, timeout: Int): UrlLookupResult { | ||
| val httpClient = OkHttpClient.Builder().callTimeout(timeout.toLong(), TimeUnit.SECONDS).build() | ||
| val policyRequest = Request.Builder().url("$methodUrlBase/policy").build() | ||
| httpClient.newCall(policyRequest).execute().use { policyResponse -> | ||
| if (policyResponse.code != 200) return UrlLookupResult() | ||
| } | ||
| val userRequest = Request.Builder().url("$methodUrlBase/$userPart").build() | ||
| httpClient.newCall(userRequest).execute().use { userResponse -> | ||
| if (userResponse.code != 200 || userResponse.body == null) return UrlLookupResult(true) | ||
| val keys = JcaPGPPublicKeyRingCollection(userResponse.body!!.byteStream()) | ||
| return UrlLookupResult(true, keys) | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
70 changes: 70 additions & 0 deletions
70
FlowCrypt/src/main/java/com/flowcrypt/email/util/BetterEmailAddress.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| /* | ||
| * © 2021-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com | ||
| * Contributors: | ||
| * Ivan Pizhenko | ||
| */ | ||
|
|
||
| package com.flowcrypt.email.util | ||
|
|
||
| import com.flowcrypt.email.extensions.kotlin.isValidEmail | ||
|
|
||
| // https://en.wikipedia.org/wiki/Email_address#Internationalization_examples | ||
| class BetterInternetAddress(str: String, verifySpecialCharacters: Boolean = true) { | ||
|
|
||
| companion object { | ||
| const val alphanum = "\\p{L}\\u0900-\\u097F0-9" | ||
| const val validEmail = "(?:[${alphanum}!#\$%&'*+/=?^_`{|}~-]+(?:\\.[${alphanum}!#\$%&'*+/=?^" + | ||
| "_`{|}~-]+)*|\"(?:[\\x01-\\x08" + | ||
| "\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f" + | ||
| "])*\")@(?:(?:[${alphanum}](?:[${alphanum}-]*[${alphanum}])?\\.)+[${alphanum}](?:[" + | ||
| "${alphanum}-]*[${alphanum}])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:" + | ||
| "25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[${alphanum}-]*[${alphanum}]:(?:[\\x01-\\x08\\x0b" + | ||
| "\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)])" | ||
| private const val validPersonalNameWithEmail = | ||
| "([$alphanum\\p{Punct}\\p{Space}]*)<($validEmail)>" | ||
|
|
||
| private val validEmailRegex = validEmail.toRegex() | ||
| private val validPersonalNameWithEmailRegex = validPersonalNameWithEmail.toRegex() | ||
| // if these appear in the display-name they must be double quoted | ||
| private val containsSpecialCharacterRegex = ".*[()<>\\[\\]:;@\\\\,.\"].*".toRegex() | ||
| // double quotes at ends only | ||
| private val doubleQuotedTextRegex = "\"[^\"]*\"".toRegex() | ||
|
|
||
| fun isValidEmail(email: String): Boolean { | ||
| return validEmailRegex.matchEntire(email) != null | ||
| } | ||
|
|
||
| fun areValidEmails(emails: Iterable<String>): Boolean { | ||
| return emails.all { it.isValidEmail() } | ||
| } | ||
| } | ||
|
|
||
| val personalName: String? | ||
| val emailAddress: String | ||
|
|
||
| init { | ||
| val personalNameWithEmailMatch = validPersonalNameWithEmailRegex.find(str) | ||
| val emailMatch = str.matches(validEmailRegex) | ||
| when { | ||
| personalNameWithEmailMatch != null -> { | ||
| val group = personalNameWithEmailMatch.groupValues | ||
| personalName = group[1].trim() | ||
| emailAddress = group[2] | ||
| if ( | ||
| verifySpecialCharacters && | ||
| personalName.matches(containsSpecialCharacterRegex) && | ||
| !personalName.matches(doubleQuotedTextRegex) | ||
| ) { | ||
| throw IllegalArgumentException( | ||
| "Invalid email $str - display name containing special characters must be fully double quoted" | ||
| ) | ||
| } | ||
| } | ||
| emailMatch -> { | ||
| personalName = null | ||
| emailAddress = str | ||
| } | ||
| else -> throw IllegalArgumentException("Invalid email $str") | ||
| } | ||
| } | ||
| } |
38 changes: 38 additions & 0 deletions
38
FlowCrypt/src/test/java/com/flowcrypt/email/api/email/WkdClientTest.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| /* | ||
| * © 2021-present FlowCrypt a.s. Limitations apply. Contact human@flowcrypt.com | ||
| * Contributors: | ||
| * Ivan Pizhenko | ||
| */ | ||
|
|
||
| package com.flowcrypt.email.api.email | ||
|
|
||
| import com.flowcrypt.email.api.wkd.WkdClient | ||
| import org.junit.Assert.assertTrue | ||
| import org.junit.Test | ||
|
|
||
| class WkdClientTest { | ||
| @Test | ||
| fun existingEmailTest() { | ||
| val keys = WkdClient.lookupEmail("human@flowcrypt.com") | ||
| assertTrue("Key not found", keys != null) | ||
| assertTrue("There are no keys in the key collection", keys!!.keyRings.hasNext()) | ||
| } | ||
|
|
||
| @Test | ||
| fun nonExistingEmailTest1() { | ||
| val keys = WkdClient.lookupEmail("no.such.email.for.sure@flowcrypt.com") | ||
| assertTrue("Key found for non-existing email", keys == null) | ||
| } | ||
|
|
||
| @Test | ||
| fun nonExistingEmailTest2() { | ||
| val keys = WkdClient.lookupEmail("doesnotexist@google.com") | ||
| assertTrue("Key found for non-existing email", keys == null) | ||
| } | ||
|
|
||
| @Test | ||
| fun nonExistingDomainTest() { | ||
| val keys = WkdClient.lookupEmail("doesnotexist@thisdomaindoesnotexist.test") | ||
| assertTrue("Key found for non-existing email", keys == null) | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks great, should also test the following:
In both cases, it should return no pubkey without throwing or failing.
Timeout is 3 seconds when it cannot reach, then it returns 'no pubkey'.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@tomholub
I've added tests with these emails.
In TypeScript timeout was 4 seconds, so I've used that.
Not sure how to test what will happen on timeout expiration.