Skip to content

Commit

Permalink
guard with #if canImport(Testing) for android CI
Browse files Browse the repository at this point in the history
  • Loading branch information
MahdiBM committed Feb 11, 2025
1 parent 2e0c712 commit 27cc0a7
Show file tree
Hide file tree
Showing 9 changed files with 192 additions and 88 deletions.
1 change: 1 addition & 0 deletions Benchmarks/.swiftformat
11 changes: 7 additions & 4 deletions Tests/JWTKitTests/ClaimTests.swift
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import JWTKit
#if canImport(Testing)
import Testing
import JWTKit

#if !canImport(Darwin)
import FoundationEssentials
import FoundationEssentials
#else
import Foundation
import Foundation
#endif

@Suite("Claim Tests")
Expand Down Expand Up @@ -35,7 +36,8 @@ struct ClaimTests {
let nadizaDialectSlovenia = try LocalePayload.from(#"{"locale":"sl-nedis"}"#)
let germanSwissPost1996 = try LocalePayload.from(#"{"locale":"de-CH-1996"}"#)
let chineseTraditionalTwoPrivate = try LocalePayload.from(
#"{"locale":"zh-Hant-CN-x-private1-private2"}"#)
#"{"locale":"zh-Hant-CN-x-private1-private2"}"#
)

#expect(plainEnglish.locale.value.identifier == "en")
#expect(brazillianPortugese.locale.value.identifier == "pt-BR")
Expand Down Expand Up @@ -114,3 +116,4 @@ struct ClaimTests {
_ = try await keyCollection.verify(jwt, as: ExpirationPayload.self)
}
}
#endif // canImport(Testing)
11 changes: 7 additions & 4 deletions Tests/JWTKitTests/ECDSATests.swift
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
#if canImport(Testing)
import Testing
import Crypto
import JWTKit
import Testing

#if !canImport(Darwin)
import FoundationEssentials
import FoundationEssentials
#else
import Foundation
import Foundation
#endif

@Suite("ECDSA Tests")
Expand Down Expand Up @@ -240,7 +241,8 @@ struct ECDSATests {
return false
}
return error.foo == "qux"
})
}
)

// Second test: "bar" payload should pass verification
let token = try await keys.sign(Payload(foo: "bar"))
Expand Down Expand Up @@ -343,3 +345,4 @@ let ecdsaPublicKey = """
C18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ==
-----END PUBLIC KEY-----
"""
#endif // canImport(Testing)
4 changes: 3 additions & 1 deletion Tests/JWTKitTests/EdDSATests.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import JWTKit
#if canImport(Testing)
import Testing
import JWTKit

@Suite("EdDSA Tests")
struct EdDSATests {
Expand Down Expand Up @@ -160,3 +161,4 @@ let eddsaPublicKeyBase64 = "0ZcEvMCSYqSwR8XIkxOoaYjRQSAO8frTMSCpNbUl4lE="
let eddsaPrivateKeyBase64 = "d1H3/dcg0V3XyAuZW2TE5Z3rhY20M+4YAfYu/HUQd8w="
let eddsaPublicKeyBase64Url = "0ZcEvMCSYqSwR8XIkxOoaYjRQSAO8frTMSCpNbUl4lE"
let eddsaPrivateKeyBase64Url = "d1H3_dcg0V3XyAuZW2TE5Z3rhY20M-4YAfYu_HUQd8w"
#endif // canImport(Testing)
99 changes: 63 additions & 36 deletions Tests/JWTKitTests/JWTKitTests.swift
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import JWTKit
#if canImport(Testing)
import Testing
import JWTKit
import X509

#if !canImport(Darwin)
import FoundationEssentials
import FoundationEssentials
#else
import Foundation
import Foundation
#endif

@Suite("JWTKit Tests")
Expand Down Expand Up @@ -127,9 +128,12 @@ struct JWTKitTests {
func sign() async throws {
let data =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImZvbyJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImV4cCI6OTk5OTk5OTk5OTk5OTl9.Gf7leJ8i30LmMI7GBTpWDMXV60y1wkTOCOBudP9v9ms"
let keyCollection = await JWTKeyCollection().add(
hmac: "bar", digestAlgorithm: .sha256, kid: "foo"
)
let keyCollection = await JWTKeyCollection()
.add(
hmac: "bar",
digestAlgorithm: .sha256,
kid: "foo"
)
let payload = try await keyCollection.verify(data, as: TestPayload.self)
#expect(payload.name == "John Doe")
}
Expand Down Expand Up @@ -309,15 +313,16 @@ struct JWTKitTests {
"awDmF9aqLqokmXjiydda8mKboArWwP2Ih7K3Ad3Og_u9nUp2gZrXiCMxGGSQiN5Jg3yiW_ffNYaHfyfRWKyQ_g31n4UfPLmPtw6iL3V9GChV5ZDRE9HpxE88U8r1h__xFFrrdnBeWKW8NldI70jg7vY6uiRae4uuXCfSbs4iAUxmRVKWCnV7JE6sObQKUV_EJkBcyND5Y97xsmWD0nPmXCnloQ84gF-eTErJoZBvQhJ4BhmBeUlREHmDKssaxVOCK4l335DKHD1vbuPk9e49M71BK7r2y4Atqk3TEetnwzMs3u-L9RqHaGIBw5u324uGweY7QeD7HFdAUtpjOq_MQQ"

// sign jwt
let keyCollection = try await JWTKeyCollection().add(
rsa: Insecure.RSA.PrivateKey(
modulus: modulus,
exponent: exponent,
privateExponent: privateExponent
),
digestAlgorithm: .sha256,
kid: "vapor"
)
let keyCollection = try await JWTKeyCollection()
.add(
rsa: Insecure.RSA.PrivateKey(
modulus: modulus,
exponent: exponent,
privateExponent: privateExponent
),
digestAlgorithm: .sha256,
kid: "vapor"
)
struct Foo: JWTPayload {
var bar: Int
func verify(using _: some JWTAlgorithm) throws {}
Expand Down Expand Up @@ -374,15 +379,19 @@ struct JWTKitTests {
admin: false,
exp: .init(value: .init(timeIntervalSince1970: 2_000_000_000))
)
let keyCollection = await JWTKeyCollection().addUnsecuredNone(
parser: DefaultJWTParser(jsonDecoder: decoder),
serializer: DefaultJWTSerializer(jsonEncoder: encoder)
)
let keyCollection = await JWTKeyCollection()
.addUnsecuredNone(
parser: DefaultJWTParser(jsonDecoder: decoder),
serializer: DefaultJWTSerializer(jsonEncoder: encoder)
)
let token = try await keyCollection.sign(payload)
#expect(
(token.split(separator: ".").dropFirst(1).first.map {
String(decoding: Data($0.utf8).base64URLDecodedBytes(), as: UTF8.self)
} ?? "").contains(#""exp":""#))
(token.split(separator: ".").dropFirst(1).first
.map {
String(decoding: Data($0.utf8).base64URLDecodedBytes(), as: UTF8.self)
} ?? "")
.contains(#""exp":""#)
)
try await #expect(keyCollection.verify(token.bytes, as: TestPayload.self) == payload)
try await #expect(keyCollection.verify(data.bytes, as: TestPayload.self) == payload)
#expect(token.hasSuffix("."))
Expand Down Expand Up @@ -425,13 +434,15 @@ struct JWTKitTests {
let (encodedHeader, encodedPayload, encodedSignature) = try getTokenParts(token)

let header = try jsonDecoder.decode(
JWTHeader.self, from: .init(encodedHeader.base64URLDecodedBytes())
JWTHeader.self,
from: .init(encodedHeader.base64URLDecodedBytes())
)

let payload =
if header.b64?.asBool ?? true {
try self.jsonDecoder.decode(
Payload.self, from: .init(encodedPayload.base64URLDecodedBytes())
Payload.self,
from: .init(encodedPayload.base64URLDecodedBytes())
)
} else {
try self.jsonDecoder.decode(Payload.self, from: .init(encodedPayload))
Expand All @@ -445,12 +456,16 @@ struct JWTKitTests {

let keyCollection = await JWTKeyCollection()
.add(
hmac: "secret", digestAlgorithm: .sha256, parser: CustomParser(),
hmac: "secret",
digestAlgorithm: .sha256,
parser: CustomParser(),
serializer: CustomSerializer()
)

let payload = TestPayload(
sub: "vapor", name: "Foo", admin: false,
sub: "vapor",
name: "Foo",
admin: false,
exp: .init(value: .init(timeIntervalSince1970: 2_000_000_000))
)

Expand Down Expand Up @@ -526,16 +541,19 @@ struct JWTKitTests {
let jsonDecoder = JSONDecoder()
let decodedFields = try jsonDecoder.decode([String: JWTHeaderField].self, from: encodedHeader)
let decodedJsonFields = try jsonDecoder.decode(
[String: JWTHeaderField].self, from: jsonFields.data(using: .utf8)!
[String: JWTHeaderField].self,
from: jsonFields.data(using: .utf8)!
)
#expect(decodedFields == decodedJsonFields)
}

@Test("Test Custom Header Fields")
func customHeaderFields() async throws {
let keyCollection = await JWTKeyCollection().add(
hmac: .init(key: .init(size: .bits256)), digestAlgorithm: .sha384
)
let keyCollection = await JWTKeyCollection()
.add(
hmac: .init(key: .init(size: .bits256)),
digestAlgorithm: .sha384
)

let payload = TestPayload(
sub: "vapor",
Expand Down Expand Up @@ -620,7 +638,8 @@ struct JWTKitTests {
parsed.header.crit == [
"b64", "http://openbanking.org.uk/iat", "http://openbanking.org.uk/iss",
"http://openbanking.org.uk/tan",
])
]
)
#expect(parsed.header.kid == "90210ABAD")
}

Expand Down Expand Up @@ -691,7 +710,8 @@ struct JWTKitTests {
OF/2NxApJCzGCEDdfSp6VQO30hyhRANCAAQRWz+jn65BtOMvdyHKcvjBeBSDZH2r
1RTwjmYSi9R/zpBnuQ4EiMnCqfMPWiZqB4QdbAd0E7oH50VpuZ1P087G
-----END PRIVATE KEY-----
""")
"""
)

let keyCollection = await JWTKeyCollection()
.add(hmac: "secret", digestAlgorithm: .sha256, kid: "hmac")
Expand All @@ -708,12 +728,16 @@ struct JWTKitTests {
}

let hmacIteratinglyVerified = try await keyCollection.verify(
hmacToken, as: TestPayload.self, iteratingKeys: true
hmacToken,
as: TestPayload.self,
iteratingKeys: true
)
#expect(hmacIteratinglyVerified.sub == "1234567890")

let ecdsaIteratinglyVerified = try await keyCollection.verify(
ecdsaToken, as: TestPayload.self, iteratingKeys: true
ecdsaToken,
as: TestPayload.self,
iteratingKeys: true
)
#expect(ecdsaIteratinglyVerified.sub == "1234567890")
}
Expand Down Expand Up @@ -760,8 +784,10 @@ struct JWTKitTests {
func jwtErrorDescription() {
#expect(
JWTError.claimVerificationFailure(
failedClaim: ExpirationClaim(value: .init(timeIntervalSince1970: 1)), reason: "test"
).description
failedClaim: ExpirationClaim(value: .init(timeIntervalSince1970: 1)),
reason: "test"
)
.description
== "JWTKitError(errorType: claimVerificationFailure, failedClaim: JWTKit.ExpirationClaim(value: 1970-01-01 00:00:01 +0000), reason: \"test\")"
)
#expect(
Expand Down Expand Up @@ -927,3 +953,4 @@ let firebaseCert = """
sb7NLsl7DkvjjxTz7I98xaGbfhofgYympeKT6UO+tmc=
-----END CERTIFICATE-----
"""
#endif // canImport(Testing)
27 changes: 18 additions & 9 deletions Tests/JWTKitTests/PSSTests.swift
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import JWTKit
#if canImport(Testing)
import Testing
import JWTKit

#if !canImport(Darwin)
import FoundationEssentials
import FoundationEssentials
#else
import Foundation
import Foundation
#endif

@Suite("PSS Tests")
Expand All @@ -13,12 +14,15 @@ struct PSSTests {
@Test("Test PSS Docs")
func pssDocs() async throws {
await #expect(throws: Never.self) {
try await JWTKeyCollection().add(
pss: Insecure.RSA.PublicKey(pem: publicKey), digestAlgorithm: .sha256)
try await JWTKeyCollection()
.add(
pss: Insecure.RSA.PublicKey(pem: publicKey),
digestAlgorithm: .sha256
)
}
}

@Test("Test Signing with Private Key")
@Test("Test Signing with Private Key" )
func signing() async throws {
let keyCollection = try await JWTKeyCollection()
.add(pss: Insecure.RSA.PrivateKey(pem: privateKey), digestAlgorithm: .sha256, kid: "private")
Expand Down Expand Up @@ -74,15 +78,18 @@ struct PSSTests {
await #expect(
performing: {
let token = try await keyCollection.sign(
Payload(foo: "qux"), header: ["kid": "private"])
Payload(foo: "qux"),
header: ["kid": "private"]
)
_ = try await keyCollection.verify(token, as: Payload.self)
},
throws: { error in
guard let notBarError = error as? NotBar else {
return false
}
return notBarError.foo == "qux"
})
}
)

// Case where foo is "bar"
let token = try await keyCollection.sign(Payload(foo: "bar"))
Expand All @@ -108,7 +115,8 @@ struct PSSTests {
func exportPublicKeyWhenKeyIsPrivate() async throws {
let privateKey = try Insecure.RSA.PrivateKey(pem: privateKey)
let publicKeyFromPrivate = try Insecure.RSA.PublicKey(
pem: privateKey.publicKey.pemRepresentation)
pem: privateKey.publicKey.pemRepresentation
)
let publicKey = try Insecure.RSA.PublicKey(pem: publicKey)
#expect(publicKeyFromPrivate == publicKey)
}
Expand Down Expand Up @@ -224,3 +232,4 @@ struct PSSTests {
L4z0tz7QWE0aGuOA32YqCSnrSYKdBTPFDILCdfHonzfP7WMPibz4jWxu_FzNk9s4Dh-uN2lV3NGW10pAsnqffD89LtYanRjaIdHnLW_PFo5fEL2yltK7qMB9hO1JegppKCfoc79W4-dr-4qy1Op0B3npOP-DaUYlNamfDmIbQW32UKeJzdGIn-_ryrBT7hQW6_uHLS2VFPPk0rNkPPKZYoNaqGnJ0eaFFF-dFwiThXIpPz--dxTAL8xYf275rjG8C9lh6awOfJSIdXMVuQITWf62E0mSQPR2-219bShMKriDYcYLbT3BJEgOkRBBHGuHo9R5TN298anxZqV1u5jtUQ
"""
}
#endif // canImport(Testing)
Loading

0 comments on commit 27cc0a7

Please sign in to comment.