def test_eq(did, next_did): same = DID(did) did = DID(did) next_did = DID(next_did) assert did == same assert did != next_did assert did != {"not a": "did"}
def test_hash(did, next_did): same = DID(did) did = DID(did) next_did = DID(next_did) assert hash(did) == hash(same) assert hash(did) != hash(next_did) assert hash(did) != hash(123)
async def resolve(self, profile: Profile, did: Union[str, DID]) -> dict: """Resolve a DID using this resolver.""" if isinstance(did, DID): did = str(did) else: DID.validate(did) if not await self.supports(profile, did): raise DIDMethodNotSupported( f"{self.__class__.__name__} does not support DID method for: {did}" ) return await self._resolve(profile, did)
async def _resolve(self, profile: Profile, did: str) -> dict: """Resolve an indy DID.""" ledger = profile.inject(BaseLedger, required=False) if not ledger or not isinstance(ledger, IndySdkLedger): raise NoIndyLedger("No Indy ledger instance is configured.") try: async with ledger: recipient_key = await ledger.get_key_for_did(did) endpoint = await ledger.get_endpoint_for_did(did) except LedgerError as err: raise DIDNotFound(f"DID {did} could not be resolved") from err builder = DIDDocumentBuilder(DID(did)) vmethod = builder.verification_methods.add( ident="key-1", suite=self.SUITE, material=recipient_key ) builder.authentication.reference(vmethod.id) builder.assertion_method.reference(vmethod.id) if endpoint: # TODO add priority builder.services.add_didcomm( ident=self.AGENT_SERVICE_TYPE, type_=self.AGENT_SERVICE_TYPE, endpoint=endpoint, recipient_keys=[vmethod], routing_keys=[], ) result = builder.build() return result.serialize()
async def test_resolve_did_x_not_found(profile): py_did = DID("did:cowsay:EiDahaOGH-liLLdDtTxEAdc8i-cfCz-WUcQdRJheMVNn3A") cowsay_resolver_not_found = MockResolver(["cowsay"], resolved=DIDNotFound()) registry = DIDResolverRegistry() registry.register(cowsay_resolver_not_found) resolver = DIDResolver(registry) with pytest.raises(DIDNotFound): await resolver.resolve(profile, py_did)
def test_match_did_to_resolver_native_priority(): registry = DIDResolverRegistry() native = MockResolver(["sov"], native=True) non_native = MockResolver(["sov"], native=False) registry.register(non_native) registry.register(native) resolver = DIDResolver(registry) assert [native, non_native] == resolver._match_did_to_resolver(DID(TEST_DID0))
async def _resolve(self, profile: Profile, did: Union[str, DID]) -> Tuple[BaseDIDResolver, dict]: """Retrieve doc and return with resolver.""" # TODO Cache results if isinstance(did, DID): did = str(did) else: DID.validate(did) for resolver in await self._match_did_to_resolver(profile, did): try: LOGGER.debug("Resolving DID %s with %s", did, resolver) document = await resolver.resolve( profile, did, ) return resolver, document except DIDNotFound: LOGGER.debug("DID %s not found by resolver %s", did, resolver) raise DIDNotFound(f"DID {did} could not be resolved")
async def _resolve(self, profile: Profile, did: str) -> dict: """Resolve mock DIDs.""" as_did = DID(did) # Document found: as_did.method_specific_id == "test" # Document not found: as_did.method_specific_id != "test" if as_did.method_specific_id == "test": return { "id": "did:mock:test", "@context": "https://www.w3.org/ns/did/v1", } raise DIDNotFound(f"No document found for {did}")
async def resolve(self, profile: Profile, did: Union[str, DID]) -> DIDDocument: """Retrieve did doc from public registry.""" # TODO Cache results py_did = DID(did) if isinstance(did, str) else did for resolver in self._match_did_to_resolver(py_did): try: LOGGER.debug("Resolving DID %s with %s", did, resolver) return await resolver.resolve(profile, py_did) except DIDNotFound: LOGGER.debug("DID %s not found by resolver %s", did, resolver) raise DIDNotFound(f"DID {did} could not be resolved")
def test_match_did_to_resolver_registration_order(): registry = DIDResolverRegistry() native1 = MockResolver(["sov"], native=True) registry.register(native1) native2 = MockResolver(["sov"], native=True) registry.register(native2) non_native3 = MockResolver(["sov"], native=False) registry.register(non_native3) native4 = MockResolver(["sov"], native=True) registry.register(native4) resolver = DIDResolver(registry) assert [native1, native2, native4, non_native3] == resolver._match_did_to_resolver(DID(TEST_DID0))
async def _resolve(self, profile: Profile, did: str) -> dict: """Resolve an indy DID.""" multitenant_mgr = profile.inject_or(BaseMultitenantManager) if multitenant_mgr: ledger_exec_inst = IndyLedgerRequestsExecutor(profile) else: ledger_exec_inst = profile.inject(IndyLedgerRequestsExecutor) ledger = ( await ledger_exec_inst.get_ledger_for_identifier( did, txn_record_type=GET_KEY_FOR_DID, ) )[1] if not ledger: raise NoIndyLedger("No Indy ledger instance is configured.") try: async with ledger: recipient_key = await ledger.get_key_for_did(did) endpoints = await ledger.get_all_endpoints_for_did(did) except LedgerError as err: raise DIDNotFound(f"DID {did} could not be resolved") from err builder = DIDDocumentBuilder(DID(did)) vmethod = builder.verification_method.add( Ed25519VerificationKey2018, ident="key-1", public_key_base58=recipient_key ) builder.authentication.reference(vmethod.id) builder.assertion_method.reference(vmethod.id) if endpoints: for type_, endpoint in endpoints.items(): if type_ == EndpointType.ENDPOINT.indy: builder.service.add_didcomm( ident=self.AGENT_SERVICE_TYPE, type_=self.AGENT_SERVICE_TYPE, service_endpoint=endpoint, priority=1, recipient_keys=[vmethod], routing_keys=[], ) else: # Accept all service types for now builder.service.add( ident=type_, type_=type_, service_endpoint=endpoint, ) result = builder.build() return result.serialize()
async def resolve(self, profile: Profile, did: Union[str, DID]) -> DIDDocument: """Resolve a DID using this resolver.""" if isinstance(did, DID): did = str(did) else: DID.validate(did) if not await self.supports(profile, did): raise DIDMethodNotSupported( f"{self.__class__.__name__} does not support DID method for: {did}" ) doc_dict = await self._resolve(profile, did) return DIDDocument.deserialize( doc_dict, options={ doc_insert_missing_ids, doc_allow_public_key, vm_allow_controller_list, vm_allow_missing_controller, vm_allow_type_list, }, )
def __transform_to_url(self, did): """ Transform did to url. according to https://w3c-ccg.github.io/did-method-web/#read-resolve """ as_did = DID(did) method_specific_id = as_did.method_specific_id if ":" in method_specific_id: # contains path url = method_specific_id.replace(":", "/") else: # bare domain needs /.well-known path url = method_specific_id + "/.well-known" # Support encoded ports (See: https://github.com/w3c-ccg/did-method-web/issues/7) url = urllib.parse.unquote(url) return "https://" + url + "/did.json"
async def resolve(self, profile: Profile, did: Union[str, DID]) -> DIDDocument: """Resolve a DID using this resolver.""" py_did = DID(did) if isinstance(did, str) else did if not self.supports(py_did.method): raise DIDMethodNotSupported( f"{self.__class__.__name__} does not support DID method {py_did.method}" ) did_document = await self._resolve(profile, str(py_did)) result = DIDDocument.deserialize( did_document, options={ doc_insert_missing_ids, doc_allow_public_key, vm_allow_controller_list, vm_allow_missing_controller, vm_allow_type_list, }, ) return result
async def test_resolve_did_x_not_supported(resolver, profile): py_did = DID("did:cowsay:EiDahaOGH-liLLdDtTxEAdc8i-cfCz-WUcQdRJheMVNn3A") with pytest.raises(DIDMethodNotSupported): await resolver.resolve(profile, py_did)
def test_can_parse_dids(did): did = DID(did) assert repr(did)
def test_match_did_to_resolver(resolver, did, method): base_resolver, *_ = resolver._match_did_to_resolver(DID(did)) assert base_resolver.supports(method)
async def test_resolve_did(resolver, profile, did): doc = await resolver.resolve(profile, DID(did)) assert isinstance(doc, DIDDocument)
def test_str(did): assert str(DID(did)) == did
def test_match_did_to_resolver_x_not_supported(resolver): py_did = DID("did:cowsay:EiDahaOGH-liLLdDtTxEAdc8i-cfCz-WUcQdRJheMVNn3A") with pytest.raises(DIDMethodNotSupported): resolver._match_did_to_resolver(py_did)
def test_full_method(did, method): assert DID(did).full_method == method
def test_method_specific_id(did, method_specific_id): assert DID(did).method_specific_id == method_specific_id
def test_method(did, method): assert DID(did).method == method
def test_url_method(did, parts): did = DID(did) assert did.url(parts.get("path"), parts.get("query"), parts.get("fragment")) == DIDUrl(**parts)
def test_parse_x(bad_did): with pytest.raises(InvalidDIDError): DID(bad_did)
def test_validate_x(bad_did): with pytest.raises(InvalidDIDError): DID.validate(bad_did)
def test_validate(did): DID.validate(did)