Skip to content

Commit

Permalink
Adjust settings slightly
Browse files Browse the repository at this point in the history
Signed-off-by: jamshale <[email protected]>
  • Loading branch information
jamshale committed Jan 14, 2025
1 parent 2d14cd6 commit 6f2ea82
Show file tree
Hide file tree
Showing 9 changed files with 21 additions and 59 deletions.
10 changes: 3 additions & 7 deletions server/app/models/did_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@

DID_WEB_REGEX = re.compile("did:web:((?:[a-zA-Z0-9._%-]*:)*[a-zA-Z0-9._%-]+)")

DID_WEB_ID_REGEX = re.compile(
"did:web:((?:[a-zA-Z0-9._%-]*:)*[a-zA-Z0-9._%-]+)#([a-z0-9._%-]+)"
)
DID_WEB_ID_REGEX = re.compile("did:web:((?:[a-zA-Z0-9._%-]*:)*[a-zA-Z0-9._%-]+)#([a-z0-9._%-]+)")


class BaseModel(BaseModel):
Expand Down Expand Up @@ -88,7 +86,7 @@ def verification_method_public_key_validator(cls, value):
"""Validate the public key field."""
try:
multibase.decode(value)
except:
except Exception:
assert False, f"Unable to decode public key multibase value {value}"
return value

Expand Down Expand Up @@ -127,9 +125,7 @@ class DidDocument(BaseModel):
description: str = Field(None)
controller: str = Field(None)
alsoKnownAs: List[str] = Field(None)
verificationMethod: List[
Union[VerificationMethodMultikey, VerificationMethodJwk]
] = Field(None)
verificationMethod: List[Union[VerificationMethodMultikey, VerificationMethodJwk]] = Field(None)
authentication: List[Union[str, VerificationMethod]] = Field(None)
assertionMethod: List[Union[str, VerificationMethod]] = Field(None)
keyAgreement: List[Union[str, VerificationMethod]] = Field(None)
Expand Down
16 changes: 4 additions & 12 deletions server/app/plugins/askar.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ class AskarStorage:
def __init__(self):
"""Initialize the Askar storage plugin."""
self.db = settings.ASKAR_DB
self.key = Store.generate_raw_key(
hashlib.md5(settings.DOMAIN.encode()).hexdigest()
)
self.key = Store.generate_raw_key(hashlib.md5(settings.DOMAIN.encode()).hexdigest())

async def provision(self, recreate=False):
"""Provision the Askar storage."""
Expand Down Expand Up @@ -74,9 +72,7 @@ def __init__(self):
def create_proof_config(self, did):
"""Create a proof configuration."""
expires = str(
(datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat(
"T", "seconds"
)
(datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat("T", "seconds")
)
return {
"type": self.type,
Expand Down Expand Up @@ -114,9 +110,7 @@ def validate_proof(self, proof):
assert (
proof["cryptosuite"] == self.cryptosuite
), f"Expected {self.cryptosuite} proof cryptosuite."
assert (
proof["proofPurpose"] == self.purpose
), f"Expected {self.purpose} proof purpose."
assert proof["proofPurpose"] == self.purpose, f"Expected {self.purpose} proof purpose."
except AssertionError as msg:
raise HTTPException(status_code=400, detail=str(msg))

Expand All @@ -139,9 +133,7 @@ def verify_proof(self, document, proof):
)
try:
if not key.verify_signature(message=hash_data, signature=signature):
raise HTTPException(
status_code=400, detail="Signature was forged or corrupt."
)
raise HTTPException(status_code=400, detail="Signature was forged or corrupt.")
return True
except Exception:
raise HTTPException(status_code=400, detail="Error verifying proof.")
4 changes: 1 addition & 3 deletions server/app/plugins/didwebvh.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ def _init_parameters(self, update_key, next_key=None, ttl=100):
return parameters

def _init_state(self, did_doc):
return json.loads(
json.dumps(did_doc).replace("did:web:", self.prefix + r"{SCID}:")
)
return json.loads(json.dumps(did_doc).replace("did:web:", self.prefix + r"{SCID}:"))

def _generate_scid(self, log_entry):
# https://identity.foundation/trustdidweb/#generate-scid
Expand Down
8 changes: 2 additions & 6 deletions server/app/routers/identifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ async def request_did(
},
)

raise HTTPException(
status_code=400, detail="Missing namespace or identifier query."
)
raise HTTPException(status_code=400, detail="Missing namespace or identifier query.")


@router.post("/")
Expand Down Expand Up @@ -123,9 +121,7 @@ async def create_didwebvh(
proof = log_entry.pop("proof", None)
proof = proof if isinstance(proof, list) else [proof]
if len(proof) != 1:
raise HTTPException(
status_code=400, detail="Expecting singular proof from controller."
)
raise HTTPException(status_code=400, detail="Expecting singular proof from controller.")

# Verify proofs
proof = proof[0]
Expand Down
6 changes: 1 addition & 5 deletions server/app/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,7 @@ def create_did_doc(did, multikey, kid="key-01"):
def find_key(did_doc, kid):
"""Find a key in a DID document."""
return next(
(
vm["publicKeyMultibase"]
for vm in did_doc["verificationMethod"]
if vm["id"] == kid
),
(vm["publicKeyMultibase"] for vm in did_doc["verificationMethod"] if vm["id"] == kid),
None,
)

Expand Down
11 changes: 2 additions & 9 deletions server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,8 @@ class Settings(BaseSettings):
POSTGRES_SERVER_PORT: str = os.getenv("POSTGRES_SERVER_PORT", "")

ASKAR_DB: str = "sqlite://app.db"
if (
POSTGRES_USER
and POSTGRES_PASSWORD
and POSTGRES_SERVER_NAME
and POSTGRES_SERVER_PORT
):
logging.info(
f"Using postgres storage: {POSTGRES_SERVER_NAME}:{POSTGRES_SERVER_PORT}"
)
if POSTGRES_USER and POSTGRES_PASSWORD and POSTGRES_SERVER_NAME and POSTGRES_SERVER_PORT:
logging.info(f"Using postgres storage: {POSTGRES_SERVER_NAME}:{POSTGRES_SERVER_PORT}")
ASKAR_DB: str = f"postgres://{POSTGRES_USER}:{POSTGRES_PASSWORD}@{POSTGRES_SERVER_NAME}:{POSTGRES_SERVER_PORT}/didwebvh-server"
else:
logging.info("Using SQLite database")
Expand Down
1 change: 1 addition & 0 deletions server/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ ruff = "^0.9.1"

[tool.ruff]
lint.select = ["B006", "C", "D", "E", "F"]
line-length = 100

lint.ignore = [
# Google Python Doc Style
Expand Down
4 changes: 1 addition & 3 deletions server/tests/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,4 @@
"proofPurpose": "assertionMethod",
}

TEST_DID_DOCUMENT = DidDocument(
context=["https://www.w3.org/ns/did/v1"], id=TEST_DID
).model_dump()
TEST_DID_DOCUMENT = DidDocument(context=["https://www.w3.org/ns/did/v1"], id=TEST_DID).model_dump()
20 changes: 6 additions & 14 deletions server/tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,13 @@ async def test_request_did():
did_request = json.loads(did_request.body.decode())
assert did_request.get("didDocument").get("id") == TEST_DID
assert did_request.get("proofOptions").get("type") == TEST_PROOF_OPTIONS["type"]
assert (
did_request.get("proofOptions").get("cryptosuite")
== TEST_PROOF_OPTIONS["cryptosuite"]
)
assert (
did_request.get("proofOptions").get("proofPurpose")
== TEST_PROOF_OPTIONS["proofPurpose"]
)
assert did_request.get("proofOptions").get("cryptosuite") == TEST_PROOF_OPTIONS["cryptosuite"]
assert did_request.get("proofOptions").get("proofPurpose") == TEST_PROOF_OPTIONS["proofPurpose"]
assert did_request.get("proofOptions").get("domain") == TEST_DOMAIN
assert did_request.get("proofOptions").get("challenge")
assert datetime.fromisoformat(
did_request.get("proofOptions").get("expires")
) > datetime.now(timezone.utc)
assert datetime.fromisoformat(did_request.get("proofOptions").get("expires")) > datetime.now(
timezone.utc
)


@pytest.mark.asyncio
Expand Down Expand Up @@ -107,9 +101,7 @@ async def test_register_log_entry():
signed_log_entry = sign(log_entry)
signed_log_entry["proof"] = [signed_log_entry["proof"]]
log_request = RegisterInitialLogEntry.model_validate({"logEntry": signed_log_entry})
response = await create_didwebvh(
TEST_DID_NAMESPACE, TEST_DID_IDENTIFIER, log_request
)
response = await create_didwebvh(TEST_DID_NAMESPACE, TEST_DID_IDENTIFIER, log_request)
log_entry = response.body.decode()
LogEntry.model_validate(json.loads(log_entry))

Expand Down

0 comments on commit 6f2ea82

Please sign in to comment.