Skip to content

Commit

Permalink
Merge pull request #51 from niscy-eudiw/feature/url-session-parameter
Browse files Browse the repository at this point in the history
Feature/url session parameter
  • Loading branch information
dtsiflit authored Jul 1, 2024
2 parents 5dd09f5 + 31d1bbf commit 2af63b0
Show file tree
Hide file tree
Showing 11 changed files with 109 additions and 32 deletions.
17 changes: 13 additions & 4 deletions Sources/Entities/AuthorisationRequest/AuthorizationRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,16 @@ public extension AuthorizationRequest {
)

let resolvedSiopOpenId4VPRequestData = try await ResolvedRequestData(
clientMetaDataResolver: ClientMetaDataResolver(),
presentationDefinitionResolver: PresentationDefinitionResolver(),
clientMetaDataResolver: ClientMetaDataResolver(
fetcher: Fetcher(session: walletConfiguration?.session ?? URLSession.shared)
),
presentationDefinitionResolver: PresentationDefinitionResolver(
fetcher: Fetcher(session: walletConfiguration?.session ?? URLSession.shared)
),
validatedAuthorizationRequest: validatedAuthorizationRequestData
)
self = .jwt(request: resolvedSiopOpenId4VPRequestData)

} else if let requestUri = authorizationRequestData.requestUri {
let validatedAuthorizationRequestData = try await ValidatedSiopOpenId4VPRequest(
requestUri: requestUri,
Expand All @@ -62,8 +67,12 @@ public extension AuthorizationRequest {
)

let resolvedSiopOpenId4VPRequestData = try await ResolvedRequestData(
clientMetaDataResolver: ClientMetaDataResolver(),
presentationDefinitionResolver: PresentationDefinitionResolver(),
clientMetaDataResolver: ClientMetaDataResolver(
fetcher: Fetcher(session: walletConfiguration?.session ?? URLSession.shared)
),
presentationDefinitionResolver: PresentationDefinitionResolver(
fetcher: Fetcher(session: walletConfiguration?.session ?? URLSession.shared)
),
validatedAuthorizationRequest: validatedAuthorizationRequestData
)
self = .jwt(request: resolvedSiopOpenId4VPRequestData)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public extension ValidatedSiopOpenId4VPRequest {
}

let jwt = try await ValidatedSiopOpenId4VPRequest.fetchJwtString(
fetcher: Fetcher(session: walletConfiguration?.session ?? URLSession.shared),
requestUrl: requestUrl
)

Expand Down Expand Up @@ -236,13 +237,12 @@ public extension ValidatedSiopOpenId4VPRequest {
}
}

fileprivate struct ResultType: Codable {}
fileprivate static func fetchJwtString(
fetcher: Fetcher<ResultType> = Fetcher(),
requestUrl: URL
) async throws -> String {
struct ResultType: Codable {}
let fetcher = Fetcher<ResultType>()
let jwtResult = try await fetcher.fetchString(url: requestUrl)

switch jwtResult {
case .success(let string):
return try ValidatedSiopOpenId4VPRequest.extractJWT(string)
Expand Down
13 changes: 7 additions & 6 deletions Sources/Main/Resolvers/ClientMetaDataResolver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,39 +28,40 @@ public protocol ClientMetaDataResolverType {
/// Resolves client metadata asynchronously.
///
/// - Parameters:
/// - fetcher: The fetcher object responsible for fetching metadata.
/// - source: The input source for resolving metadata.
/// - Returns: An asynchronous result containing the resolved metadata or an error.
func resolve(
fetcher: Fetcher<OutputType>,
source: InputType?
) async -> Result<OutputType?, ErrorType>
}

public actor ClientMetaDataResolver: ClientMetaDataResolverType {

private let fetcher: Fetcher<ClientMetaData>

/**
Initializes an instance.
*/
public init() {
public init(
fetcher: Fetcher<ClientMetaData> = Fetcher()
) {
self.fetcher = fetcher
}

/// Resolves client metadata asynchronously.
///
/// - Parameters:
/// - fetcher: The fetcher object responsible for fetching metadata. Default value is Fetcher<ClientMetaData>().
/// - source: The input source for resolving metadata.
/// - Returns: An asynchronous result containing the resolved metadata or an error of type ResolvingError.
public func resolve(
fetcher: Fetcher<ClientMetaData> = Fetcher(),
source: ClientMetaDataSource?
) async -> Result<ClientMetaData?, ResolvingError> {
guard let source = source else { return .success(nil) }
switch source {
case .passByValue(metaData: let metaData):
return .success(metaData)
case .fetchByReference(url: let url):
let result = await fetcher.fetch(url: url)
let result = await self.fetcher.fetch(url: url)
let metaData = try? result.get()
if let metaData = metaData {
return .success(metaData)
Expand Down
11 changes: 6 additions & 5 deletions Sources/Main/Resolvers/PresentationDefinitionResolver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,34 +29,35 @@ public protocol PresentationDefinitionResolverType {
/// Resolves presentation definitions asynchronously.
///
/// - Parameters:
/// - fetcher: The fetcher object responsible for fetching presentation definitions.
/// - predefinedDefinitions: Predefined presentation definitions mapped by keys.
/// - source: The input source for resolving presentation definitions.
/// - Returns: An asynchronous result containing the resolved presentation definition or an error.
func resolve(
fetcher: Fetcher<OutputType>,
predefinedDefinitions: [String: OutputType],
source: InputType
) async -> Result<OutputType, ErrorType>
}

public actor PresentationDefinitionResolver: PresentationDefinitionResolverType {

private let fetcher: Fetcher<PresentationDefinition>

/**
Initializes an instance.
*/
public init() {
public init(
fetcher: Fetcher<PresentationDefinition> = Fetcher()
) {
self.fetcher = fetcher
}

/// Resolves presentation definitions asynchronously.
///
/// - Parameters:
/// - fetcher: The fetcher object responsible for fetching presentation definitions.
/// - predefinedDefinitions: Predefined presentation definitions mapped by keys.
/// - source: The input source for resolving presentation definitions.
/// - Returns: An asynchronous result containing the resolved presentation definition or an error
public func resolve(
fetcher: Fetcher<PresentationDefinition> = Fetcher(),
predefinedDefinitions: [String: PresentationDefinition] = [:],
source: PresentationDefinitionSource
) async -> Result<PresentationDefinition, ResolvingError> {
Expand Down
1 change: 0 additions & 1 deletion Sources/Main/Services/AuthorisationService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ public actor AuthorisationService: AuthorisationServiceType {
)

let result: Result<T, PostError> = await poster.post(
session: URLSession.shared,
request: post.urlRequest
)
return try result.get()
Expand Down
4 changes: 3 additions & 1 deletion Sources/SiopOpenID4VP/SiopOpenID4VP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,9 @@ public class SiopOpenID4VP: SiopOpenID4VPType {
authorizationResponse: response
)

return try await dispatcher.dispatch()
return try await dispatcher.dispatch(
poster: Poster(session: walletConfiguration?.session ?? URLSession.shared)
)
}

/**
Expand Down
37 changes: 37 additions & 0 deletions Sources/Utilities/Networking/Networking.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright (c) 2023 European Commission
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation

extension URLSession: Networking {}

public protocol Networking {
func data(
from url: URL
) async throws -> (Data, URLResponse)
func data(
for request: URLRequest
) async throws -> (Data, URLResponse)
}

public extension Networking {
func data(from url: URL) async throws -> (Data, URLResponse) {
try await data(from: url)
}

func data(for request: URLRequest) async throws -> (Data, URLResponse) {
try await data(for: request)
}
}
15 changes: 10 additions & 5 deletions Sources/Utilities/RemoteDataAccess/Fetcher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,27 +44,32 @@ public enum FetchError: LocalizedError {
}

public protocol Fetching {
var session: Networking { get set }
associatedtype Element: Codable

/**
Fetches data from the provided URL.

- Parameters:
- session: The URLSession to use for fetching the data.
- url: The URL from which to fetch the data.

- Returns: A `Result` type with the fetched data or an error.
*/
func fetch(session: URLSession, url: URL) async -> Result<Element, FetchError>
func fetch(url: URL) async -> Result<Element, FetchError>
}

public struct Fetcher<Element: Codable>: Fetching {

@Injected var reporter: Reporting
public var session: Networking

/**
Initializes a Fetcher instance.
*/
public init() {
public init(
session: Networking = URLSession.shared
) {
self.session = session
}

/**
Expand All @@ -75,9 +80,9 @@ public struct Fetcher<Element: Codable>: Fetching {

- Returns: A Result type with the fetched data or an error.
*/
public func fetch(session: URLSession = URLSession.shared, url: URL) async -> Result<Element, FetchError> {
public func fetch(url: URL) async -> Result<Element, FetchError> {
do {
let (data, response) = try await session.data(from: url)
let (data, response) = try await self.session.data(from: url)
let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0
if !statusCode.isWithinRange(200...299) {
throw FetchError.invalidStatusCode(url, statusCode)
Expand Down
17 changes: 12 additions & 5 deletions Sources/Utilities/RemoteDataAccess/Poster.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ public enum PostError: Error {

public protocol Posting {

var session: Networking { get set }

/**
Performs a POST request with the provided URLRequest.

Expand All @@ -44,7 +46,7 @@ public protocol Posting {

- Returns: A Result type with the response data or an error.
*/
func post<Response: Codable>(session: URLSession, request: URLRequest) async -> Result<Response, PostError>
func post<Response: Codable>(request: URLRequest) async -> Result<Response, PostError>

/**
Performs a POST request with the provided URLRequest.
Expand All @@ -59,10 +61,15 @@ public protocol Posting {

public struct Poster: Posting {

public var session: Networking

/**
Initializes a Poster instance.
*/
public init() {
public init(
session: Networking = URLSession.shared
) {
self.session = session
}

/**
Expand All @@ -73,9 +80,9 @@ public struct Poster: Posting {

- Returns: A Result type with the response data or an error.
*/
public func post<Response: Codable>(session: URLSession, request: URLRequest) async -> Result<Response, PostError> {
public func post<Response: Codable>(request: URLRequest) async -> Result<Response, PostError> {
do {
let (data, _) = try await session.data(for: request)
let (data, _) = try await self.session.data(for: request)
let object = try JSONDecoder().decode(Response.self, from: data)

return .success(object)
Expand All @@ -101,7 +108,7 @@ public struct Poster: Posting {
public func check(key: String, request: URLRequest) async -> Result<(String, Bool) , PostError> {
do {

let (data, response) = try await URLSession.shared.data(for: request)
let (data, response) = try await self.session.data(for: request)

let string = String(data: data, encoding: .utf8)
let dictionary = string?.toDictionary() ?? [:]
Expand Down
17 changes: 16 additions & 1 deletion Sources/WalletEntities/WalletOpenId4VPConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public struct WalletOpenId4VPConfiguration {
public let supportedClientIdSchemes: [SupportedClientIdScheme]
public let vpFormatsSupported: [ClaimFormat]
public let knownPresentationDefinitionsPerScope: [String: PresentationDefinition]
public let session: Networking

public init(
subjectSyntaxTypesSupported: [SubjectSyntaxType],
Expand All @@ -37,7 +38,8 @@ public struct WalletOpenId4VPConfiguration {
signingKeySet: WebKeySet,
supportedClientIdSchemes: [SupportedClientIdScheme],
vpFormatsSupported: [ClaimFormat],
knownPresentationDefinitionsPerScope: [String: PresentationDefinition] = [:]
knownPresentationDefinitionsPerScope: [String: PresentationDefinition] = [:],
session: Networking = Self.walletSession
) {
self.subjectSyntaxTypesSupported = subjectSyntaxTypesSupported
self.preferredSubjectSyntaxType = preferredSubjectSyntaxType
Expand All @@ -49,6 +51,7 @@ public struct WalletOpenId4VPConfiguration {
self.supportedClientIdSchemes = supportedClientIdSchemes
self.vpFormatsSupported = vpFormatsSupported
self.knownPresentationDefinitionsPerScope = knownPresentationDefinitionsPerScope
self.session = session
}

internal init() throws {
Expand All @@ -62,5 +65,17 @@ public struct WalletOpenId4VPConfiguration {
supportedClientIdSchemes = []
vpFormatsSupported = []
knownPresentationDefinitionsPerScope = [:]
session = URLSession.shared
}

public static let walletSession: Networking = {
/*let delegate = SelfSignedSessionDelegate()
let configuration = URLSessionConfiguration.default
return URLSession(
configuration: configuration,
delegate: delegate,
delegateQueue: nil
)*/
URLSession.shared
}()
}
3 changes: 2 additions & 1 deletion Tests/Entities/EnititiesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ class ResolvedSiopOpenId4VPRequestDataTests: XCTestCase {
signingKeySet: signingKeySet,
supportedClientIdSchemes: supportedClientIdSchemes,
vpFormatsSupported: vpFormatsSupported,
knownPresentationDefinitionsPerScope: knownPresentationDefinitionsPerScope
knownPresentationDefinitionsPerScope: knownPresentationDefinitionsPerScope,
session: WalletOpenId4VPConfiguration.walletSession
)

XCTAssertEqual(walletOpenId4VPConfiguration.subjectSyntaxTypesSupported, subjectSyntaxTypesSupported)
Expand Down

0 comments on commit 2af63b0

Please sign in to comment.