generated from NHSDigital/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 1
[GPCAPIM-285] JWT creation #88
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Vox-Ben
wants to merge
9
commits into
main
Choose a base branch
from
feature/GPCAPIM-285_jwt
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
e9ac116
Add pyjwt, clinical_jwt, make ruff happy
Vox-Ben f1611c7
Include JWT with provider request
Vox-Ben 03aac2f
Add unit tests
Vox-Ben da59fec
Review comments
Vox-Ben b93cf1c
Make ruff happy, refactor controller JWT test
Vox-Ben b5127f5
Fix provider test payloads
Vox-Ben c1ef469
Remove incorrect return values from docstring
Vox-Ben 72c16fc
Make SDS integration tests call main app
Vox-Ben 9f2f955
Fix device and practitioner json
Vox-Ben File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| from .device import Device | ||
| from .jwt import JWT | ||
| from .practitioner import Practitioner | ||
|
|
||
| __all__ = ["JWT", "Device", "Practitioner"] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| from dataclasses import dataclass | ||
|
|
||
|
|
||
| @dataclass(frozen=True, kw_only=True) | ||
| class Device: | ||
| system: str | ||
| value: str | ||
| model: str | ||
| version: str | ||
|
|
||
| @property | ||
| def json(self) -> str: | ||
| outstr = f""" | ||
| {{ | ||
| "resourceType": "Device", | ||
| "identifier": [ | ||
| {{ | ||
| "system": "{self.system}", | ||
| "value": "{self.value}" | ||
| }} | ||
| ], | ||
| "model": "{self.model}", | ||
| "version": "{self.version}" | ||
| }} | ||
| """ | ||
| return outstr.strip() | ||
|
|
||
| def __str__(self) -> str: | ||
| return self.json |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| from dataclasses import dataclass, field | ||
| from datetime import UTC, datetime | ||
| from time import time | ||
| from typing import Any | ||
|
|
||
| import jwt as pyjwt | ||
|
|
||
|
|
||
| @dataclass(frozen=True, kw_only=True) | ||
| class JWT: | ||
| issuer: str | ||
| subject: str | ||
| audience: str | ||
| requesting_device: str | ||
| requesting_organization: str | ||
| requesting_practitioner: str | ||
|
|
||
| # Time fields | ||
| issued_at: int = field(default_factory=lambda: int(time())) | ||
| expiration: int = field(default_factory=lambda: int(time()) + 300) | ||
|
|
||
| # These are here for future proofing but are not expected ever to be changed | ||
| algorithm: str | None = None | ||
| type: str = "JWT" | ||
| reason_for_request: str = "directcare" | ||
| requested_scope: str = "patient/*.read" | ||
|
|
||
| @property | ||
| def issue_time(self) -> str: | ||
| return datetime.fromtimestamp(self.issued_at, tz=UTC).isoformat() | ||
|
|
||
| @property | ||
| def exp_time(self) -> str: | ||
| return datetime.fromtimestamp(self.expiration, tz=UTC).isoformat() | ||
|
|
||
| def encode(self) -> str: | ||
| return pyjwt.encode( | ||
| self.payload(), | ||
| key=None, | ||
| algorithm=self.algorithm, | ||
| headers={"typ": self.type}, | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def decode(token: str) -> "JWT": | ||
| token_dict = pyjwt.decode( | ||
| token, | ||
| options={"verify_signature": False}, # NOSONAR S5659 (not signed) | ||
| ) | ||
|
|
||
| return JWT( | ||
| issuer=token_dict["iss"], | ||
| subject=token_dict["sub"], | ||
| audience=token_dict["aud"], | ||
| expiration=token_dict["exp"], | ||
| issued_at=token_dict["iat"], | ||
| requesting_device=token_dict["requesting_device"], | ||
| requesting_organization=token_dict["requesting_organization"], | ||
| requesting_practitioner=token_dict["requesting_practitioner"], | ||
| ) | ||
|
|
||
| def payload(self) -> dict[str, Any]: | ||
| return { | ||
| "iss": self.issuer, | ||
| "sub": self.subject, | ||
| "aud": self.audience, | ||
| "exp": self.expiration, | ||
| "iat": self.issued_at, | ||
| "requesting_device": self.requesting_device, | ||
| "requesting_organization": self.requesting_organization, | ||
| "requesting_practitioner": self.requesting_practitioner, | ||
| "reason_for_request": self.reason_for_request, | ||
| "requested_scope": self.requested_scope, | ||
| } | ||
|
|
||
| def __str__(self) -> str: | ||
| return self.encode() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| from dataclasses import dataclass | ||
|
|
||
|
|
||
| @dataclass(kw_only=True) | ||
| class Practitioner: | ||
| id: str | ||
| sds_userid: str | ||
| role_profile_id: str | ||
| userid_url: str | ||
| userid_value: str | ||
| family_name: str | ||
| given_name: str | None = None | ||
| prefix: str | None = None | ||
|
|
||
| def __post_init__(self) -> None: | ||
| given = "" if self.given_name is None else f',"given":["{self.given_name}"]' | ||
| prefix = "" if self.prefix is None else f',"prefix":["{self.prefix}"]' | ||
| self._name_str = f'[{{"family": "{self.family_name}"{given}{prefix}}}]' | ||
|
|
||
| @property | ||
| def json(self) -> str: | ||
| user_id_system = "https://fhir.nhs.uk/Id/sds-user-id" | ||
| role_id_system = "https://fhir.nhs.uk/Id/sds-role-profile-id" | ||
|
|
||
| outstr = f""" | ||
| {{ | ||
| "resourceType": "Practitioner", | ||
| "id": "{self.id}", | ||
| "identifier": [ | ||
| {{ | ||
| "system": "{user_id_system}", | ||
| "value": "{self.sds_userid}" | ||
| }}, | ||
| {{ | ||
| "system": "{role_id_system}", | ||
| "value": "{self.role_profile_id}" | ||
| }}, | ||
| {{ | ||
| "system": "{self.userid_url}", | ||
| "value": "{self.userid_value}" | ||
| }} | ||
| ], | ||
| "name": {self._name_str} | ||
| }} | ||
| """ | ||
| return outstr.strip() | ||
|
|
||
| def __str__(self) -> str: | ||
| return self.json |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| """ | ||
| Unit tests for :mod:`gateway_api.clinical_jwt.device`. | ||
| """ | ||
|
|
||
| from json import loads | ||
|
|
||
| from gateway_api.clinical_jwt import Device | ||
|
|
||
|
|
||
| def test_device_creation_with_all_required_fields() -> None: | ||
davidhamill1-nhs marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| """ | ||
| Test that a Device instance can be created with all required fields. | ||
| """ | ||
| device = Device( | ||
| system="https://consumersupplier.com/Id/device-identifier", | ||
| value="CONS-APP-4", | ||
| model="Consumer product name", | ||
| version="5.3.0", | ||
| ) | ||
|
|
||
| assert device.system == "https://consumersupplier.com/Id/device-identifier" | ||
| assert device.value == "CONS-APP-4" | ||
| assert device.model == "Consumer product name" | ||
| assert device.version == "5.3.0" | ||
|
|
||
|
|
||
| def test_device_json_property_returns_valid_json_structure() -> None: | ||
| """ | ||
| Test that the json property returns a valid JSON structure for requesting_device. | ||
| """ | ||
| input_device = Device( | ||
| system="https://consumersupplier.com/Id/device-identifier", | ||
| value="CONS-APP-4", | ||
| model="Consumer product name", | ||
| version="5.3.0", | ||
| ) | ||
|
|
||
| json_output = input_device.json | ||
| jdict = loads(json_output) | ||
|
|
||
| output_device = Device( | ||
| system=jdict["identifier"][0]["system"], | ||
| value=jdict["identifier"][0]["value"], | ||
| model=jdict["model"], | ||
| version=jdict["version"], | ||
| ) | ||
|
|
||
| assert input_device == output_device | ||
|
|
||
|
|
||
| def test_device_str_returns_json() -> None: | ||
| """ | ||
| Test that __str__ returns the same value as the json property. | ||
| """ | ||
| device = Device( | ||
| system="https://test.com/device", | ||
| value="TEST-001", | ||
| model="Test Model", | ||
| version="1.0.0", | ||
| ) | ||
|
|
||
| assert str(device) == device.json | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.