|
| 1 | +import Domain |
| 2 | +import Foundation |
| 3 | +import Gzip |
| 4 | +import JSONWebSignature |
| 5 | + |
| 6 | +struct JWTRevocationCheck { |
| 7 | + let credential: JWTCredential |
| 8 | + |
| 9 | + init(credential: JWTCredential) { |
| 10 | + self.credential = credential |
| 11 | + } |
| 12 | + |
| 13 | + func checkIsRevoked() async throws -> Bool { |
| 14 | + guard let status = credential.jwtVerifiableCredential.verifiableCredential.credentialStatus else { |
| 15 | + return false |
| 16 | + } |
| 17 | + |
| 18 | + guard status.type == "StatusList2021Entry" else { |
| 19 | + throw UnknownError.somethingWentWrongError(customMessage: nil, underlyingErrors: nil) |
| 20 | + } |
| 21 | + |
| 22 | + let listData = try await DownloadDataWithResolver() |
| 23 | + .downloadFromEndpoint(urlOrDID: status.statusListCredential) |
| 24 | + let statusList = try JSONDecoder.didComm().decode(JWTRevocationStatusListCredential.self, from: listData) |
| 25 | + let encodedList = statusList.credentialSubject.encodedList |
| 26 | + let index = status.statusListIndex |
| 27 | + return try verifyRevocationOnEncodedList(encodedList.tryToData(), index: index) |
| 28 | + } |
| 29 | + |
| 30 | + func verifyRevocationOnEncodedList(_ list: Data, index: Int) throws -> Bool { |
| 31 | + let encodedListData = try list.gunzipped() |
| 32 | + let bitList = encodedListData.bytes.flatMap { $0.toBits() } |
| 33 | + guard index < bitList.count else { |
| 34 | + throw UnknownError.somethingWentWrongError(customMessage: "Revocation index out of bounds", underlyingErrors: nil) |
| 35 | + } |
| 36 | + return bitList[index] |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +extension UInt8 { |
| 41 | + func toBits() -> [Bool] { |
| 42 | + var bits = [Bool](repeating: false, count: 8) |
| 43 | + for i in 0..<8 { |
| 44 | + bits[7 - i] = (self & (1 << i)) != 0 |
| 45 | + } |
| 46 | + return bits |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +fileprivate struct DownloadDataWithResolver: Downloader { |
| 51 | + |
| 52 | + public func downloadFromEndpoint(urlOrDID: String) async throws -> Data { |
| 53 | + let url: URL |
| 54 | + |
| 55 | + if let validUrl = URL(string: urlOrDID.replacingOccurrences(of: "host.docker.internal", with: "localhost")) { |
| 56 | + url = validUrl |
| 57 | + } else { |
| 58 | + throw CommonError.invalidURLError(url: urlOrDID) |
| 59 | + } |
| 60 | + |
| 61 | + let (data, urlResponse) = try await URLSession.shared.data(from: url) |
| 62 | + |
| 63 | + guard |
| 64 | + let code = (urlResponse as? HTTPURLResponse)?.statusCode, |
| 65 | + 200...299 ~= code |
| 66 | + else { |
| 67 | + throw CommonError.httpError( |
| 68 | + code: (urlResponse as? HTTPURLResponse)?.statusCode ?? 500, |
| 69 | + message: String(data: data, encoding: .utf8) ?? "" |
| 70 | + ) |
| 71 | + } |
| 72 | + |
| 73 | + return data |
| 74 | + } |
| 75 | +} |
| 76 | + |
0 commit comments