|
| 1 | +"""did:web resolver. |
| 2 | +
|
| 3 | +Resolve did:web style dids to a did document. did:web spec: |
| 4 | +https://w3c-ccg.github.io/did-method-web/ |
| 5 | +""" |
| 6 | + |
| 7 | +from . import DIDResolver, DIDNotFound, DIDResolutionError |
| 8 | +from pydid import DID |
| 9 | +from urllib.parse import urlparse |
| 10 | +from datetime import datetime, timedelta |
| 11 | +import urllib.request as url_request |
| 12 | +import re |
| 13 | +import json |
| 14 | +import urllib |
| 15 | + |
| 16 | +domain_regex = ( |
| 17 | + r"((?!-))(xn--)?[a-z0-9][a-z0-9-_]{0,61}[a-z0-9]{0,1}" |
| 18 | + r"\.(xn--)?([a-z0-9\._-]{1,61}|[a-z0-9-]{1,30})" |
| 19 | + r"(%3[aA]\d+)?" # Port |
| 20 | + r"(:[a-zA-Z]+)*" # Path |
| 21 | +) |
| 22 | +did_web_pattern = re.compile(rf"^did:web:{domain_regex}$") |
| 23 | +cache = {} |
| 24 | +TIME_TO_CACHE = 1800 # 30 minutes |
| 25 | + |
| 26 | + |
| 27 | +class DIDWeb(DIDResolver): |
| 28 | + """Utility functions for building and interacting with did:web.""" |
| 29 | + |
| 30 | + async def resolve(self, did: str) -> dict: |
| 31 | + """Resolve a did:web to a did document via http request.""" |
| 32 | + |
| 33 | + # Check to see if we've seen the did recently |
| 34 | + if did in cache: |
| 35 | + if cache[did]["timestamp"] > datetime.now() + timedelta( |
| 36 | + seconds=-TIME_TO_CACHE |
| 37 | + ): |
| 38 | + return cache[did]["doc"] |
| 39 | + else: |
| 40 | + del cache[did] |
| 41 | + |
| 42 | + uri = DIDWeb._did_to_uri(did) |
| 43 | + headers = { |
| 44 | + "User-Agent": "DIDCommRelay/1.0", |
| 45 | + } |
| 46 | + request = url_request.Request(url=uri, method="GET", headers=headers) |
| 47 | + try: |
| 48 | + with url_request.urlopen(request) as response: |
| 49 | + doc = json.loads(response.read().decode()) |
| 50 | + cache[did] = { |
| 51 | + "timestamp": datetime.now(), |
| 52 | + "doc": doc, |
| 53 | + } |
| 54 | + return doc |
| 55 | + except urllib.error.HTTPError as e: |
| 56 | + if e.code == 404: |
| 57 | + raise DIDNotFound( |
| 58 | + f"The did:web {did} returned a 404 not found while resolving" |
| 59 | + ) |
| 60 | + else: |
| 61 | + raise DIDResolutionError( |
| 62 | + f"Unknown server error ({e.code}) while resolving did:web: {did}" |
| 63 | + ) |
| 64 | + except json.decoder.JSONDecodeError as e: |
| 65 | + msg = str(e) |
| 66 | + raise DIDNotFound(f"The did:web {did} returned invalid JSON {msg}") |
| 67 | + except Exception as e: |
| 68 | + raise DIDResolutionError("Failed to fetch did document") from e |
| 69 | + |
| 70 | + @staticmethod |
| 71 | + def _did_to_uri(did: str) -> str: |
| 72 | + # Split the did by it's segments |
| 73 | + did_segments = did.split(":") |
| 74 | + |
| 75 | + # Get the hostname & port |
| 76 | + hostname = did_segments[2].lower() |
| 77 | + hostname = hostname.replace("%3a", ":") |
| 78 | + |
| 79 | + # Resolve the path portion of the DID, if there is no path, default to |
| 80 | + # a .well-known address |
| 81 | + path = ".well-known" |
| 82 | + if len(did_segments) > 3: |
| 83 | + path = "/".join(did_segments[3:]) |
| 84 | + |
| 85 | + # Assemble the URI |
| 86 | + did_uri = f"https://{hostname}/{path}/did.json" |
| 87 | + |
| 88 | + return did_uri |
| 89 | + |
| 90 | + async def is_resolvable(self, did: str) -> bool: |
| 91 | + """Determine if the did is a valid did:web did that can be resolved.""" |
| 92 | + if DID.is_valid(did) and did_web_pattern.match(did): |
| 93 | + return True |
| 94 | + return False |
| 95 | + |
| 96 | + @staticmethod |
| 97 | + def did_from_url(url: str) -> DID: |
| 98 | + """Convert a URL into a did:web did.""" |
| 99 | + |
| 100 | + # Make sure that the URL starts with a scheme |
| 101 | + if not url.startswith("http"): |
| 102 | + url = f"https://{url}" |
| 103 | + |
| 104 | + # Parse it out to we can grab pieces |
| 105 | + parsed_url = urlparse(url) |
| 106 | + |
| 107 | + # Assemble the domain portion of the DID |
| 108 | + did = "did:web:%s" % parsed_url.netloc.replace(":", "%3A") |
| 109 | + |
| 110 | + # Cleanup the path |
| 111 | + path = parsed_url.path.replace(".well-known/did.json", "") |
| 112 | + path = path.replace("/did.json", "") |
| 113 | + |
| 114 | + # Add the path portion of the did |
| 115 | + if len(path) > 1: |
| 116 | + did += path.replace("/", ":") |
| 117 | + return did |
0 commit comments