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

update to jwt-kit v5beta #53

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion Core/Sources/Configuration/OAuth/OAuthPayload.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public struct OAuthPayload: JWTPayload {
/// Using to nominate the account you want access to on the domain from a service account
var sub: String?

public func verify(using signer: JWTSigner) throws {
public func verify(using algorithm: some JWTAlgorithm) async throws {
try exp.verifyNotExpired()
}
}
52 changes: 29 additions & 23 deletions Core/Sources/Configuration/OAuth/OAuthServiceAccount.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,40 +31,46 @@ public class OAuthServiceAccount: OAuthRefreshable {

// Google Documentation for this approach: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
public func refresh() -> EventLoopFuture<OAuthAccessToken> {
do {
let headers: HTTPHeaders = ["Content-Type": "application/x-www-form-urlencoded"]
let token = try generateJWT()
let headers: HTTPHeaders = ["Content-Type": "application/x-www-form-urlencoded"]

return generateJWT(on: self.eventLoop).flatMapThrowing { (token: String) -> HTTPClient.Request in
let body: HTTPClient.Body = .string("grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=\(token)"
.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")
let request = try HTTPClient.Request(url: GoogleOAuthTokenUrl, method: .POST, headers: headers, body: body)
.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")

return httpClient.execute(request: request, eventLoop: .delegate(on: self.eventLoop)).flatMap { response in

guard var byteBuffer = response.body,
let responseData = byteBuffer.readData(length: byteBuffer.readableBytes),
response.status == .ok else {
return self.eventLoop.makeFailedFuture(OauthRefreshError.noResponse(response.status))
}

do {
return self.eventLoop.makeSucceededFuture(try self.decoder.decode(OAuthAccessToken.self, from: responseData))
} catch {
return self.eventLoop.makeFailedFuture(error)
}
return try HTTPClient.Request(url: GoogleOAuthTokenUrl, method: .POST, headers: headers, body: body)
}.flatMap { request in
return self.httpClient.execute(request: request, eventLoop: .delegate(on: self.eventLoop))
}.flatMap { (response: HTTPClient.Response) in
guard var byteBuffer = response.body,
let responseData = byteBuffer.readData(length: byteBuffer.readableBytes),
response.status == .ok else {
return self.eventLoop.makeFailedFuture(OauthRefreshError.noResponse(response.status))
}

} catch {
return self.eventLoop.makeFailedFuture(error)
do {
return self.eventLoop.makeSucceededFuture(try self.decoder.decode(OAuthAccessToken.self, from: responseData))
} catch {
return self.eventLoop.makeFailedFuture(error)
}
}
}

private func generateJWT() throws -> String {
private func generateJWT(on eventLoop: EventLoop) -> EventLoopFuture<String> {
let payload = OAuthPayload(iss: IssuerClaim(value: credentials.clientEmail),
scope: scope,
aud: AudienceClaim(value: GoogleOAuthTokenAudience),
exp: ExpirationClaim(value: Date().addingTimeInterval(3600)),
iat: IssuedAtClaim(value: Date()), sub: subscription)
let privateKey = try RSAKey.private(pem: credentials.privateKey.data(using: .utf8, allowLossyConversion: true) ?? Data())
return try JWTSigner.rs256(key: privateKey).sign(payload)

let privateKey: Insecure.RSA.PrivateKey
do {
privateKey = try Insecure.RSA.PrivateKey(pem: credentials.privateKey.data(using: .utf8, allowLossyConversion: true) ?? Data())
} catch {
return eventLoop.makeFailedFuture(error)
}

return eventLoop.makeFutureWithTask {
try await JWTKeyCollection().add(rsa: privateKey, digestAlgorithm: .sha256).sign(payload)
}
}
}
4 changes: 2 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ let package = Package(
name: "google-cloud-kit",
platforms: [
.macOS(.v13),
.iOS(.v13)
.iOS(.v16)
],
products: [
.library(
Expand Down Expand Up @@ -51,7 +51,7 @@ let package = Package(
],
dependencies: [
.package(url: "https://github.com/swift-server/async-http-client.git", from: "1.18.0"),
.package(url: "https://github.com/vapor/jwt-kit.git", from: "4.13.0")
.package(url: "https://github.com/vapor/jwt-kit.git", from: "5.0.0")
],
targets: [
.target(
Expand Down