Skip to content

Commit f4fa608

Browse files
authored
Merge pull request #24 from dbluhm/fix/did-regex
fix: did regex and partial matches
2 parents c5360f5 + 779c43a commit f4fa608

File tree

5 files changed

+13
-6
lines changed

5 files changed

+13
-6
lines changed

pydid/common.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
"""Common components."""
22
import re
33

4-
DID_PATTERN = re.compile("did:([a-z0-9]+):((?:[a-zA-Z0-9._-]*:)*[a-zA-Z0-9._-]+)")
4+
DID_REGEX = "did:([a-z0-9]+):((?:[a-zA-Z0-9._-]*:)*[a-zA-Z0-9._-]+)"
5+
DID_PATTERN = re.compile(f"^{DID_REGEX}$")
6+
DID_URL_DID_PART_PATTERN = re.compile(f"^({DID_REGEX})[?/#]")
57

68

79
class DIDError(Exception):

pydid/did.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class DID:
2525
def __init__(self, did: str):
2626
"""Validate and parse raw DID str."""
2727
self._raw = did
28-
matched = DID_PATTERN.fullmatch(did)
28+
matched = DID_PATTERN.match(did)
2929
if not matched:
3030
raise InvalidDIDError("Unable to parse DID {}".format(did))
3131
self._method = matched.group(1)
@@ -73,7 +73,7 @@ def ref(self, ident: str) -> DIDUrl:
7373
@classmethod
7474
def is_valid(cls, did: str):
7575
"""Return if the passed string is a valid DID."""
76-
return DID_PATTERN.fullmatch(did)
76+
return DID_PATTERN.match(did)
7777

7878
@classmethod
7979
def validate(cls, did: str):

pydid/did_url.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from voluptuous import Invalid
66

7-
from .common import DID_PATTERN, DIDError
7+
from .common import DID_URL_DID_PART_PATTERN, DIDError
88

99

1010
class InvalidDIDUrlError(DIDError, Invalid):
@@ -78,12 +78,12 @@ def __hash__(self):
7878
@classmethod
7979
def parse(cls, url: str):
8080
"""Parse DID URL from string."""
81-
matches = DID_PATTERN.match(url)
81+
matches = DID_URL_DID_PART_PATTERN.match(url)
8282

8383
if not matches:
8484
raise InvalidDIDUrlError("DID could not be parsed from URL {}".format(url))
8585

86-
did = matches.group(0)
86+
did = matches.group(1)
8787
_, url_component = url.split(did)
8888

8989
if not url_component:

tests/test_did.py

+1
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ def test_validate(did):
111111
"did:nomethodspecificidentifier",
112112
"did:invalid-chars-in-method:method-specific-id",
113113
"bad-prefix:method:method-specific-id",
114+
"did:bad:char'@='acters:example:1234abcd",
114115
*TEST_DID_URLS,
115116
],
116117
)

tests/test_did_url.py

+4
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,7 @@ def test_is_valid(url):
5353
@pytest.mark.parametrize("bad_url", [TEST_DID0, "not a did url"])
5454
def test_is_valid_x(bad_url):
5555
assert not DIDUrl.is_valid(bad_url)
56+
57+
58+
def test_partial_match_url():
59+
assert not DIDUrl.is_valid("did:bad:char'@='acters:example:1234abcd#4")

0 commit comments

Comments
 (0)