From f5eded5d0179e8318eba9a5c09601a84882d6cee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Greg=C3=B3rio=20Granado=20Magalh=C3=A3es?= Date: Thu, 4 Mar 2021 15:38:37 -0300 Subject: [PATCH] Add Python package target and examples Python package using C bindings Add support for DIDKit errors; Automatically convert to and from utf8 strings Signed-off-by: Tiago Nascimento Added symlink to the libdidkit.so Added Makefile target Build and install instructions for Python Git ignore for __pycache__ Correct binary name for each OS Django base scaffold Fix free on python target QRCode to generate VC, VC Issuance Submit did functionality Changes for working with credible Python package build to Makefile and CI Python package using C bindings Added symlink to the libdidkit.so Added Makefile target Change author and email address Add build instructions for django example Remove sqlite file Add django dependency Add flask example Remove library binary Fix links to the libraries Add install command for pip Fix didkit build instruction Replace unnecessary dependency Automatically get the the current version Add tests to python target --- .github/workflows/build.yml | 3 + .gitignore | 1 + examples/python-flask/.gitignore | 1 + examples/python-flask/README.md | 46 ++++ examples/python-flask/didkit_flask.py | 63 ++++++ examples/python-flask/issue_credential.py | 47 ++++ .../python-flask/templates/credential.html | 11 + examples/python-flask/templates/index.html | 30 +++ examples/python_django/.gitignore | 2 + examples/python_django/README.md | 49 +++++ examples/python_django/db.sqlite3 | 0 .../python_django/didkit_django/__init__.py | 0 examples/python_django/didkit_django/admin.py | 3 + examples/python_django/didkit_django/apps.py | 5 + .../didkit_django/issue_credential.py | 50 +++++ .../didkit_django/migrations/__init__.py | 0 .../python_django/didkit_django/models.py | 3 + .../templates/didkit_django/credential.html | 12 ++ .../templates/didkit_django/index.html | 32 +++ .../didkit_django/templatetags/__init__.py | 0 .../didkit_django/templatetags/extras.py | 10 + .../didkit_django/templatetags/qrcode.py | 9 + examples/python_django/didkit_django/tests.py | 3 + examples/python_django/didkit_django/urls.py | 9 + examples/python_django/didkit_django/views.py | 45 ++++ examples/python_django/manage.py | 37 ++++ .../python_django/python_django/.gitignore | 1 + .../python_django/python_django/__init__.py | 0 examples/python_django/python_django/asgi.py | 16 ++ .../python_django/python_django/settings.py | 128 +++++++++++ examples/python_django/python_django/urls.py | 7 + examples/python_django/python_django/wsgi.py | 16 ++ lib/Makefile | 11 + lib/python/.gitignore | 3 + lib/python/LICENSE | 201 ++++++++++++++++++ lib/python/README.md | 51 +++++ lib/python/didkit/.gitignore | 1 + lib/python/didkit/__init__.py | 185 ++++++++++++++++ lib/python/didkit/libdidkit.dll | 1 + lib/python/didkit/libdidkit.dylib | 1 + lib/python/didkit/libdidkit.so | 1 + lib/python/didkit/tests.py | 156 ++++++++++++++ lib/python/pyproject.toml | 6 + lib/python/setup.cfg | 23 ++ 44 files changed, 1279 insertions(+) create mode 100644 examples/python-flask/.gitignore create mode 100644 examples/python-flask/README.md create mode 100644 examples/python-flask/didkit_flask.py create mode 100644 examples/python-flask/issue_credential.py create mode 100644 examples/python-flask/templates/credential.html create mode 100644 examples/python-flask/templates/index.html create mode 100644 examples/python_django/.gitignore create mode 100644 examples/python_django/README.md create mode 100644 examples/python_django/db.sqlite3 create mode 100644 examples/python_django/didkit_django/__init__.py create mode 100644 examples/python_django/didkit_django/admin.py create mode 100644 examples/python_django/didkit_django/apps.py create mode 100644 examples/python_django/didkit_django/issue_credential.py create mode 100644 examples/python_django/didkit_django/migrations/__init__.py create mode 100644 examples/python_django/didkit_django/models.py create mode 100644 examples/python_django/didkit_django/templates/didkit_django/credential.html create mode 100644 examples/python_django/didkit_django/templates/didkit_django/index.html create mode 100644 examples/python_django/didkit_django/templatetags/__init__.py create mode 100644 examples/python_django/didkit_django/templatetags/extras.py create mode 100644 examples/python_django/didkit_django/templatetags/qrcode.py create mode 100644 examples/python_django/didkit_django/tests.py create mode 100644 examples/python_django/didkit_django/urls.py create mode 100644 examples/python_django/didkit_django/views.py create mode 100755 examples/python_django/manage.py create mode 100644 examples/python_django/python_django/.gitignore create mode 100644 examples/python_django/python_django/__init__.py create mode 100644 examples/python_django/python_django/asgi.py create mode 100644 examples/python_django/python_django/settings.py create mode 100644 examples/python_django/python_django/urls.py create mode 100644 examples/python_django/python_django/wsgi.py create mode 100644 lib/python/.gitignore create mode 100644 lib/python/LICENSE create mode 100644 lib/python/README.md create mode 100644 lib/python/didkit/.gitignore create mode 100644 lib/python/didkit/__init__.py create mode 120000 lib/python/didkit/libdidkit.dll create mode 120000 lib/python/didkit/libdidkit.dylib create mode 120000 lib/python/didkit/libdidkit.so create mode 100644 lib/python/didkit/tests.py create mode 100644 lib/python/pyproject.toml create mode 100644 lib/python/setup.cfg diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a9ee6088..dcb848f2 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -129,3 +129,6 @@ jobs: - name: Build Android Archive run: make -C lib ../target/test/aar.stamp + + - name: Test Python Package + run: make -C lib ../target/test/python.stamp diff --git a/.gitignore b/.gitignore index 96ef6c0b..307117d7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target Cargo.lock +__pycache__/ \ No newline at end of file diff --git a/examples/python-flask/.gitignore b/examples/python-flask/.gitignore new file mode 100644 index 00000000..f45d9d50 --- /dev/null +++ b/examples/python-flask/.gitignore @@ -0,0 +1 @@ +key.jwk \ No newline at end of file diff --git a/examples/python-flask/README.md b/examples/python-flask/README.md new file mode 100644 index 00000000..473560cf --- /dev/null +++ b/examples/python-flask/README.md @@ -0,0 +1,46 @@ +# Flask Example + +This project demonstrates use of verifiable credentials and presentation for an +application. + +## Dependencies + +- Python 3 +- Pip +- Python 3 virtual environment + +```bash +$ sudo apt update +$ sudo apt install -y python3.6 python3-pip python3-virtualenv python3-venv +``` + +### Python dependencies + +- flask-qrcode +- Flask +- didkit + +```bash +$ python3 -m pip install flask-qrcode flask +``` + +### Building DIDKit + +DIDKit is used to handle credentials and presentations, since it's not yet +publically available in PyPI manual installation is required. + +To do so got to the root folder of this repository and run: +```bash +$ make -C lib ../target/test/python.stamp +``` + +## Running + +For the first time running you will need to run the migrations, +this can be accomplished by running the following command: + +To start the server just run: + +```bash +$ FLASK_APP=didkit_flask.py python3 didkit_flask.py +``` \ No newline at end of file diff --git a/examples/python-flask/didkit_flask.py b/examples/python-flask/didkit_flask.py new file mode 100644 index 00000000..429d1b3d --- /dev/null +++ b/examples/python-flask/didkit_flask.py @@ -0,0 +1,63 @@ +from socket import socket, AF_INET, SOCK_DGRAM +from flask import Flask, request, render_template, jsonify +from issue_credential import issueCredential +from flask_qrcode import QRcode +from didkit import generateEd25519Key +import errno +import os +import json + +app = Flask(__name__) +qrcode = QRcode(app) + + +@app.route('/') +def index(): + s = socket(AF_INET, SOCK_DGRAM) + try: + s.connect(("10.255.255.255", 1)) + IP = s.getsockname()[0] + except Exception: + IP = "127.0.0.1" + finally: + s.close() + + url = (request.is_secure and "https://" or "http://") + IP + \ + ":" + request.host.split(':')[-1] + "/wallet" + + return render_template('index.html', url=url) + + +@app.route('/credential', methods=['GET', 'POST']) +def credential(): + credential = json.dumps(issueCredential(request), indent=2, sort_keys=True) + + return render_template('credential.html', credential=credential) + + +@app.route('/wallet', methods=['GET', 'POST']) +def wallet(): + credential = issueCredential(request) + if request.method == 'GET': + return jsonify({ + "type": "CredentialOffer", + "credentialPreview": credential + }) + + elif request.method == 'POST': + return jsonify(credential) + + +if __name__ == '__main__': + flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY + try: + file_handle = os.open('key.jwk', flags) + except OSError as e: + if e.errno == errno.EEXIST: + pass + else: + raise + else: + with os.fdopen(file_handle, 'w') as file_obj: + file_obj.write(generateEd25519Key()) + app.run(host='0.0.0.0') diff --git a/examples/python-flask/issue_credential.py b/examples/python-flask/issue_credential.py new file mode 100644 index 00000000..4777be63 --- /dev/null +++ b/examples/python-flask/issue_credential.py @@ -0,0 +1,47 @@ +from datetime import datetime, timedelta +import didkit +import json +import uuid + + +def issueCredential(request): + with open('key.jwk', "r") as f: + key = f.readline() + f.close() + + did_key = request.form.get('subject_id', didkit.keyToDID("key", key)) + verification_method = didkit.keyToVerificationMethod("key", key) + issuance_date = datetime.utcnow().replace(microsecond=0) + expiration_date = issuance_date + timedelta(weeks=24) + + credential = { + "id": "urn:uuid:" + uuid.uuid4().__str__(), + "@context": [ + "https://www.w3.org/2018/credentials/v1", + "https://www.w3.org/2018/credentials/examples/v1", + ], + "type": ["VerifiableCredential"], + "issuer": did_key, + "issuanceDate": issuance_date.isoformat() + "Z", + "expirationDate": expiration_date.isoformat() + "Z", + "credentialSubject": { + "@context": [ + { + "username": "https://schema.org/Text" + } + ], + "id": "urn:uuid:" + uuid.uuid4().__str__(), + "username": "Someone", + }, + } + + didkit_options = { + "proofPurpose": "assertionMethod", + "verificationMethod": verification_method, + } + + credential = didkit.issueCredential( + credential.__str__().replace("'", '"'), + didkit_options.__str__().replace("'", '"'), + key) + return json.loads(credential) diff --git a/examples/python-flask/templates/credential.html b/examples/python-flask/templates/credential.html new file mode 100644 index 00000000..d7021f88 --- /dev/null +++ b/examples/python-flask/templates/credential.html @@ -0,0 +1,11 @@ + + + + + + DIDKit Django + + +
{{ credential }}
+ + \ No newline at end of file diff --git a/examples/python-flask/templates/index.html b/examples/python-flask/templates/index.html new file mode 100644 index 00000000..c1c7a100 --- /dev/null +++ b/examples/python-flask/templates/index.html @@ -0,0 +1,30 @@ + + + + + + DIDKit Django + + +
+ + +
+

or scan the QRCode bellow with your wallet. i.e: Credible

+
+

or

+ + + + + \ No newline at end of file diff --git a/examples/python_django/.gitignore b/examples/python_django/.gitignore new file mode 100644 index 00000000..ce24ef44 --- /dev/null +++ b/examples/python_django/.gitignore @@ -0,0 +1,2 @@ +key.jwk +db.sqlite3 \ No newline at end of file diff --git a/examples/python_django/README.md b/examples/python_django/README.md new file mode 100644 index 00000000..3102b8e3 --- /dev/null +++ b/examples/python_django/README.md @@ -0,0 +1,49 @@ +# Django Example + +This project demonstrates use of verifiable credentials and presentation for an +application. + +## Dependencies + +- Python 3 +- Pip + +```bash +$ sudo apt update +$ sudo apt install -y python3.6 python3-pip +``` + +### Python dependencies + +- django-qr-code +- didkit +- Django + +```bash +$ python3 -m pip install django-qr-code django +``` + +### Building DIDKit + +DIDKit is used to handle credentials and presentations, since it's not yet +publically available in PyPI manual installation is required. + +To do so got to the root folder of this repository and run: +```bash +$ make -C lib ../target/test/python.stamp +``` + +## Running + +For the first time running you will need to run the migrations, +this can be accomplished by running the following command: + +```bash +$ python3 manage.py migrate +``` + +To start the server just run: + +```bash +$ python3 manage.py runserver +``` \ No newline at end of file diff --git a/examples/python_django/db.sqlite3 b/examples/python_django/db.sqlite3 new file mode 100644 index 00000000..e69de29b diff --git a/examples/python_django/didkit_django/__init__.py b/examples/python_django/didkit_django/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/python_django/didkit_django/admin.py b/examples/python_django/didkit_django/admin.py new file mode 100644 index 00000000..8c38f3f3 --- /dev/null +++ b/examples/python_django/didkit_django/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/examples/python_django/didkit_django/apps.py b/examples/python_django/didkit_django/apps.py new file mode 100644 index 00000000..1efb8437 --- /dev/null +++ b/examples/python_django/didkit_django/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class DidkitDjangoConfig(AppConfig): + name = 'didkit_django' diff --git a/examples/python_django/didkit_django/issue_credential.py b/examples/python_django/didkit_django/issue_credential.py new file mode 100644 index 00000000..68143584 --- /dev/null +++ b/examples/python_django/didkit_django/issue_credential.py @@ -0,0 +1,50 @@ +from python_django.settings import KEY_PATH +from django.core.files import File +from datetime import datetime, timedelta +import didkit +import json +import uuid + + +def issueCredential(request): + with open(KEY_PATH, "r") as f: + key_file = File(f) + key = key_file.readline() + key_file.close() + + did_key = request.POST.get('subject_id', didkit.keyToDID("key", key)) + verification_method = didkit.keyToVerificationMethod("key", key) + issuance_date = datetime.utcnow().replace(microsecond=0) + expiration_date = issuance_date + timedelta(weeks=24) + + credential = { + "id": "urn:uuid:" + uuid.uuid4().__str__(), + "@context": [ + "https://www.w3.org/2018/credentials/v1", + "https://www.w3.org/2018/credentials/examples/v1", + ], + "type": ["VerifiableCredential"], + "issuer": did_key, + "issuanceDate": issuance_date.isoformat() + "Z", + "expirationDate": expiration_date.isoformat() + "Z", + "credentialSubject": { + "@context": [ + { + "username": "https://schema.org/Text" + } + ], + "id": "urn:uuid:" + uuid.uuid4().__str__(), + "username": "Someone", + }, + } + + didkit_options = { + "proofPurpose": "assertionMethod", + "verificationMethod": verification_method, + } + + credential = didkit.issueCredential( + credential.__str__().replace("'", '"'), + didkit_options.__str__().replace("'", '"'), + key) + return json.loads(credential) diff --git a/examples/python_django/didkit_django/migrations/__init__.py b/examples/python_django/didkit_django/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/python_django/didkit_django/models.py b/examples/python_django/didkit_django/models.py new file mode 100644 index 00000000..71a83623 --- /dev/null +++ b/examples/python_django/didkit_django/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/examples/python_django/didkit_django/templates/didkit_django/credential.html b/examples/python_django/didkit_django/templates/didkit_django/credential.html new file mode 100644 index 00000000..a376ab24 --- /dev/null +++ b/examples/python_django/didkit_django/templates/didkit_django/credential.html @@ -0,0 +1,12 @@ + +{% load extras %} + + + + + DIDKit Django + + +
{{ credential | pretty_json }}
+ + \ No newline at end of file diff --git a/examples/python_django/didkit_django/templates/didkit_django/index.html b/examples/python_django/didkit_django/templates/didkit_django/index.html new file mode 100644 index 00000000..802fbeab --- /dev/null +++ b/examples/python_django/didkit_django/templates/didkit_django/index.html @@ -0,0 +1,32 @@ + +{% load qrcode %} + + + + + DIDKit Django + + +
+ {% csrf_token %} + + +
+

or scan the QRCode bellow with your wallet. i.e: Credible

+
{% qr_from_text url size="S" image_format="svg" %}
+

or

+ + + + + \ No newline at end of file diff --git a/examples/python_django/didkit_django/templatetags/__init__.py b/examples/python_django/didkit_django/templatetags/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/python_django/didkit_django/templatetags/extras.py b/examples/python_django/didkit_django/templatetags/extras.py new file mode 100644 index 00000000..9631e69c --- /dev/null +++ b/examples/python_django/didkit_django/templatetags/extras.py @@ -0,0 +1,10 @@ +import json + +from django import template + +register = template.Library() + + +@register.filter +def pretty_json(value): + return json.dumps(value, indent=2, sort_keys=True) diff --git a/examples/python_django/didkit_django/templatetags/qrcode.py b/examples/python_django/didkit_django/templatetags/qrcode.py new file mode 100644 index 00000000..7a344b70 --- /dev/null +++ b/examples/python_django/didkit_django/templatetags/qrcode.py @@ -0,0 +1,9 @@ +from qr_code.qrcode.maker import make_qr_code_with_args +from django import template + +register = template.Library() + + +@register.simple_tag() +def qr_from_text(text, **kwargs) -> str: + return make_qr_code_with_args(text, qr_code_args=kwargs) diff --git a/examples/python_django/didkit_django/tests.py b/examples/python_django/didkit_django/tests.py new file mode 100644 index 00000000..7ce503c2 --- /dev/null +++ b/examples/python_django/didkit_django/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/examples/python_django/didkit_django/urls.py b/examples/python_django/didkit_django/urls.py new file mode 100644 index 00000000..5db87b9f --- /dev/null +++ b/examples/python_django/didkit_django/urls.py @@ -0,0 +1,9 @@ +from django.urls import path + +from . import views + +urlpatterns = [ + path('', views.index, name='index'), + path('credential/', views.credential, name='credential'), + path('wallet/', views.wallet, name='wallet'), +] diff --git a/examples/python_django/didkit_django/views.py b/examples/python_django/didkit_django/views.py new file mode 100644 index 00000000..603151de --- /dev/null +++ b/examples/python_django/didkit_django/views.py @@ -0,0 +1,45 @@ +from django.shortcuts import render +from django.http import HttpResponse +import socket +from django import forms +from django.http import JsonResponse +from didkit_django.issue_credential import issueCredential +from django.views.decorators.csrf import csrf_exempt + + +def index(request): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.connect(("10.255.255.255", 1)) + IP = s.getsockname()[0] + except Exception: + IP = "127.0.0.1" + finally: + s.close() + + context = { + "url": (request.is_secure() and "https://" or "http://") + IP + + ":" + request.META["SERVER_PORT"] + "/didkit/wallet", + } + return render(request, "didkit_django/index.html", context) + + +def credential(request): + context = { + "credential": issueCredential(request), + } + + return render(request, "didkit_django/credential.html", context) + + +@csrf_exempt +def wallet(request): + credential = issueCredential(request) + if request.method == 'GET': + return JsonResponse({ + "type": "CredentialOffer", + "credentialPreview": credential + }) + + elif request.method == 'POST': + return JsonResponse(credential) diff --git a/examples/python_django/manage.py b/examples/python_django/manage.py new file mode 100755 index 00000000..a80c43a2 --- /dev/null +++ b/examples/python_django/manage.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import errno +import os +import sys +import didkit +flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'python_django.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + + try: + file_handle = os.open('key.jwk', flags) + except OSError as e: + if e.errno == errno.EEXIST: + pass + else: + raise + else: + with os.fdopen(file_handle, 'w') as file_obj: + file_obj.write(didkit.generateEd25519Key()) + + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/examples/python_django/python_django/.gitignore b/examples/python_django/python_django/.gitignore new file mode 100644 index 00000000..ed8ebf58 --- /dev/null +++ b/examples/python_django/python_django/.gitignore @@ -0,0 +1 @@ +__pycache__ \ No newline at end of file diff --git a/examples/python_django/python_django/__init__.py b/examples/python_django/python_django/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/python_django/python_django/asgi.py b/examples/python_django/python_django/asgi.py new file mode 100644 index 00000000..0d19324f --- /dev/null +++ b/examples/python_django/python_django/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for python_django project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'python_django.settings') + +application = get_asgi_application() diff --git a/examples/python_django/python_django/settings.py b/examples/python_django/python_django/settings.py new file mode 100644 index 00000000..17895ebc --- /dev/null +++ b/examples/python_django/python_django/settings.py @@ -0,0 +1,128 @@ +""" +Django settings for python_django project. + +Generated by 'django-admin startproject' using Django 3.1.7. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.1/ref/settings/ +""" + +from pathlib import Path +import os + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = '=(y4vg%x4h#jr(n5ce)$(q$a0%n+)z1t75b7ripbi+#&xlqx+u' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [ + '*' +] + +KEY_PATH = os.path.join(BASE_DIR, 'key.jwk') + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'didkit_django', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'python_django.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + 'libraries':{ + 'qrcode': 'didkit_django.templatetags.qrcode', + } + }, + }, +] + +WSGI_APPLICATION = 'python_django.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/3.1/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/3.1/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.1/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/examples/python_django/python_django/urls.py b/examples/python_django/python_django/urls.py new file mode 100644 index 00000000..1fa62b51 --- /dev/null +++ b/examples/python_django/python_django/urls.py @@ -0,0 +1,7 @@ +from django.contrib import admin +from django.urls import include, path + +urlpatterns = [ + path('didkit/', include('didkit_django.urls')), + path('admin/', admin.site.urls), +] diff --git a/examples/python_django/python_django/wsgi.py b/examples/python_django/python_django/wsgi.py new file mode 100644 index 00000000..6d3acffe --- /dev/null +++ b/examples/python_django/python_django/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for python_django project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'python_django.settings') + +application = get_wsgi_application() diff --git a/lib/Makefile b/lib/Makefile index 68cea3d7..cc588866 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -7,6 +7,8 @@ else OS_NAME=$(shell uname | tr '[:upper:]' '[:lower:]') endif +VERSION=$(shell cat Cargo.toml | grep -m 1 version | cut -d' ' -f3 | sed 's/"//g') + .PHONY: test test: $(TARGET)/test/c.stamp \ $(TARGET)/test/java.stamp \ @@ -41,6 +43,15 @@ $(TARGET)/test/c.stamp: $(TARGET)/cabi-test $(TARGET)/release/libdidkit.so | $(T $(TARGET)/cabi-test: c/test.c $(TARGET)/release/libdidkit.so $(TARGET)/didkit.h $(CC) -I$(TARGET) -L$(TARGET)/release $< -ldl -ldidkit -o $@ +## Python +$(TARGET)/test/python.stamp: $(TARGET)/release/libdidkit.so | $(TARGET)/test + rm -rf python/dist/* + python3 -m pip install --upgrade pip build + python3 -m build python/ + python3 -m pip install python/dist/didkit-$(VERSION)-*.whl + python3 -m unittest python/didkit/tests.py -v + touch $@ + ## Java JAVA_SRC=$(wildcard java/*/*/*.java java/*/*/*/*.java java/*/*/*/*/*.java) diff --git a/lib/python/.gitignore b/lib/python/.gitignore new file mode 100644 index 00000000..2ebc5b00 --- /dev/null +++ b/lib/python/.gitignore @@ -0,0 +1,3 @@ +build +dist +*.egg* diff --git a/lib/python/LICENSE b/lib/python/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/lib/python/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/lib/python/README.md b/lib/python/README.md new file mode 100644 index 00000000..1f72fc80 --- /dev/null +++ b/lib/python/README.md @@ -0,0 +1,51 @@ +Check out the DIDKit documentation [here](https://spruceid.dev/docs/didkit/). + +# DIDKit + +DIDKit provides Verifiable Credential and Decentralized Identifier +functionality across different platforms. It was written primarily in Rust due +to Rust's expressive type system, memory safety, simple dependency web, and +suitability across different platforms including embedded systems. DIDKit +embeds the [`ssi`](https://github.com/spruceid/ssi) library, which contains the +core functionality. + +![DIDKit core components](https://spruceid.dev/assets/images/didkit-core-components-7abba2778ffe8dde24997f305e706bd8.png) + +## Building + +Make sure you have the latest versions of pip and PyPA’s build installed: +```bash +sudo apt install -y python3-pip python3-virtualenv +python3 -m pip install --upgrade pip build +``` + +Build DIDKit: +```bash +cargo build --release +``` + +Build the package +```bash +python3 -m build +``` + +Install the package +```bash +python3 -m pip install dist/didkit-`cat setup.cfg | grep version | cut -d' ' -f3`-*.whl +``` + +## Maturity Disclaimer +In the v0.1 release on January 27th, 2021, DIDKit has not yet undergone a +formal security audit and to desired levels of confidence for suitable use in +production systems. This implementation is currently suitable for exploratory +work and experimentation only. We welcome feedback on the usability, +architecture, and security of this implementation and are committed to a +conducting a formal audit with a reputable security firm before the v1.0 +release. + +We are setting up a process to accept contributions. Please feel free to open +issues or PRs in the interim, but we cannot merge external changes until this +process is in place. + +We are also in the process of creating crates.io entries for the DIDKit and SSI +packages. \ No newline at end of file diff --git a/lib/python/didkit/.gitignore b/lib/python/didkit/.gitignore new file mode 100644 index 00000000..ed8ebf58 --- /dev/null +++ b/lib/python/didkit/.gitignore @@ -0,0 +1 @@ +__pycache__ \ No newline at end of file diff --git a/lib/python/didkit/__init__.py b/lib/python/didkit/__init__.py new file mode 100644 index 00000000..f1bd01bc --- /dev/null +++ b/lib/python/didkit/__init__.py @@ -0,0 +1,185 @@ +from ctypes import * +from sys import platform +import os.path + +didkit = None +didpath = os.path.dirname(os.path.abspath(__file__)) + +if platform == "linux" or platform == "linux2": + didpath = os.path.join(didpath, 'libdidkit.so') + didkit = libc = CDLL(didpath) +elif platform == "darwin": + didpath = os.path.join(didpath, 'libdidkit.dylib') + didkit = libc = CDLL(didpath) +else: + didpath = os.path.join(didpath, 'libdidkit.dll') + didkit = libc = CDLL(didpath, winmode=1) + +# String getVersion() +didkit.didkit_get_version.restype = c_char_p +didkit.didkit_get_version.argtype = () + +# String didkit_error_message() +didkit.didkit_error_message.restype = c_char_p +didkit.didkit_error_message.argtype = () + +# int didkit_error_code() +didkit.didkit_error_code.restype = c_int32 +didkit.didkit_error_code.argtype = () + +# String generateEd25519Key() +didkit.didkit_vc_generate_ed25519_key.restype = c_void_p +didkit.didkit_vc_generate_ed25519_key.argtype = () + +# String keyToDID(String methodName, String key) +didkit.didkit_key_to_did.restype = c_void_p +didkit.didkit_key_to_did.argtype = (c_char_p, c_char_p) + +# String keyToVerificationMethod(String methodName, String key) +didkit.didkit_key_to_verification_method.restype = c_void_p +didkit.didkit_key_to_verification_method.argtype = (c_char_p, c_char_p) + +# String issueCredential(String credential, String options, String key) +didkit.didkit_vc_issue_credential.restype = c_void_p +didkit.didkit_vc_issue_credential.argtype = (c_char_p, c_char_p, c_char_p) + +# String verifyCredential(String credential, String options) +didkit.didkit_vc_verify_credential.restype = c_void_p +didkit.didkit_vc_verify_credential.argtype = (c_char_p, c_char_p) + +# String issuePresentation(String presentation, String options, String key) +didkit.didkit_vc_issue_presentation.restype = c_void_p +didkit.didkit_vc_issue_presentation.argtype = (c_char_p, c_char_p, c_char_p) + +# String verifyPresentation(String presentation, String options) +didkit.didkit_vc_verify_presentation.restype = c_void_p +didkit.didkit_vc_verify_presentation.argtype = (c_char_p, c_char_p) + +# String resolveDID(String did, String inputMetadata) +didkit.didkit_did_resolve.restype = c_void_p +didkit.didkit_did_resolve.argtype = (c_char_p, c_char_p) + +# String dereferenceDIDURL(String didUrl, String inputMetadata) +didkit.didkit_did_url_dereference.restype = c_void_p +didkit.didkit_did_url_dereference.argtype = (c_char_p, c_char_p) + +# String DIDAuth(String did, String options, String key) +didkit.didkit_did_auth.restype = c_void_p +didkit.didkit_did_auth.argtype = (c_char_p, c_char_p, c_char_p) + +# void didkit_free_string(String str) +didkit.didkit_free_string.restype = None +didkit.didkit_free_string.argtype = (c_void_p) + + +class DIDKitException(Exception): + def __init__(self, code, message): + self.code = code + self.message = message + + @staticmethod + def lastError(): + code = didkit.didkit_error_code() + message = didkit.didkit_error_message() + message_str = 'Unable to get error message' if not message else message.decode() + return DIDKitException(code, message_str) + + +def getVersion(): + return didkit.didkit_get_version().decode() + + +def generateEd25519Key(): + key = didkit.didkit_vc_generate_ed25519_key() + if not key: + raise DIDKitException.lastError() + key_str = cast(key, c_char_p).value.decode() + didkit.didkit_free_string(cast(key, c_void_p)) + return key_str + + +def keyToDID(methodName, key): + did = didkit.didkit_key_to_did(methodName.encode(), key.encode()) + if not did: + raise DIDKitException.lastError() + did_str = cast(did, c_char_p).value.decode() + didkit.didkit_free_string(cast(did, c_void_p)) + return did_str + + +def keyToVerificationMethod(methodName, key): + vm = didkit.didkit_key_to_verification_method(methodName.encode(), + key.encode()) + if not vm: + raise DIDKitException.lastError() + vm_str = cast(vm, c_char_p).value.decode() + didkit.didkit_free_string(cast(vm, c_void_p)) + return vm_str + + +def issueCredential(credential, options, key): + vc = didkit.didkit_vc_issue_credential(credential.encode(), + options.encode(), key.encode()) + if not vc: + raise DIDKitException.lastError() + vc_str = cast(vc, c_char_p).value.decode() + didkit.didkit_free_string(cast(vc, c_void_p)) + return vc_str + + +def verifyCredential(credential, options): + result = didkit.didkit_vc_verify_credential(credential.encode(), + options.encode()) + if not result: + raise DIDKitException.lastError() + result_str = cast(result, c_char_p).value.decode() + didkit.didkit_free_string(cast(result, c_void_p)) + return result_str + + +def issuePresentation(presentation, options, key): + vp = didkit.didkit_vc_issue_presentation(presentation.encode(), + options.encode(), key.encode()) + if not vp: + raise DIDKitException.lastError() + vp_str = cast(vp, c_char_p).value.decode() + didkit.didkit_free_string(cast(vp, c_void_p)) + return vp_str + + +def verifyPresentation(presentation, options): + result = didkit.didkit_vc_verify_presentation(presentation.encode(), + options.encode()) + if not result: + raise DIDKitException.lastError() + result_str = cast(result, c_char_p).value.decode() + didkit.didkit_free_string(cast(result, c_void_p)) + return result_str + + +def resolveDID(did, inputMetadata): + result = didkit.didkit_did_resolve(did.encode(), inputMetadata.encode()) + if not result: + raise DIDKitException.lastError() + result_str = cast(result, c_char_p).value.decode() + didkit.didkit_free_string(cast(result, c_void_p)) + return result_str + + +def dereferenceDIDURL(didUrl, inputMetadata): + result = didkit.didkit_did_url_dereference(didUrl.encode(), + inputMetadata.encode()) + if not result: + raise DIDKitException.lastError() + result_str = cast(result, c_char_p).value.decode() + didkit.didkit_free_string(cast(result, c_void_p)) + return result_str + + +def DIDAuth(did, options, key): + vp = didkit.didkit_did_auth(did.encode(), options.encode(), key.encode()) + if not vp: + raise DIDKitException.lastError() + vp_str = cast(vp, c_char_p).value.decode() + didkit.didkit_free_string(cast(vp, c_void_p)) + return vp_str diff --git a/lib/python/didkit/libdidkit.dll b/lib/python/didkit/libdidkit.dll new file mode 120000 index 00000000..b8297d9e --- /dev/null +++ b/lib/python/didkit/libdidkit.dll @@ -0,0 +1 @@ +../../../target/release/libdidkit.dll \ No newline at end of file diff --git a/lib/python/didkit/libdidkit.dylib b/lib/python/didkit/libdidkit.dylib new file mode 120000 index 00000000..e13718fb --- /dev/null +++ b/lib/python/didkit/libdidkit.dylib @@ -0,0 +1 @@ +../../../target/release/libdidkit.dylib \ No newline at end of file diff --git a/lib/python/didkit/libdidkit.so b/lib/python/didkit/libdidkit.so new file mode 120000 index 00000000..147f6a2d --- /dev/null +++ b/lib/python/didkit/libdidkit.so @@ -0,0 +1 @@ +../../../target/release/libdidkit.so \ No newline at end of file diff --git a/lib/python/didkit/tests.py b/lib/python/didkit/tests.py new file mode 100644 index 00000000..d4a9890a --- /dev/null +++ b/lib/python/didkit/tests.py @@ -0,0 +1,156 @@ +import unittest +import didkit +import json +import tests +import uuid + + +class TestKeyMethods(unittest.TestCase): + + def setUp(self): + tests.key = "{\"kty\":\"OKP\",\"crv\":\"Ed25519\",\"x\":\"PBcY2yJ4h_cLUnQNcYhplu9KQQBNpGxP4sYcMPdlu6I\",\"d\":\"n5WUFIghmRYZi0rEYo2lz-Zg2B9B1KW4MYfJXwOXfyI\"}" + + def testGetLibraryVersion(self): + self.assertTrue(type(didkit.getVersion()) is str) + + def testGeneratesEd25519Key(self): + key = json.loads(didkit.generateEd25519Key()) + self.assertIn("kty", key.keys()) + self.assertIn("crv", key.keys()) + self.assertIn("x", key.keys()) + self.assertIn("d", key.keys()) + + def testKeyToDID(self): + self.assertEqual(didkit.keyToDID("key", tests.key), + "did:key:z6MkiVpwA241guqtKWAkohHpcAry7S94QQb6ukW3GcCsugbK" + ) + + def testKeyToVerificationMethod(self): + self.assertEqual(didkit.keyToVerificationMethod( + "key", tests.key), "did:key:z6MkiVpwA241guqtKWAkohHpcAry7S94QQb6ukW3GcCsugbK#z6MkiVpwA241guqtKWAkohHpcAry7S94QQb6ukW3GcCsugbK") + + +class TestCredentialMethods(unittest.TestCase): + def setUp(self): + tests.key = "{\"kty\":\"OKP\",\"crv\":\"Ed25519\",\"x\":\"PBcY2yJ4h_cLUnQNcYhplu9KQQBNpGxP4sYcMPdlu6I\",\"d\":\"n5WUFIghmRYZi0rEYo2lz-Zg2B9B1KW4MYfJXwOXfyI\"}" + tests.did = didkit.keyToDID("key", tests.key) + tests.verificationMethod = didkit.keyToVerificationMethod( + "key", tests.key) + tests.credential = { + "@context": "https://www.w3.org/2018/credentials/v1", + "id": "http://example.org/credentials/3731", + "type": ["VerifiableCredential"], + "issuer": tests.did, + "issuanceDate": "2020-08-19T21:41:50Z", + "credentialSubject": { + "id": "did:example:d23dd687a7dc6787646f2eb98d0", + }, + } + + tests.verificationMethod = { + "proofPurpose": "assertionMethod", + "verificationMethod": tests.verificationMethod, + } + + def testRaisesOnIssueWithEmptyObjects(self): + with self.assertRaises(didkit.DIDKitException): + didkit.issueCredential("{}", "{}", "{}") + + def testIssuesCredentials(self): + credential = didkit.issueCredential( + tests.credential.__str__().replace("'", '"'), + tests.verificationMethod.__str__().replace("'", '"'), + tests.key + ) + + verifyResult = json.loads(didkit.verifyCredential( + credential.__str__().replace("'", '"'), + "{\"proofPurpose\":\"assertionMethod\"}" + )) + + self.assertEqual(len(verifyResult["errors"]), 0) + + +class TestPresentationMethods(unittest.TestCase): + def setUp(self): + tests.key = "{\"kty\":\"OKP\",\"crv\":\"Ed25519\",\"x\":\"PBcY2yJ4h_cLUnQNcYhplu9KQQBNpGxP4sYcMPdlu6I\",\"d\":\"n5WUFIghmRYZi0rEYo2lz-Zg2B9B1KW4MYfJXwOXfyI\"}" + tests.did = didkit.keyToDID("key", tests.key) + tests.verificationMethod = didkit.keyToVerificationMethod( + "key", tests.key) + tests.presentation = { + "@context": ["https://www.w3.org/2018/credentials/v1"], + "id": "http://example.org/presentations/3731", + "type": ["VerifiablePresentation"], + "holder": tests.did, + "verifiableCredential": { + "@context": "https://www.w3.org/2018/credentials/v1", + "id": "http://example.org/credentials/3731", + "type": ["VerifiableCredential"], + "issuer": "did:example:30e07a529f32d234f6181736bd3", + "issuanceDate": "2020-08-19T21:41:50Z", + "credentialSubject": { + "id": "did:example:d23dd687a7dc6787646f2eb98d0", + }, + }, + } + + tests.verificationPurpose = { + "proofPurpose": "authentication", + "verificationMethod": tests.verificationMethod, + } + + def testRaisesOnPresentWithEmptyObjects(self): + with self.assertRaises(didkit.DIDKitException): + didkit.issuePresentation("{}", "{}", "{}") + + def testVerifyIssuedPresentation(self): + presentation = didkit.issuePresentation( + tests.presentation.__str__().replace("'", '"'), + tests.verificationPurpose.__str__().replace("'", '"'), + tests.key + ) + + verifyResult = json.loads(didkit.verifyPresentation( + presentation.__str__().replace("'", '"'), + tests.verificationPurpose.__str__().replace("'", '"') + )) + + self.assertEqual(len(verifyResult["errors"]), 0) + + +class TestAuthMethods(unittest.TestCase): + def setUp(self): + tests.key = "{\"kty\":\"OKP\",\"crv\":\"Ed25519\",\"x\":\"PBcY2yJ4h_cLUnQNcYhplu9KQQBNpGxP4sYcMPdlu6I\",\"d\":\"n5WUFIghmRYZi0rEYo2lz-Zg2B9B1KW4MYfJXwOXfyI\"}" + tests.did = didkit.keyToDID("key", tests.key) + tests.verificationMethod = didkit.keyToVerificationMethod( + "key", + tests.key + ) + + tests.verificationPurpose = { + "proofPurpose": "authentication", + "verificationMethod": tests.verificationMethod, + "challenge": uuid.uuid4().__str__() + } + + def testRaisesOnPresentWithEmptyObjects(self): + with self.assertRaises(didkit.DIDKitException): + didkit.DIDAuth("", "{}", "{}") + + def testIssueAndVerifyDIDAuthVerifiablePresentation(self): + presentation = didkit.DIDAuth( + tests.did.__str__().replace("'", '"'), + tests.verificationPurpose.__str__().replace("'", '"'), + tests.key + ) + + verifyResult = json.loads(didkit.verifyPresentation( + presentation, + tests.verificationPurpose.__str__().replace("'", '"') + )) + + self.assertEqual(len(verifyResult["errors"]), 0) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python/pyproject.toml b/lib/python/pyproject.toml new file mode 100644 index 00000000..374b58cb --- /dev/null +++ b/lib/python/pyproject.toml @@ -0,0 +1,6 @@ +[build-system] +requires = [ + "setuptools>=42", + "wheel" +] +build-backend = "setuptools.build_meta" diff --git a/lib/python/setup.cfg b/lib/python/setup.cfg new file mode 100644 index 00000000..faa34dea --- /dev/null +++ b/lib/python/setup.cfg @@ -0,0 +1,23 @@ +[metadata] +name = didkit +version = 0.1.0 +author = Spruce Systems, Inc. +author_email = oss@spruceid.com +description = DIDKit python package +long_description = file: README.md +long_description_content_type = text/markdown +url = https://github.com/spruceid/didkit +project_urls = + Bug Tracker = https://github.com/spruceid/didkit/issues +classifiers = + Programming Language :: Python :: 3 + License :: OSI Approved :: Apache Software License + Operating System :: OS Independent + +[options] +packages = find: +include_package_data = True +python_requires = >=3.6 + +[options.data_files] +didkit = didkit/libdidkit.so