IdHub/oidc4vp/models.py

326 lines
9.9 KiB
Python
Raw Normal View History

2023-12-11 14:39:50 +00:00
import json
2023-11-24 15:36:05 +00:00
import requests
2023-11-24 16:53:43 +00:00
import secrets
import nacl
import base64
from nacl import pwhash, secret
from django.core.cache import cache
2023-11-24 15:36:05 +00:00
2023-11-24 16:53:43 +00:00
from django.conf import settings
2023-11-24 15:36:05 +00:00
from django.http import QueryDict
from django.utils.translation import gettext_lazy as _
from idhub_auth.models import User
2023-11-24 16:53:43 +00:00
from django.db import models
2023-12-07 17:10:04 +00:00
from utils.idhub_ssikit import verify_presentation
2023-11-24 16:53:43 +00:00
SALT_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
def gen_salt(length: int) -> str:
"""Generate a random string of SALT_CHARS with specified ``length``."""
if length <= 0:
raise ValueError("Salt length must be positive")
return "".join(secrets.choice(SALT_CHARS) for _ in range(length))
def set_client_id():
return gen_salt(24)
def set_client_secret():
return gen_salt(48)
def set_code():
return gen_salt(24)
2023-11-24 15:36:05 +00:00
class Organization(models.Model):
2023-11-24 16:53:43 +00:00
"""
2023-11-29 09:54:05 +00:00
This class represent a member of one net trust or federated host.
Client_id and client_secret are the credentials of this organization
get a connection to my. (receive a request)
My_client_id and my_client_secret are my credentials than to use if I
want to connect to this organization. (send a request)
For use the packages requests we need use my_client_id
For use in the get or post method of a View, then we need use client_id
2024-02-27 08:27:55 +00:00
and secret_id.
main is a field which indicates the organization of this idhub
2023-11-24 16:53:43 +00:00
"""
2023-11-24 15:36:05 +00:00
name = models.CharField(max_length=250)
2024-03-04 08:44:53 +00:00
domain = models.CharField(max_length=250, null=True, default=None)
2024-02-27 08:27:55 +00:00
main = models.BooleanField(default=False)
2023-11-24 17:10:43 +00:00
client_id = models.CharField(
max_length=24,
default=set_client_id,
unique=True
)
client_secret = models.CharField(
max_length=48,
default=set_client_secret
)
2023-11-29 09:54:05 +00:00
my_client_id = models.CharField(
max_length=24,
)
my_client_secret = models.CharField(
max_length=48,
)
2023-11-24 15:36:05 +00:00
response_uri = models.URLField(
2023-11-24 16:53:43 +00:00
help_text=_("Url where to send the verificable presentation"),
2023-11-24 15:36:05 +00:00
max_length=250
)
2024-02-23 15:50:31 +00:00
encrypted_sensitive_data = models.CharField(max_length=255, default=None, null=True)
salt = models.CharField(max_length=255, default=None, null=True)
2023-11-24 15:36:05 +00:00
2023-12-07 17:10:04 +00:00
def send(self, vp, code):
2023-11-24 16:53:43 +00:00
"""
Send the verificable presentation to Verifier
"""
2023-11-29 11:27:20 +00:00
url = "{url}/verify".format(
url=self.response_uri.strip("/"),
)
2023-12-04 08:51:08 +00:00
auth = (self.my_client_id, self.my_client_secret)
2023-12-04 14:47:48 +00:00
data = {"vp_token": vp}
2023-12-07 17:10:04 +00:00
if code:
data["code"] = code
2023-12-04 14:47:48 +00:00
return requests.post(url, data=data, auth=auth)
2023-11-24 16:53:43 +00:00
2023-11-28 08:39:02 +00:00
def demand_authorization(self):
"""
Send the a request for start a process of Verifier
"""
2023-11-29 11:27:20 +00:00
url = "{url}/verify?demand_uri={redirect_uri}".format(
2023-11-28 08:39:02 +00:00
url=self.response_uri.strip("/"),
2024-03-04 08:44:53 +00:00
redirect_uri=self.response_uri
2023-11-28 08:39:02 +00:00
)
2023-11-29 10:50:24 +00:00
auth = (self.my_client_id, self.my_client_secret)
2023-11-28 08:39:02 +00:00
return requests.get(url, auth=auth)
def derive_key_from_password(self, password=None):
if not password:
password = cache.get("KEY_DIDS").encode('utf-8')
kdf = pwhash.argon2i.kdf
ops = pwhash.argon2i.OPSLIMIT_INTERACTIVE
mem = pwhash.argon2i.MEMLIMIT_INTERACTIVE
return kdf(
secret.SecretBox.KEY_SIZE,
password,
self.get_salt(),
opslimit=ops,
memlimit=mem
)
def decrypt_sensitive_data(self, data=None):
sb_key = self.derive_key_from_password()
sb = secret.SecretBox(sb_key)
if not data:
data = self.get_encrypted_sensitive_data()
if not isinstance(data, bytes):
data = data.encode('utf-8')
return sb.decrypt(data).decode('utf-8')
def encrypt_sensitive_data(self, data):
sb_key = self.derive_key_from_password()
sb = secret.SecretBox(sb_key)
if not isinstance(data, bytes):
data = data.encode('utf-8')
return base64.b64encode(sb.encrypt(data)).decode('utf-8')
def get_salt(self):
2024-02-23 15:50:31 +00:00
if not self.salt:
return ''
return base64.b64decode(self.salt.encode('utf-8'))
def set_salt(self):
self.salt = base64.b64encode(nacl.utils.random(16)).decode('utf-8')
def get_encrypted_sensitive_data(self):
return base64.b64decode(self.encrypted_sensitive_data.encode('utf-8'))
def set_encrypted_sensitive_data(self):
key = base64.b64encode(nacl.utils.random(64))
self.set_salt()
key_crypted = self.encrypt_sensitive_data(key)
self.encrypted_sensitive_data = key_crypted
2024-02-23 15:50:31 +00:00
def encrypt_data(self, data):
pw = self.decrypt_sensitive_data().encode('utf-8')
2024-02-23 15:50:31 +00:00
sb = self.get_secret_box(pw)
value_enc = sb.encrypt(data.encode('utf-8'))
return base64.b64encode(value_enc).decode('utf-8')
def decrypt_data(self, data):
pw = self.decrypt_sensitive_data().encode('utf-8')
2024-02-23 15:50:31 +00:00
sb = self.get_secret_box(pw)
value = base64.b64decode(data.encode('utf-8'))
return sb.decrypt(value).decode('utf-8')
def get_secret_box(self, password):
sb_key = self.derive_key_from_password(password=password)
2024-02-23 15:50:31 +00:00
return secret.SecretBox(sb_key)
def change_password_key(self, new_password):
data = self.decrypt_sensitive_data()
sb_key = self.derive_key_from_password(password=new_password)
sb = secret.SecretBox(sb_key)
if not isinstance(data, bytes):
data = data.encode('utf-8')
encrypted_data = base64.b64encode(sb.encrypt(data)).decode('utf-8')
self.encrypted_sensitive_data = encrypted_data
2023-11-24 15:36:05 +00:00
def __str__(self):
return self.name
2023-11-24 16:53:43 +00:00
###################
# Verifier clases #
###################
2023-11-24 15:36:05 +00:00
class Authorization(models.Model):
2023-11-24 16:53:43 +00:00
"""
This class represent a query through browser the client to the wallet.
The Verifier need to do a redirection to the user to Wallet.
The code we use as a soft foreing key between Authorization and OAuth2VPToken.
"""
code = models.CharField(max_length=24, default=set_code)
2023-12-11 13:06:43 +00:00
code_used = models.BooleanField(default=False)
2023-11-24 15:36:05 +00:00
created = models.DateTimeField(auto_now=True)
2023-11-24 16:53:43 +00:00
presentation_definition = models.CharField(max_length=250)
2023-11-24 15:36:05 +00:00
organization = models.ForeignKey(
Organization,
on_delete=models.CASCADE,
2023-11-24 16:53:43 +00:00
related_name='authorizations',
2023-11-24 15:36:05 +00:00
null=True,
)
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
null=True,
)
2023-12-07 17:10:04 +00:00
def authorize(self, path=None):
2023-11-24 15:36:05 +00:00
data = {
"response_type": "vp_token",
"response_mode": "direct_post",
2023-11-29 10:18:12 +00:00
"client_id": self.organization.my_client_id,
2023-11-28 16:33:24 +00:00
"presentation_definition": self.presentation_definition,
2023-12-07 17:10:04 +00:00
"code": self.code,
2023-11-24 16:53:43 +00:00
"nonce": gen_salt(5),
2023-11-24 15:36:05 +00:00
}
query_dict = QueryDict('', mutable=True)
query_dict.update(data)
2023-12-07 17:10:04 +00:00
response_uri = self.organization.response_uri.strip("/")
if path:
response_uri = "{}/{}".format(response_uri, path.strip("/"))
2023-11-24 15:36:05 +00:00
url = '{response_uri}/authorize?{params}'.format(
2023-12-07 17:10:04 +00:00
response_uri=response_uri,
2023-11-24 15:36:05 +00:00
params=query_dict.urlencode()
)
2023-11-24 16:53:43 +00:00
return url
2023-11-24 15:36:05 +00:00
class OAuth2VPToken(models.Model):
2023-11-24 16:53:43 +00:00
"""
This class represent the response of Wallet to Verifier
and the result of verify.
"""
2023-11-24 15:36:05 +00:00
created = models.DateTimeField(auto_now=True)
2023-12-07 17:10:04 +00:00
result_verify = models.CharField(max_length=255)
vp_token = models.TextField()
2023-11-24 15:36:05 +00:00
organization = models.ForeignKey(
Organization,
on_delete=models.CASCADE,
related_name='vp_tokens',
null=True,
)
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='vp_tokens',
null=True,
)
2023-11-24 16:53:43 +00:00
authorization = models.ForeignKey(
Authorization,
on_delete=models.SET_NULL,
2023-12-11 17:40:37 +00:00
related_name='vp_tokens',
2023-11-24 16:53:43 +00:00
null=True,
)
2023-12-07 17:10:04 +00:00
def __init__(self, *args, **kwargs):
code = kwargs.pop("code", None)
super().__init__(*args, **kwargs)
2023-12-11 17:40:37 +00:00
self.authorization = Authorization.objects.filter(code=code).first()
2023-12-07 17:10:04 +00:00
2024-03-07 16:52:39 +00:00
@property
def code(self):
if not self.authorization:
return ''
return self.authorization.code
2023-11-24 16:53:43 +00:00
def verifing(self):
2023-12-07 17:10:04 +00:00
self.result_verify = verify_presentation(self.vp_token)
2024-03-07 16:03:35 +00:00
def get_result_verify(self):
2024-03-07 15:56:15 +00:00
if not self.result_verify:
return {}
return json.loads(self.result_verify)
2023-12-07 17:10:04 +00:00
def get_response_verify(self):
response = {
"verify": ',',
"redirect_uri": "",
"response": "",
}
verification = json.loads(self.result_verify)
if verification.get('errors') or verification.get('warnings'):
2024-03-11 11:53:27 +00:00
response["verify"] = "Error, {}".format(_("Failed verification"))
2023-12-07 17:10:04 +00:00
return response
2024-03-11 11:53:27 +00:00
response["verify"] = "Ok, {}".format(_("Correct verification"))
2024-01-21 10:35:24 +00:00
url = self.get_redirect_url()
if url:
response["redirect_uri"] = url
2023-12-07 17:10:04 +00:00
return response
def get_redirect_url(self):
2024-03-04 09:30:42 +00:00
if not settings.OIDC_REDIRECT:
2024-01-21 10:35:24 +00:00
return
2023-12-07 17:10:04 +00:00
data = {
"code": self.authorization.code,
}
query_dict = QueryDict('', mutable=True)
query_dict.update(data)
2023-11-24 15:36:05 +00:00
2023-12-07 17:10:04 +00:00
response_uri = settings.ALLOW_CODE_URI
2023-11-27 09:59:30 +00:00
2023-12-07 17:10:04 +00:00
url = '{response_uri}?{params}'.format(
response_uri=response_uri,
params=query_dict.urlencode()
)
return url
def get_user_info(self):
tk = json.loads(self.vp_token)
self.user_info = tk.get(
"verifiableCredential", [{}]
)[-1].get("credentialSubject")
2024-03-07 16:52:39 +00:00
return json.dumps(self.user_info, indent=2)
2024-03-15 13:13:35 +00:00
def get_user_info_all(self):
tk = json.loads(self.vp_token)
return json.dumps(tk, indent=2)