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

Feat/add presentation submission #48

Merged
merged 4 commits into from
Apr 1, 2024
Merged
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
81 changes: 78 additions & 3 deletions Sources/Web5/Credentials/PresentationExchange.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,30 @@ public enum Optionality: Codable {
case preferred
}

public struct PresentationSubmission: Codable, Equatable {
public let id: String
public let definitionID: String
public let descriptorMap: [InputDescriptorMapping]

enum CodingKeys: String, CodingKey {
case id
case definitionID = "definition_id"
case descriptorMap = "descriptor_map"
}
}

public struct InputDescriptorMapping: Codable, Hashable {
public let id: String
public let format: String
public let path: String

enum CodingKeys: String, CodingKey {
case id
case format
case path
}
}

public enum PresentationExchange {

// MARK: - Select Credentials
Expand All @@ -128,11 +152,59 @@ public enum PresentationExchange {
presentationDefinition: PresentationDefinitionV2
) throws -> Void {
let inputDescriptorToVcMap = try mapInputDescriptorsToVCs(vcJWTList: vcJWTs, presentationDefinition: presentationDefinition)
let inputDescriptorToVcFlatMap = inputDescriptorToVcMap.flatMap { $0.value }
guard inputDescriptorToVcFlatMap.count == presentationDefinition.inputDescriptors.count else {

guard inputDescriptorToVcMap.count == presentationDefinition.inputDescriptors.count else {
throw Error.missingDescriptors(presentationDefinition.inputDescriptors.count, inputDescriptorToVcMap.count)
}
}

// MARK: - Create Presentation From Credentials
public static func createPresentationFromCredentials(
vcJWTs: [String],
presentationDefinition: PresentationDefinitionV2
) throws -> PresentationSubmission {
// Make sure VCs satisfy the PD. Note: VCs should be result from `selectCredentials`
do {
try satisfiesPresentationDefinition(
vcJWTs: vcJWTs,
presentationDefinition: presentationDefinition
)
} catch {
throw Error.reason("""
Credentials do not satisfy the provided PresentationDefinition.
Use `PresentationExchange.selectCredentials` and pass in the result to this method's `vcJWTs` argument.
"""
)
}

var descriptorMapList: [InputDescriptorMapping] = []

// Get our inputDescriptor to VC jwt map
let inputDescriptorToVcMap = try mapInputDescriptorsToVCs(vcJWTList: vcJWTs, presentationDefinition: presentationDefinition)

// Iterate through our inputDescriptors
for (inputDescriptor, vcMatches) in inputDescriptorToVcMap {
// Take the first match and get index
if let matchingIndex = vcJWTs.firstIndex(of: vcMatches[0]) {
descriptorMapList.append(
InputDescriptorMapping(
id: inputDescriptor.id,
format: "jwt_vc",
path: "$.verifiableCredential[\(matchingIndex)]"
)
)
} else {
print("No matching JWT found")
}

}

return PresentationSubmission(
id: UUID().uuidString,
definitionID: presentationDefinition.id,
descriptorMap: descriptorMapList
)
}

// MARK: - Map Input Descriptors to VCs
private static func mapInputDescriptorsToVCs(
Expand All @@ -141,7 +213,7 @@ public enum PresentationExchange {
) throws -> [InputDescriptorV2: [String]] {
let vcJWTListMap: [VCDataModel] = try vcJWTList.map { vcJWT in
let parsedJWT = try JWT.parse(jwtString: vcJWT)
guard let vcJSON = parsedJWT.payload.miscellaneous?["vc"]?.value as? [String: Any] else {
guard let vcJSON = parsedJWT.payload.miscellaneous?["vc"]?.value as? [String: Any] else {
throw Error.missingCredentialObject
}

Expand Down Expand Up @@ -226,6 +298,7 @@ extension PresentationExchange {
public enum Error: LocalizedError {
case missingCredentialObject
case missingDescriptors(Int, Int)
case reason(String)

public var errorDescription: String? {
switch self {
Expand All @@ -237,6 +310,8 @@ extension PresentationExchange {
\(totalNeeded) descriptors, but only
\(actualReceived) were found. Check and provide the missing descriptors.
"""
case .reason(let reason):
return "Error: \(reason)"
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import XCTest

final class Web5TestVectorsPresentationExchange: XCTestCase {

func test_resolve() throws {
func test_selectCredentials() throws {
struct Input: Codable {
let presentationDefinition: PresentationDefinitionV2
let credentialJwts: [String]
Expand Down Expand Up @@ -52,5 +52,56 @@ final class Web5TestVectorsPresentationExchange: XCTestCase {
wait(for: [expectation], timeout: 1)
}
}

func test_createPresentationFromDefinition() throws {
struct Input: Codable {
let presentationDefinition: PresentationDefinitionV2
let credentialJwts: [String]
let mockServer: [String: [String: String]]?

func mocks() throws -> [Mock] {
guard let mockServer = mockServer else { return [] }

return try mockServer.map({ key, value in
return Mock(
url: URL(string: key)!,
contentType: .json,
statusCode: 200,
data: [
.get: try JSONEncoder().encode(value)
]
)
})
}
}

struct Output: Codable {
let presentationSubmission: PresentationSubmission
}

let testVector = try TestVector<Input, Output>(
fileName: "create_presentation_from_credentials",
subdirectory: "test-vectors/presentation_exchange"
)

testVector.run { vector in
let expectation = XCTestExpectation(description: "async resolve")
Task {
/// Register each of the mock network responses
try vector.input.mocks().forEach { $0.register() }

/// Select valid credentials from each of the inputs
let credentials = try PresentationExchange.selectCredentials(vcJWTs: vector.input.credentialJwts, presentationDefinition: vector.input.presentationDefinition)

/// Create a presentation submission from the selected credentials and make sure it matches the output
let result = try PresentationExchange.createPresentationFromCredentials(vcJWTs: credentials, presentationDefinition: vector.input.presentationDefinition)
XCTAssertEqual(result.definitionID, vector.output!.presentationSubmission.definitionID)
XCTAssertEqual(result.descriptorMap, vector.output!.presentationSubmission.descriptorMap)
expectation.fulfill()
}

wait(for: [expectation], timeout: 1)
}
}

}
2 changes: 1 addition & 1 deletion Tests/Web5TestVectors/web5-spec
83 changes: 76 additions & 7 deletions Tests/Web5Tests/Credentials/PresentationExchangeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class PresentationExchangeTests: XCTestCase {
eyJraWQiOiJkaWQ6andrOmV5SnJkSGtpT2lKRlF5SXNJblZ6WlNJNkluTnBaeUlzSW1OeWRpSTZJbk5sWTNBeU5UWnJNU0lzSW10cFpDSTZJazVDWDNGc1ZVbHlNRFl0UVdsclZsWk5SbkpsY1RCc1l5MXZiVkYwZW1NMmJ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wZSI6WyJWZXJpZmlhYmxlQ3JlZGVudGlhbCIsIlN0cmVldENyZWQiXSwiQGNvbnRleHQiOlsiaHR0cHM6Ly93d3cudzMub3JnLzIwMTgvY3JlZGVudGlhbHMvdjEiXSwiaXNzdWVyIjoiZGlkOmp3azpleUpyZEhraU9pSkZReUlzSW5WelpTSTZJbk5wWnlJc0ltTnlkaUk2SW5ObFkzQXlOVFpyTVNJc0ltdHBaQ0k2SWs1Q1gzRnNWVWx5TURZdFFXbHJWbFpOUm5KbGNUQnNZeTF2YlZGMGVtTTJiSGRvYUdOMlowODJjalFpTENKNElqb2lSR1IwVGpoWE5uaGZNelJ3UWw5dWEzaFNNR1V4ZEcxRWEwNXVjMHBsZFhOQ1FVVlFla3RYWjJaZldTSXNJbmtpT2lKMU0xY3hNelZwYm05a1RIRjBZMFZpT1dwT1IxTXpTbk5OWDNWR1MyMXJTbE5pT0ZSeVl6bHNkVmRKSWl3aVlXeG5Jam9pUlZNeU5UWkxJbjAifX0.8AehkiboIK6SZy6LHC9ugy_OcT2VsjluzH4qzsgjfTtq9fEsGyY-cOW_xekNUa2RE2VzlP6FXk0gDn4xf6_r4g
"""

// vcJwt satisfies this
let inputDescriptor = InputDescriptorV2(
id: "1234567890_a",
name: nil,
Expand All @@ -36,6 +37,7 @@ class PresentationExchangeTests: XCTestCase {
)
)

// no creds satisfy this
let inputDescriptor2 = InputDescriptorV2(
id: "1234567890_b",
name: nil,
Expand All @@ -56,6 +58,7 @@ class PresentationExchangeTests: XCTestCase {
)
)

// vcJwt and vcJwt2 both satisfy this
let inputDescriptor3 = InputDescriptorV2(
id: "1234567890_c",
name: nil,
Expand All @@ -76,7 +79,7 @@ class PresentationExchangeTests: XCTestCase {
)
)

func test_select_oneOfTwoCorrectCredentials() throws {
func test_selectOneCorrectCredential() throws {
let pd = PresentationDefinitionV2(
id: "1234567890_d",
name: nil,
Expand All @@ -89,34 +92,100 @@ class PresentationExchangeTests: XCTestCase {
)
let result = try PresentationExchange.selectCredentials(vcJWTs: [vcJwt, vcJwt2], presentationDefinition: pd)

XCTAssertEqual(result, [vcJwt])
XCTAssertEqual(result.sorted(), [vcJwt])
}

func test_throw_zeroCorrectCredentials() throws {
func test_selectTwoCorrectCredentials() throws {
let pd = PresentationDefinitionV2(
id: "1234567890_e",
name: nil,
purpose: nil,
format: nil,
submissionRequirements: nil,
inputDescriptors: [
inputDescriptor, inputDescriptor3
]
)
let result = try PresentationExchange.selectCredentials(vcJWTs: [vcJwt, vcJwt2], presentationDefinition: pd)

XCTAssertEqual(result.sorted(), [vcJwt, vcJwt2])
}

func test_selectNoCorrectCredentials() throws {
let pd = PresentationDefinitionV2(
id: "1234567890_f",
name: nil,
purpose: nil,
format: nil,
submissionRequirements: nil,
inputDescriptors: [
inputDescriptor2
]
)
let result = try PresentationExchange.selectCredentials(vcJWTs: [vcJwt, vcJwt2], presentationDefinition: pd)

XCTAssertEqual(result.sorted(), [])
}

func test_throwOnInsufficientCorrectCredentials() throws {
let pd = PresentationDefinitionV2(
id: "1234567890_g",
name: nil,
purpose: nil,
format: nil,
submissionRequirements: nil,
inputDescriptors: [
inputDescriptor, inputDescriptor2
]
)
XCTAssertThrowsError(try PresentationExchange.satisfiesPresentationDefinition(vcJWTs: [vcJwt], presentationDefinition: pd))
}

func test_select_twoOfTwoCorrectCredentials() throws {
func test_noThrowOnSufficientCorrectCredentials() throws {
let pd = PresentationDefinitionV2(
id: "1234567890_f",
id: "1234567890_h",
name: nil,
purpose: nil,
format: nil,
submissionRequirements: nil,
inputDescriptors: [
inputDescriptor, inputDescriptor3
]
)
XCTAssertNoThrow(try PresentationExchange.satisfiesPresentationDefinition(vcJWTs: [vcJwt], presentationDefinition: pd))
}

func test_createPresentationFromCredentials() throws {
let pd = PresentationDefinitionV2(
id: "1234567890_e",
name: nil,
purpose: nil,
format: nil,
submissionRequirements: nil,
inputDescriptors: [
inputDescriptor3
inputDescriptor, inputDescriptor3
]
)
XCTAssertThrowsError(try PresentationExchange.satisfiesPresentationDefinition(vcJWTs: [vcJwt, vcJwt2], presentationDefinition: pd))
let credentials = try PresentationExchange.selectCredentials(vcJWTs: [vcJwt, vcJwt2], presentationDefinition: pd)
let submission = try PresentationExchange.createPresentationFromCredentials(vcJWTs: credentials, presentationDefinition: pd)
XCTAssertNotNil(submission.id)
XCTAssertEqual(submission.definitionID, pd.id)
XCTAssertEqual(submission.descriptorMap.count, 2)
XCTAssertEqual(submission.descriptorMap[0].path, "$.verifiableCredential[0]")
}

func test_throwsOnCreatePresentationFromInvalidCredentials() throws {
let pd = PresentationDefinitionV2(
id: "1234567890_e",
name: nil,
purpose: nil,
format: nil,
submissionRequirements: nil,
inputDescriptors: [
inputDescriptor, inputDescriptor3
]
)

XCTAssertThrowsError(try PresentationExchange.createPresentationFromCredentials(vcJWTs: [vcJwt2], presentationDefinition: pd))
}
}
Loading