2022-12-21 12:41:20 +03:00
|
|
|
import logging
|
2022-12-20 16:55:07 +03:00
|
|
|
from base64 import b64encode as b64enc
|
2022-12-16 15:51:14 +03:00
|
|
|
from hashlib import sha256
|
|
|
|
from uuid import uuid4
|
2022-12-19 16:27:10 +03:00
|
|
|
from os.path import join, dirname
|
2022-12-28 13:53:56 +03:00
|
|
|
from os import getenv as env
|
2022-12-21 12:41:20 +03:00
|
|
|
|
2022-12-21 12:53:51 +03:00
|
|
|
from dotenv import load_dotenv
|
2022-12-16 15:51:14 +03:00
|
|
|
from fastapi import FastAPI, HTTPException
|
|
|
|
from fastapi.requests import Request
|
|
|
|
import json
|
2022-12-19 15:11:28 +03:00
|
|
|
from datetime import datetime
|
|
|
|
from dateutil.relativedelta import relativedelta
|
2022-12-16 15:51:14 +03:00
|
|
|
from calendar import timegm
|
|
|
|
from jose import jws, jwk, jwt
|
|
|
|
from jose.constants import ALGORITHMS
|
2022-12-21 12:41:20 +03:00
|
|
|
from starlette.middleware.cors import CORSMiddleware
|
2022-12-29 12:35:15 +03:00
|
|
|
from starlette.responses import StreamingResponse, JSONResponse, HTMLResponse, Response, RedirectResponse
|
2022-12-22 14:57:06 +03:00
|
|
|
from sqlalchemy import create_engine
|
|
|
|
from sqlalchemy.orm import sessionmaker
|
2022-12-27 14:21:52 +03:00
|
|
|
|
2022-12-29 09:37:17 +03:00
|
|
|
from util import load_key, load_file
|
2022-12-29 11:40:36 +03:00
|
|
|
from orm import Origin, Lease, init as db_init, migrate
|
2022-12-22 14:57:06 +03:00
|
|
|
|
2022-12-21 12:40:05 +03:00
|
|
|
logger = logging.getLogger()
|
2022-12-21 13:06:09 +03:00
|
|
|
load_dotenv('../version.env')
|
2022-12-21 12:40:05 +03:00
|
|
|
|
2022-12-28 13:53:56 +03:00
|
|
|
VERSION, COMMIT, DEBUG = env('VERSION', 'unknown'), env('COMMIT', 'unknown'), bool(env('DEBUG', False))
|
2022-12-21 12:40:05 +03:00
|
|
|
|
2022-12-29 12:35:15 +03:00
|
|
|
config = dict(openapi_url='/-/openapi.json', docs_url='/-/docs', redoc_url='/-/redoc')
|
|
|
|
app = FastAPI(title='FastAPI-DLS', description='Minimal Delegated License Service (DLS).', version=VERSION, **config)
|
2022-12-28 13:53:56 +03:00
|
|
|
db = create_engine(str(env('DATABASE', 'sqlite:///db.sqlite')))
|
2022-12-29 11:40:36 +03:00
|
|
|
db_init(db), migrate(db)
|
2022-12-16 15:51:14 +03:00
|
|
|
|
2022-12-28 13:53:56 +03:00
|
|
|
DLS_URL = str(env('DLS_URL', 'localhost'))
|
|
|
|
DLS_PORT = int(env('DLS_PORT', '443'))
|
|
|
|
SITE_KEY_XID = str(env('SITE_KEY_XID', '00000000-0000-0000-0000-000000000000'))
|
|
|
|
INSTANCE_REF = str(env('INSTANCE_REF', '00000000-0000-0000-0000-000000000000'))
|
|
|
|
INSTANCE_KEY_RSA = load_key(str(env('INSTANCE_KEY_RSA', join(dirname(__file__), 'cert/instance.private.pem'))))
|
|
|
|
INSTANCE_KEY_PUB = load_key(str(env('INSTANCE_KEY_PUB', join(dirname(__file__), 'cert/instance.public.pem'))))
|
2022-12-28 11:23:17 +03:00
|
|
|
TOKEN_EXPIRE_DELTA = relativedelta(hours=1) # days=1
|
2022-12-28 13:53:56 +03:00
|
|
|
LEASE_EXPIRE_DELTA = relativedelta(days=int(env('LEASE_EXPIRE_DAYS', 90)))
|
2022-12-30 09:42:57 +03:00
|
|
|
CORS_ORIGINS = str(env('CORS_ORIGINS', '')).split(',') if (env('CORS_ORIGINS')) else [f'https://{DLS_URL}']
|
2022-12-21 12:41:20 +03:00
|
|
|
|
2022-12-20 16:55:07 +03:00
|
|
|
jwt_encode_key = jwk.construct(INSTANCE_KEY_RSA.export_key().decode('utf-8'), algorithm=ALGORITHMS.RS256)
|
2022-12-28 13:33:06 +03:00
|
|
|
jwt_decode_key = jwk.construct(INSTANCE_KEY_PUB.export_key().decode('utf-8'), algorithm=ALGORITHMS.RS256)
|
2022-12-20 16:55:07 +03:00
|
|
|
|
2022-12-21 12:41:20 +03:00
|
|
|
app.debug = DEBUG
|
|
|
|
app.add_middleware(
|
|
|
|
CORSMiddleware,
|
|
|
|
allow_origins=CORS_ORIGINS,
|
|
|
|
allow_credentials=True,
|
2022-12-29 22:40:42 +03:00
|
|
|
allow_methods=['*'],
|
|
|
|
allow_headers=['*'],
|
2022-12-21 12:41:20 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
logger.setLevel(logging.DEBUG if DEBUG else logging.INFO)
|
|
|
|
|
2022-12-16 15:51:14 +03:00
|
|
|
|
2022-12-29 22:42:40 +03:00
|
|
|
def __get_token(request: Request) -> dict:
|
2022-12-29 22:40:42 +03:00
|
|
|
authorization_header = request.headers.get('authorization')
|
2022-12-20 20:06:32 +03:00
|
|
|
token = authorization_header.split(' ')[1]
|
2022-12-21 10:00:52 +03:00
|
|
|
return jwt.decode(token=token, key=jwt_decode_key, algorithms=ALGORITHMS.RS256, options={'verify_aud': False})
|
2022-12-20 20:06:32 +03:00
|
|
|
|
|
|
|
|
2022-12-29 22:41:02 +03:00
|
|
|
@app.get('/', summary='Index')
|
2022-12-16 15:51:14 +03:00
|
|
|
async def index():
|
2022-12-29 12:31:25 +03:00
|
|
|
return RedirectResponse('/-/readme')
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
|
2022-12-29 20:48:30 +03:00
|
|
|
@app.get('/status', summary='* Status', description='returns current service status, version (incl. git-commit) and some variables.', deprecated=True)
|
2022-12-16 15:53:32 +03:00
|
|
|
async def status(request: Request):
|
2022-12-21 12:40:05 +03:00
|
|
|
return JSONResponse({'status': 'up', 'version': VERSION, 'commit': COMMIT, 'debug': DEBUG})
|
2022-12-16 15:53:32 +03:00
|
|
|
|
|
|
|
|
2022-12-29 22:41:02 +03:00
|
|
|
@app.get('/-/', summary='* Index')
|
|
|
|
async def _index():
|
|
|
|
return RedirectResponse('/-/readme')
|
|
|
|
|
|
|
|
|
2022-12-29 12:31:25 +03:00
|
|
|
@app.get('/-/health', summary='* Health')
|
|
|
|
async def _health(request: Request):
|
|
|
|
return JSONResponse({'status': 'up', 'version': VERSION, 'commit': COMMIT, 'debug': DEBUG})
|
|
|
|
|
|
|
|
|
|
|
|
@app.get('/-/readme', summary='* Readme')
|
|
|
|
async def _readme():
|
|
|
|
from markdown import markdown
|
|
|
|
content = load_file('../README.md').decode('utf-8')
|
|
|
|
return HTMLResponse(markdown(text=content, extensions=['tables', 'fenced_code', 'md_in_html', 'nl2br', 'toc']))
|
|
|
|
|
|
|
|
|
|
|
|
@app.get('/-/manage', summary='* Management UI')
|
2022-12-29 12:12:31 +03:00
|
|
|
async def _manage(request: Request):
|
|
|
|
response = '''
|
|
|
|
<!DOCTYPE html>
|
|
|
|
<html>
|
|
|
|
<head>
|
|
|
|
<title>FastAPI-DLS Management</title>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<button onclick="deleteOrigins()">delete origins and their leases</button>
|
|
|
|
<button onclick="deleteLease()">delete specific lease</button>
|
|
|
|
|
|
|
|
<script>
|
|
|
|
function deleteOrigins() {
|
|
|
|
var xhr = new XMLHttpRequest();
|
|
|
|
xhr.open("DELETE", '/-/origins', true);
|
|
|
|
xhr.send();
|
|
|
|
}
|
|
|
|
function deleteLease(lease_ref) {
|
|
|
|
if(lease_ref === undefined)
|
|
|
|
lease_ref = window.prompt("Please enter 'lease_ref' which should be deleted");
|
|
|
|
if(lease_ref === null || lease_ref === "")
|
|
|
|
return
|
|
|
|
var xhr = new XMLHttpRequest();
|
|
|
|
xhr.open("DELETE", `/-/lease/${lease_ref}`, true);
|
|
|
|
xhr.send();
|
|
|
|
}
|
|
|
|
</script>
|
|
|
|
</body>
|
|
|
|
</html>
|
|
|
|
'''
|
|
|
|
return HTMLResponse(response)
|
|
|
|
|
|
|
|
|
2022-12-29 12:35:15 +03:00
|
|
|
@app.get('/-/origins', summary='* Origins')
|
2022-12-29 11:00:52 +03:00
|
|
|
async def _origins(request: Request, leases: bool = False):
|
2022-12-23 15:21:52 +03:00
|
|
|
session = sessionmaker(bind=db)()
|
2022-12-29 11:00:52 +03:00
|
|
|
response = []
|
|
|
|
for origin in session.query(Origin).all():
|
|
|
|
x = origin.serialize()
|
|
|
|
if leases:
|
|
|
|
x['leases'] = list(map(lambda _: _.serialize(), Lease.find_by_origin_ref(db, origin.origin_ref)))
|
|
|
|
response.append(x)
|
2022-12-22 14:57:06 +03:00
|
|
|
session.close()
|
2022-12-20 20:24:59 +03:00
|
|
|
return JSONResponse(response)
|
|
|
|
|
|
|
|
|
2022-12-29 12:35:15 +03:00
|
|
|
@app.delete('/-/origins', summary='* Origins')
|
2022-12-29 11:57:37 +03:00
|
|
|
async def _origins_delete(request: Request):
|
|
|
|
Origin.delete(db)
|
|
|
|
return Response(status_code=201)
|
|
|
|
|
|
|
|
|
2022-12-29 12:35:15 +03:00
|
|
|
@app.get('/-/leases', summary='* Leases')
|
2022-12-29 11:00:52 +03:00
|
|
|
async def _leases(request: Request, origin: bool = False):
|
2022-12-23 15:21:52 +03:00
|
|
|
session = sessionmaker(bind=db)()
|
2022-12-29 11:00:52 +03:00
|
|
|
response = []
|
|
|
|
for lease in session.query(Lease).all():
|
|
|
|
x = lease.serialize()
|
|
|
|
if origin:
|
|
|
|
# assume that each lease has a valid origin record
|
|
|
|
x['origin'] = session.query(Origin).filter(Origin.origin_ref == lease.origin_ref).first().serialize()
|
|
|
|
response.append(x)
|
2022-12-22 14:57:06 +03:00
|
|
|
session.close()
|
2022-12-20 20:24:59 +03:00
|
|
|
return JSONResponse(response)
|
|
|
|
|
|
|
|
|
2022-12-29 12:35:15 +03:00
|
|
|
@app.delete('/-/lease/{lease_ref}', summary='* Lease')
|
2022-12-29 11:57:37 +03:00
|
|
|
async def _lease_delete(request: Request, lease_ref: str):
|
|
|
|
if Lease.delete(db, lease_ref) == 1:
|
|
|
|
return Response(status_code=201)
|
|
|
|
raise HTTPException(status_code=404, detail='lease not found')
|
|
|
|
|
|
|
|
|
2022-12-16 15:51:14 +03:00
|
|
|
# venv/lib/python3.9/site-packages/nls_core_service_instance/service_instance_token_manager.py
|
2022-12-29 22:33:50 +03:00
|
|
|
@app.get('/-/client-token', summary='* Client-Token', description='creates a new messenger token for this service instance')
|
|
|
|
async def _client_token():
|
2022-12-16 15:51:14 +03:00
|
|
|
cur_time = datetime.utcnow()
|
2022-12-19 15:11:28 +03:00
|
|
|
exp_time = cur_time + relativedelta(years=12)
|
2022-12-19 17:51:49 +03:00
|
|
|
|
2022-12-16 15:51:14 +03:00
|
|
|
payload = {
|
|
|
|
"jti": str(uuid4()),
|
|
|
|
"iss": "NLS Service Instance",
|
|
|
|
"aud": "NLS Licensed Client",
|
2022-12-19 15:52:16 +03:00
|
|
|
"iat": timegm(cur_time.timetuple()),
|
|
|
|
"nbf": timegm(cur_time.timetuple()),
|
|
|
|
"exp": timegm(exp_time.timetuple()),
|
2022-12-16 15:51:14 +03:00
|
|
|
"update_mode": "ABSOLUTE",
|
2022-12-29 11:01:36 +03:00
|
|
|
"scope_ref_list": [str(uuid4())], # this is our LEASE_REF
|
2022-12-16 15:51:14 +03:00
|
|
|
"fulfillment_class_ref_list": [],
|
|
|
|
"service_instance_configuration": {
|
2022-12-23 15:22:06 +03:00
|
|
|
"nls_service_instance_ref": INSTANCE_REF,
|
2022-12-16 15:51:14 +03:00
|
|
|
"svc_port_set_list": [
|
|
|
|
{
|
|
|
|
"idx": 0,
|
|
|
|
"d_name": "DLS",
|
2022-12-20 20:06:32 +03:00
|
|
|
"svc_port_map": [{"service": "auth", "port": DLS_PORT}, {"service": "lease", "port": DLS_PORT}]
|
2022-12-16 15:51:14 +03:00
|
|
|
}
|
|
|
|
],
|
2022-12-19 16:44:26 +03:00
|
|
|
"node_url_list": [{"idx": 0, "url": DLS_URL, "url_qr": DLS_URL, "svc_port_set_idx": 0}]
|
2022-12-16 15:51:14 +03:00
|
|
|
},
|
2022-12-23 15:22:06 +03:00
|
|
|
"service_instance_public_key_configuration": {
|
|
|
|
"service_instance_public_key_me": {
|
|
|
|
"mod": hex(INSTANCE_KEY_PUB.public_key().n)[2:],
|
2022-12-23 15:31:23 +03:00
|
|
|
"exp": int(INSTANCE_KEY_PUB.public_key().e),
|
2022-12-23 15:22:06 +03:00
|
|
|
},
|
|
|
|
"service_instance_public_key_pem": INSTANCE_KEY_PUB.export_key().decode('utf-8'),
|
|
|
|
"key_retention_mode": "LATEST_ONLY"
|
|
|
|
},
|
2022-12-16 15:51:14 +03:00
|
|
|
}
|
|
|
|
|
2022-12-21 10:00:52 +03:00
|
|
|
content = jws.sign(payload, key=jwt_encode_key, headers=None, algorithm=ALGORITHMS.RS256)
|
2022-12-16 15:51:14 +03:00
|
|
|
|
2022-12-20 20:06:32 +03:00
|
|
|
response = StreamingResponse(iter([content]), media_type="text/plain")
|
2022-12-30 05:50:48 +03:00
|
|
|
filename = f'client_configuration_token_{datetime.now().strftime("%d-%m-%y-%H-%M-%S")}.tok'
|
2022-12-20 00:20:50 +03:00
|
|
|
response.headers["Content-Disposition"] = f'attachment; filename={filename}'
|
2022-12-20 20:06:32 +03:00
|
|
|
|
2022-12-16 15:51:14 +03:00
|
|
|
return response
|
|
|
|
|
|
|
|
|
2022-12-29 22:33:50 +03:00
|
|
|
@app.get('/client-token', summary='* Client-Token', description='creates a new messenger token for this service instance', deprecated=True)
|
|
|
|
async def client_token():
|
|
|
|
return RedirectResponse('/-/client-token')
|
|
|
|
|
|
|
|
|
2022-12-16 15:51:14 +03:00
|
|
|
# venv/lib/python3.9/site-packages/nls_services_auth/test/test_origins_controller.py
|
2022-12-20 16:55:07 +03:00
|
|
|
# {"candidate_origin_ref":"00112233-4455-6677-8899-aabbccddeeff","environment":{"fingerprint":{"mac_address_list":["ff:ff:ff:ff:ff:ff"]},"hostname":"my-hostname","ip_address_list":["192.168.178.123","fe80::","fe80::1%enp6s18"],"guest_driver_version":"510.85.02","os_platform":"Debian GNU/Linux 11 (bullseye) 11","os_version":"11 (bullseye)"},"registration_pending":false,"update_pending":false}
|
2022-12-29 20:48:30 +03:00
|
|
|
@app.post('/auth/v1/origin', description='find or create an origin')
|
2022-12-21 10:00:52 +03:00
|
|
|
async def auth_v1_origin(request: Request):
|
2022-12-23 15:31:23 +03:00
|
|
|
j, cur_time = json.loads((await request.body()).decode('utf-8')), datetime.utcnow()
|
2022-12-20 16:55:07 +03:00
|
|
|
|
2022-12-20 20:06:32 +03:00
|
|
|
origin_ref = j['candidate_origin_ref']
|
2022-12-21 12:45:45 +03:00
|
|
|
logging.info(f'> [ origin ]: {origin_ref}: {j}')
|
2022-12-20 16:55:07 +03:00
|
|
|
|
2022-12-22 14:57:06 +03:00
|
|
|
data = Origin(
|
2022-12-20 20:06:32 +03:00
|
|
|
origin_ref=origin_ref,
|
2022-12-20 16:55:07 +03:00
|
|
|
hostname=j['environment']['hostname'],
|
|
|
|
guest_driver_version=j['environment']['guest_driver_version'],
|
2022-12-20 20:06:32 +03:00
|
|
|
os_platform=j['environment']['os_platform'], os_version=j['environment']['os_version'],
|
2022-12-20 16:55:07 +03:00
|
|
|
)
|
2022-12-20 20:06:32 +03:00
|
|
|
|
2022-12-22 14:57:06 +03:00
|
|
|
Origin.create_or_update(db, data)
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
response = {
|
2022-12-20 20:06:32 +03:00
|
|
|
"origin_ref": origin_ref,
|
2022-12-19 17:51:49 +03:00
|
|
|
"environment": j['environment'],
|
2022-12-16 15:51:14 +03:00
|
|
|
"svc_port_set_list": None,
|
|
|
|
"node_url_list": None,
|
|
|
|
"node_query_order": None,
|
|
|
|
"prompts": None,
|
2022-12-20 08:47:40 +03:00
|
|
|
"sync_timestamp": cur_time.isoformat()
|
2022-12-16 15:51:14 +03:00
|
|
|
}
|
2022-12-20 20:06:32 +03:00
|
|
|
|
2022-12-20 08:47:40 +03:00
|
|
|
return JSONResponse(response)
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
|
2022-12-27 21:03:03 +03:00
|
|
|
# venv/lib/python3.9/site-packages/nls_services_auth/test/test_origins_controller.py
|
|
|
|
# { "environment" : { "guest_driver_version" : "guest_driver_version", "hostname" : "myhost", "ip_address_list" : [ "192.168.1.129" ], "os_version" : "os_version", "os_platform" : "os_platform", "fingerprint" : { "mac_address_list" : [ "e4:b9:7a:e5:7b:ff" ] }, "host_driver_version" : "host_driver_version" }, "origin_ref" : "00112233-4455-6677-8899-aabbccddeeff" }
|
2022-12-29 20:48:30 +03:00
|
|
|
@app.post('/auth/v1/origin/update', description='update an origin evidence')
|
2022-12-27 21:03:03 +03:00
|
|
|
async def auth_v1_origin_update(request: Request):
|
|
|
|
j, cur_time = json.loads((await request.body()).decode('utf-8')), datetime.utcnow()
|
|
|
|
|
|
|
|
origin_ref = j['origin_ref']
|
|
|
|
logging.info(f'> [ update ]: {origin_ref}: {j}')
|
|
|
|
|
2022-12-27 21:05:41 +03:00
|
|
|
data = Origin(
|
2022-12-27 21:03:03 +03:00
|
|
|
origin_ref=origin_ref,
|
|
|
|
hostname=j['environment']['hostname'],
|
|
|
|
guest_driver_version=j['environment']['guest_driver_version'],
|
|
|
|
os_platform=j['environment']['os_platform'], os_version=j['environment']['os_version'],
|
|
|
|
)
|
|
|
|
|
2022-12-27 21:05:41 +03:00
|
|
|
Origin.create_or_update(db, data)
|
2022-12-27 21:03:03 +03:00
|
|
|
|
|
|
|
response = {
|
|
|
|
"environment": j['environment'],
|
|
|
|
"prompts": None,
|
|
|
|
"sync_timestamp": cur_time.isoformat()
|
|
|
|
}
|
|
|
|
|
|
|
|
return JSONResponse(response)
|
|
|
|
|
|
|
|
|
2022-12-16 15:51:14 +03:00
|
|
|
# venv/lib/python3.9/site-packages/nls_services_auth/test/test_auth_controller.py
|
|
|
|
# venv/lib/python3.9/site-packages/nls_core_auth/auth.py - CodeResponse
|
2022-12-20 16:55:07 +03:00
|
|
|
# {"code_challenge":"...","origin_ref":"00112233-4455-6677-8899-aabbccddeeff"}
|
2022-12-29 20:48:30 +03:00
|
|
|
@app.post('/auth/v1/code', description='get an authorization code')
|
2022-12-21 10:00:52 +03:00
|
|
|
async def auth_v1_code(request: Request):
|
2022-12-23 15:31:23 +03:00
|
|
|
j, cur_time = json.loads((await request.body()).decode('utf-8')), datetime.utcnow()
|
2022-12-20 16:55:07 +03:00
|
|
|
|
|
|
|
origin_ref = j['origin_ref']
|
2022-12-21 12:45:45 +03:00
|
|
|
logging.info(f'> [ code ]: {origin_ref}: {j}')
|
2022-12-16 15:51:14 +03:00
|
|
|
|
2022-12-20 20:06:32 +03:00
|
|
|
delta = relativedelta(minutes=15)
|
|
|
|
expires = cur_time + delta
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
payload = {
|
|
|
|
'iat': timegm(cur_time.timetuple()),
|
|
|
|
'exp': timegm(expires.timetuple()),
|
|
|
|
'challenge': j['code_challenge'],
|
2022-12-23 08:56:29 +03:00
|
|
|
'origin_ref': j['origin_ref'],
|
2022-12-16 15:51:14 +03:00
|
|
|
'key_ref': SITE_KEY_XID,
|
|
|
|
'kid': SITE_KEY_XID
|
|
|
|
}
|
|
|
|
|
2022-12-21 10:00:52 +03:00
|
|
|
auth_code = jws.sign(payload, key=jwt_encode_key, headers={'kid': payload.get('kid')}, algorithm=ALGORITHMS.RS256)
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
response = {
|
|
|
|
"auth_code": auth_code,
|
2022-12-20 08:47:40 +03:00
|
|
|
"sync_timestamp": cur_time.isoformat(),
|
2022-12-16 15:51:14 +03:00
|
|
|
"prompts": None
|
|
|
|
}
|
2022-12-20 20:06:32 +03:00
|
|
|
|
2022-12-20 08:47:40 +03:00
|
|
|
return JSONResponse(response)
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
|
|
|
|
# venv/lib/python3.9/site-packages/nls_services_auth/test/test_auth_controller.py
|
|
|
|
# venv/lib/python3.9/site-packages/nls_core_auth/auth.py - TokenResponse
|
2022-12-20 16:55:07 +03:00
|
|
|
# {"auth_code":"...","code_verifier":"..."}
|
2022-12-29 20:48:30 +03:00
|
|
|
@app.post('/auth/v1/token', description='exchange auth code and verifier for token')
|
2022-12-21 10:00:52 +03:00
|
|
|
async def auth_v1_token(request: Request):
|
2022-12-23 15:31:23 +03:00
|
|
|
j, cur_time = json.loads((await request.body()).decode('utf-8')), datetime.utcnow()
|
2022-12-28 13:33:06 +03:00
|
|
|
payload = jwt.decode(token=j['auth_code'], key=jwt_decode_key)
|
2022-12-16 15:51:14 +03:00
|
|
|
|
2022-12-23 08:56:29 +03:00
|
|
|
origin_ref = payload['origin_ref']
|
|
|
|
logging.info(f'> [ auth ]: {origin_ref}: {j}')
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
# validate the code challenge
|
2022-12-20 16:55:07 +03:00
|
|
|
if payload['challenge'] != b64enc(sha256(j['code_verifier'].encode('utf-8')).digest()).rstrip(b'=').decode('utf-8'):
|
2022-12-20 20:06:32 +03:00
|
|
|
raise HTTPException(status_code=401, detail='expected challenge did not match verifier')
|
2022-12-16 15:51:14 +03:00
|
|
|
|
2022-12-20 20:06:32 +03:00
|
|
|
access_expires_on = cur_time + TOKEN_EXPIRE_DELTA
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
new_payload = {
|
|
|
|
'iat': timegm(cur_time.timetuple()),
|
|
|
|
'nbf': timegm(cur_time.timetuple()),
|
|
|
|
'iss': 'https://cls.nvidia.org',
|
|
|
|
'aud': 'https://cls.nvidia.org',
|
|
|
|
'exp': timegm(access_expires_on.timetuple()),
|
2022-12-23 08:56:29 +03:00
|
|
|
'origin_ref': origin_ref,
|
2022-12-16 15:51:14 +03:00
|
|
|
'key_ref': SITE_KEY_XID,
|
|
|
|
'kid': SITE_KEY_XID,
|
|
|
|
}
|
|
|
|
|
2022-12-21 10:00:52 +03:00
|
|
|
auth_token = jwt.encode(new_payload, key=jwt_encode_key, headers={'kid': payload.get('kid')}, algorithm=ALGORITHMS.RS256)
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
response = {
|
2022-12-20 08:47:40 +03:00
|
|
|
"expires": access_expires_on.isoformat(),
|
2022-12-16 15:51:14 +03:00
|
|
|
"auth_token": auth_token,
|
2022-12-20 08:47:40 +03:00
|
|
|
"sync_timestamp": cur_time.isoformat(),
|
2022-12-16 15:51:14 +03:00
|
|
|
}
|
|
|
|
|
2022-12-20 08:47:40 +03:00
|
|
|
return JSONResponse(response)
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
|
2022-12-20 16:55:07 +03:00
|
|
|
# {'fulfillment_context': {'fulfillment_class_ref_list': []}, 'lease_proposal_list': [{'license_type_qualifiers': {'count': 1}, 'product': {'name': 'NVIDIA RTX Virtual Workstation'}}], 'proposal_evaluation_mode': 'ALL_OF', 'scope_ref_list': ['00112233-4455-6677-8899-aabbccddeeff']}
|
2022-12-29 20:48:30 +03:00
|
|
|
@app.post('/leasing/v1/lessor', description='request multiple leases (borrow) for current origin')
|
2022-12-21 10:00:52 +03:00
|
|
|
async def leasing_v1_lessor(request: Request):
|
2022-12-29 22:42:40 +03:00
|
|
|
j, token, cur_time = json.loads((await request.body()).decode('utf-8')), __get_token(request), datetime.utcnow()
|
2022-12-20 16:55:07 +03:00
|
|
|
|
2022-12-29 20:59:26 +03:00
|
|
|
origin_ref = token.get('origin_ref')
|
2022-12-20 16:55:07 +03:00
|
|
|
scope_ref_list = j['scope_ref_list']
|
2022-12-23 08:56:29 +03:00
|
|
|
logging.info(f'> [ create ]: {origin_ref}: create leases for scope_ref_list {scope_ref_list}')
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
lease_result_list = []
|
2022-12-20 16:55:07 +03:00
|
|
|
for scope_ref in scope_ref_list:
|
2022-12-20 20:06:32 +03:00
|
|
|
expires = cur_time + LEASE_EXPIRE_DELTA
|
2022-12-16 15:51:14 +03:00
|
|
|
lease_result_list.append({
|
|
|
|
"ordinal": 0,
|
2022-12-20 20:06:32 +03:00
|
|
|
# https://docs.nvidia.com/license-system/latest/nvidia-license-system-user-guide/index.html
|
2022-12-16 15:51:14 +03:00
|
|
|
"lease": {
|
|
|
|
"ref": scope_ref,
|
2022-12-20 08:47:40 +03:00
|
|
|
"created": cur_time.isoformat(),
|
2022-12-20 20:06:32 +03:00
|
|
|
"expires": expires.isoformat(),
|
|
|
|
# The percentage of the lease period that must elapse before a licensed client can renew a license
|
2022-12-16 15:51:14 +03:00
|
|
|
"recommended_lease_renewal": 0.15,
|
|
|
|
"offline_lease": "true",
|
|
|
|
"license_type": "CONCURRENT_COUNTED_SINGLE"
|
|
|
|
}
|
|
|
|
})
|
2022-12-20 20:06:32 +03:00
|
|
|
|
2022-12-22 14:57:06 +03:00
|
|
|
data = Lease(origin_ref=origin_ref, lease_ref=scope_ref, lease_created=cur_time, lease_expires=expires)
|
|
|
|
Lease.create_or_update(db, data)
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
response = {
|
|
|
|
"lease_result_list": lease_result_list,
|
|
|
|
"result_code": "SUCCESS",
|
2022-12-20 08:47:40 +03:00
|
|
|
"sync_timestamp": cur_time.isoformat(),
|
2022-12-16 15:51:14 +03:00
|
|
|
"prompts": None
|
|
|
|
}
|
|
|
|
|
2022-12-20 08:47:40 +03:00
|
|
|
return JSONResponse(response)
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
|
|
|
|
# venv/lib/python3.9/site-packages/nls_services_lease/test/test_lease_multi_controller.py
|
2022-12-20 20:06:32 +03:00
|
|
|
# venv/lib/python3.9/site-packages/nls_dal_service_instance_dls/schema/service_instance/V1_0_21__product_mapping.sql
|
2022-12-29 20:48:30 +03:00
|
|
|
@app.get('/leasing/v1/lessor/leases', description='get active leases for current origin')
|
2022-12-21 10:00:52 +03:00
|
|
|
async def leasing_v1_lessor_lease(request: Request):
|
2022-12-29 22:42:40 +03:00
|
|
|
token, cur_time = __get_token(request), datetime.utcnow()
|
2022-12-20 16:55:07 +03:00
|
|
|
|
2022-12-29 20:59:26 +03:00
|
|
|
origin_ref = token.get('origin_ref')
|
2022-12-20 16:55:07 +03:00
|
|
|
|
2022-12-27 22:05:55 +03:00
|
|
|
active_lease_list = list(map(lambda x: x.lease_ref, Lease.find_by_origin_ref(db, origin_ref)))
|
2022-12-23 08:56:29 +03:00
|
|
|
logging.info(f'> [ leases ]: {origin_ref}: found {len(active_lease_list)} active leases')
|
2022-12-20 16:55:07 +03:00
|
|
|
|
2022-12-16 15:51:14 +03:00
|
|
|
response = {
|
2022-12-20 16:55:07 +03:00
|
|
|
"active_lease_list": active_lease_list,
|
2022-12-20 08:47:40 +03:00
|
|
|
"sync_timestamp": cur_time.isoformat(),
|
2022-12-16 15:51:14 +03:00
|
|
|
"prompts": None
|
|
|
|
}
|
|
|
|
|
2022-12-20 08:47:40 +03:00
|
|
|
return JSONResponse(response)
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
|
2022-12-19 15:15:19 +03:00
|
|
|
# venv/lib/python3.9/site-packages/nls_core_lease/lease_single.py
|
2022-12-29 20:48:30 +03:00
|
|
|
@app.put('/leasing/v1/lease/{lease_ref}', description='renew a lease')
|
2022-12-21 10:00:52 +03:00
|
|
|
async def leasing_v1_lease_renew(request: Request, lease_ref: str):
|
2022-12-29 22:42:40 +03:00
|
|
|
token, cur_time = __get_token(request), datetime.utcnow()
|
2022-12-20 16:55:07 +03:00
|
|
|
|
2022-12-29 20:59:26 +03:00
|
|
|
origin_ref = token.get('origin_ref')
|
2022-12-23 08:56:29 +03:00
|
|
|
logging.info(f'> [ renew ]: {origin_ref}: renew {lease_ref}')
|
2022-12-20 20:06:32 +03:00
|
|
|
|
2022-12-22 14:57:06 +03:00
|
|
|
entity = Lease.find_by_origin_ref_and_lease_ref(db, origin_ref, lease_ref)
|
|
|
|
if entity is None:
|
2022-12-20 20:06:32 +03:00
|
|
|
raise HTTPException(status_code=404, detail='requested lease not available')
|
2022-12-19 15:15:19 +03:00
|
|
|
|
2022-12-20 16:55:07 +03:00
|
|
|
expires = cur_time + LEASE_EXPIRE_DELTA
|
2022-12-19 15:15:19 +03:00
|
|
|
response = {
|
|
|
|
"lease_ref": lease_ref,
|
2022-12-20 16:55:07 +03:00
|
|
|
"expires": expires.isoformat(),
|
2022-12-19 15:15:19 +03:00
|
|
|
"recommended_lease_renewal": 0.16,
|
|
|
|
"offline_lease": True,
|
|
|
|
"prompts": None,
|
2022-12-20 08:47:40 +03:00
|
|
|
"sync_timestamp": cur_time.isoformat(),
|
2022-12-19 15:15:19 +03:00
|
|
|
}
|
|
|
|
|
2022-12-22 14:57:06 +03:00
|
|
|
Lease.renew(db, entity, expires, cur_time)
|
2022-12-20 16:55:07 +03:00
|
|
|
|
2022-12-20 08:47:40 +03:00
|
|
|
return JSONResponse(response)
|
2022-12-19 15:15:19 +03:00
|
|
|
|
|
|
|
|
2022-12-29 21:03:09 +03:00
|
|
|
@app.delete('/leasing/v1/lease/{lease_ref}', description='release (return) a lease')
|
|
|
|
async def leasing_v1_lease_delete(request: Request, lease_ref: str):
|
2022-12-29 22:42:40 +03:00
|
|
|
token, cur_time = __get_token(request), datetime.utcnow()
|
2022-12-29 21:03:09 +03:00
|
|
|
|
|
|
|
origin_ref = token.get('origin_ref')
|
|
|
|
logging.info(f'> [ return ]: {origin_ref}: return {lease_ref}')
|
|
|
|
|
|
|
|
entity = Lease.find_by_lease_ref(db, lease_ref)
|
|
|
|
if entity.origin_ref != origin_ref:
|
|
|
|
raise HTTPException(status_code=403, detail='access or operation forbidden')
|
|
|
|
if entity is None:
|
|
|
|
raise HTTPException(status_code=404, detail='requested lease not available')
|
|
|
|
|
|
|
|
if Lease.delete(db, lease_ref) == 0:
|
|
|
|
raise HTTPException(status_code=404, detail='lease not found')
|
|
|
|
|
|
|
|
response = {
|
|
|
|
"lease_ref": lease_ref,
|
|
|
|
"prompts": None,
|
|
|
|
"sync_timestamp": cur_time.isoformat(),
|
|
|
|
}
|
|
|
|
|
|
|
|
return JSONResponse(response)
|
|
|
|
|
|
|
|
|
2022-12-29 20:48:30 +03:00
|
|
|
@app.delete('/leasing/v1/lessor/leases', description='release all leases')
|
2022-12-21 10:00:52 +03:00
|
|
|
async def leasing_v1_lessor_lease_remove(request: Request):
|
2022-12-29 22:42:40 +03:00
|
|
|
token, cur_time = __get_token(request), datetime.utcnow()
|
2022-12-20 16:55:07 +03:00
|
|
|
|
2022-12-29 20:59:26 +03:00
|
|
|
origin_ref = token.get('origin_ref')
|
2022-12-22 14:57:06 +03:00
|
|
|
|
|
|
|
released_lease_list = list(map(lambda x: x.lease_ref, Lease.find_by_origin_ref(db, origin_ref)))
|
2022-12-27 22:10:18 +03:00
|
|
|
deletions = Lease.cleanup(db, origin_ref)
|
2022-12-23 08:56:29 +03:00
|
|
|
logging.info(f'> [ remove ]: {origin_ref}: removed {deletions} leases')
|
2022-12-20 16:55:07 +03:00
|
|
|
|
2022-12-16 15:51:14 +03:00
|
|
|
response = {
|
2022-12-20 16:55:07 +03:00
|
|
|
"released_lease_list": released_lease_list,
|
2022-12-16 15:51:14 +03:00
|
|
|
"release_failure_list": None,
|
2022-12-20 08:47:40 +03:00
|
|
|
"sync_timestamp": cur_time.isoformat(),
|
2022-12-16 15:51:14 +03:00
|
|
|
"prompts": None
|
|
|
|
}
|
2022-12-23 15:31:23 +03:00
|
|
|
|
2022-12-20 08:47:40 +03:00
|
|
|
return JSONResponse(response)
|
2022-12-16 15:51:14 +03:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
import uvicorn
|
|
|
|
|
2022-12-19 15:35:03 +03:00
|
|
|
###
|
|
|
|
#
|
|
|
|
# Running `python app/main.py` assumes that the user created a keypair, e.g. with openssl.
|
|
|
|
#
|
|
|
|
# openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout app/cert/webserver.key -out app/cert/webserver.crt
|
|
|
|
#
|
|
|
|
###
|
2022-12-16 15:51:14 +03:00
|
|
|
|
2022-12-21 12:45:45 +03:00
|
|
|
logging.info(f'> Starting dev-server ...')
|
2022-12-19 15:35:03 +03:00
|
|
|
|
2022-12-19 16:27:10 +03:00
|
|
|
ssl_keyfile = join(dirname(__file__), 'cert/webserver.key')
|
|
|
|
ssl_certfile = join(dirname(__file__), 'cert/webserver.crt')
|
2022-12-19 15:35:03 +03:00
|
|
|
|
|
|
|
uvicorn.run('main:app', host='0.0.0.0', port=443, ssl_keyfile=ssl_keyfile, ssl_certfile=ssl_certfile, reload=True)
|