|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# |
| 3 | +# This file is part of SENAITE.JSONAPI. |
| 4 | +# |
| 5 | +# SENAITE.JSONAPI is free software: you can redistribute it and/or modify it |
| 6 | +# under the terms of the GNU General Public License as published by the Free |
| 7 | +# Software Foundation, version 2. |
| 8 | +# |
| 9 | +# This program is distributed in the hope that it will be useful, but WITHOUT |
| 10 | +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
| 11 | +# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
| 12 | +# details. |
| 13 | +# |
| 14 | +# You should have received a copy of the GNU General Public License along with |
| 15 | +# this program; if not, write to the Free Software Foundation, Inc., 51 |
| 16 | +# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
| 17 | +# |
| 18 | +# Copyright 2017-2026 by it's authors. |
| 19 | +# Some rights reserved, see README and LICENSE. |
| 20 | + |
| 21 | +from calendar import timegm |
| 22 | +from datetime import timedelta |
| 23 | + |
| 24 | +import jwt |
| 25 | +from AccessControl import ClassSecurityInfo |
| 26 | +from bika.lims import api |
| 27 | +from BTrees.OOBTree import OOBTree |
| 28 | +from plone.keyring.keyring import GenerateSecret |
| 29 | +from Products.PluggableAuthService.interfaces import plugins |
| 30 | +from Products.PluggableAuthService.plugins.BasePlugin import BasePlugin |
| 31 | +from senaite.core.api import dtime |
| 32 | +from senaite.jsonapi import PRODUCT_NAME |
| 33 | +from senaite.jsonapi.config import JWT_COOKIE_ID |
| 34 | +from senaite.jsonapi.config import JWT_HEADER_ID |
| 35 | +from senaite.jsonapi.config import JWT_TOKENS_TIMEOUT |
| 36 | +from senaite.jsonapi.config import KEY_STORAGE |
| 37 | +from zope.annotation.interfaces import IAnnotations |
| 38 | +from zope.interface import implementer |
| 39 | + |
| 40 | +# The id of the plugin |
| 41 | +ID = "%s.pas.plugin.JWTAuthenticationPlugin" % PRODUCT_NAME |
| 42 | + |
| 43 | +# Meta type name of the plugin |
| 44 | +META_TYPE = "%s: JWT Authentication Plugin" % PRODUCT_NAME |
| 45 | + |
| 46 | + |
| 47 | +@implementer(plugins.IAuthenticationPlugin, plugins.IExtractionPlugin) |
| 48 | +class JWTAuthenticationPlugin(BasePlugin): |
| 49 | + """PAS plugin for authentication with JSON Web tokens (JWT). |
| 50 | +
|
| 51 | + JWT authentication is a stateless, token-based method where the SENAITE |
| 52 | + server issues a signed token to a client after a user logs in. The client |
| 53 | + then stores this token and includes it in subsequent requests to access |
| 54 | + protected resources, allowing the server to verify the user's identity |
| 55 | + without needing to store session data on the server-side. |
| 56 | + """ |
| 57 | + |
| 58 | + id = ID |
| 59 | + title = META_TYPE |
| 60 | + meta_type = META_TYPE |
| 61 | + security = ClassSecurityInfo() |
| 62 | + |
| 63 | + @security.private |
| 64 | + def extractCredentials(self, request): # noqa camelCase |
| 65 | + """IExtractionPlugin implementation. Extracts the JSON Web Token (JWT) |
| 66 | + from the request, if any. Returns a dict made of {"token": <token>} |
| 67 | + :param request: the HTTPRequest object to extract credentials from |
| 68 | + :return: a dict with credentials |
| 69 | + """ |
| 70 | + token = get_jwt_token(request) |
| 71 | + if not token: |
| 72 | + return {} |
| 73 | + return {"token": token} |
| 74 | + |
| 75 | + @security.private |
| 76 | + def authenticateCredentials(self, credentials): # noqa camelCase |
| 77 | + """IAuthenticationPlugin implementation, maps credentials to a User ID. |
| 78 | + If credentials cannot be authenticated, return None |
| 79 | + :param credentials: dict with credentials |
| 80 | + :return: a tuple with the user id and login name or None |
| 81 | + """ |
| 82 | + # Ignore credentials that are not from our extractor |
| 83 | + extractor = credentials.get("extractor") |
| 84 | + if extractor != self.getId(): |
| 85 | + return None |
| 86 | + |
| 87 | + token = credentials.get("token") |
| 88 | + if not token: |
| 89 | + return None |
| 90 | + |
| 91 | + # Peek the payload (no signature check) to learn the userid the |
| 92 | + # token claims to belong to |
| 93 | + userid = peek_userid(token) |
| 94 | + if not userid: |
| 95 | + return None |
| 96 | + |
| 97 | + # Verify signature and expiration with that user's secret |
| 98 | + payload = decode_token(token, userid) |
| 99 | + if not payload: |
| 100 | + return None |
| 101 | + |
| 102 | + # Defensive: ensure the verified payload still names the same user |
| 103 | + if api.to_utf8(payload.get("userid"), default=None) != userid: |
| 104 | + return None |
| 105 | + |
| 106 | + # Make sure the user still exists |
| 107 | + user = api.get_user(userid) |
| 108 | + if not user: |
| 109 | + return None |
| 110 | + |
| 111 | + return userid, userid |
| 112 | + |
| 113 | + |
| 114 | +def get_jwt_token(request): |
| 115 | + """Extracts the JWT token from the request, in this order of preference: |
| 116 | + Authorization: Bearer header, "token" cookie, X-JWT-Auth-Token header. |
| 117 | + """ |
| 118 | + # Read from Authorization header |
| 119 | + auth = request._auth # noqa |
| 120 | + if auth and auth[:7].lower() == "bearer ": |
| 121 | + return auth.split()[-1] |
| 122 | + |
| 123 | + # Read from cookie |
| 124 | + token = request.cookies.get(JWT_COOKIE_ID) |
| 125 | + if token: |
| 126 | + return token |
| 127 | + |
| 128 | + # Read from header |
| 129 | + return request.getHeader(JWT_HEADER_ID) |
| 130 | + |
| 131 | + |
| 132 | +def get_keystorage(): |
| 133 | + """Returns the OOBTree where per-user JWT signing secrets are stored, |
| 134 | + creating it lazily on the portal's annotations on first access. |
| 135 | + """ |
| 136 | + annotation = IAnnotations(api.get_portal()) |
| 137 | + storage = annotation.get(KEY_STORAGE) |
| 138 | + if storage is None: |
| 139 | + annotation[KEY_STORAGE] = OOBTree() |
| 140 | + return annotation[KEY_STORAGE] |
| 141 | + |
| 142 | + |
| 143 | +def signing_secret(userid): |
| 144 | + """Returns the signing secret for the given userid, generating one |
| 145 | + on first call. |
| 146 | + """ |
| 147 | + userid = api.to_utf8(userid, default=None) |
| 148 | + if not userid: |
| 149 | + raise ValueError("Invalid userid: %r" % userid) |
| 150 | + |
| 151 | + storage = get_keystorage() |
| 152 | + data = storage.get(userid) |
| 153 | + if not data: |
| 154 | + storage[userid] = { |
| 155 | + "key": GenerateSecret(), |
| 156 | + "created": timestamp(), |
| 157 | + } |
| 158 | + return storage[userid]["key"] |
| 159 | + |
| 160 | + |
| 161 | +def rotate_secret(userid): |
| 162 | + """Discards the signing secret for the given userid, so a new one is |
| 163 | + generated on the next call to ``signing_secret``. All previously |
| 164 | + issued tokens for the user are invalidated. |
| 165 | + """ |
| 166 | + userid = api.to_utf8(userid, default=None) |
| 167 | + if not userid: |
| 168 | + return |
| 169 | + storage = get_keystorage() |
| 170 | + if userid in storage: |
| 171 | + del storage[userid] |
| 172 | + |
| 173 | + |
| 174 | +def timestamp(seconds=0, minutes=0, hours=0, days=0): |
| 175 | + """Returns a Unix timestamp from GMT plus the given offset. |
| 176 | + """ |
| 177 | + delta = timedelta(seconds=seconds, minutes=minutes, hours=hours, days=days) |
| 178 | + utc = dtime.datetime.utcnow() + delta |
| 179 | + return timegm(utc.utctimetuple()) |
| 180 | + |
| 181 | + |
| 182 | +def peek_userid(token): |
| 183 | + """Returns the ``userid`` claim of the given token without verifying |
| 184 | + the signature, or None if the token cannot be decoded. |
| 185 | + """ |
| 186 | + token = api.to_utf8(token, default=None) |
| 187 | + if not token: |
| 188 | + return None |
| 189 | + try: |
| 190 | + payload = jwt.decode(token, verify=False) |
| 191 | + except (ValueError, TypeError, jwt.InvalidTokenError): |
| 192 | + return None |
| 193 | + return api.to_utf8(payload.get("userid"), default=None) |
| 194 | + |
| 195 | + |
| 196 | +def decode_token(token, userid): |
| 197 | + """Decodes the given JWT, verifies the signature with ``userid``'s |
| 198 | + secret and checks the expiration. Returns the payload or None. |
| 199 | + """ |
| 200 | + token = api.to_utf8(token, default=None) |
| 201 | + if not token: |
| 202 | + return None |
| 203 | + try: |
| 204 | + secret = signing_secret(userid) |
| 205 | + return jwt.decode(token, secret, algorithms=["HS256"]) |
| 206 | + except (ValueError, TypeError, jwt.InvalidTokenError): |
| 207 | + return None |
| 208 | + |
| 209 | + |
| 210 | +def create_token(userid, timeout=JWT_TOKENS_TIMEOUT, **kwargs): |
| 211 | + """Creates a JSON Web Token (JWT) for the given userid. |
| 212 | + """ |
| 213 | + payload = { |
| 214 | + "userid": userid, |
| 215 | + "exp": timestamp(seconds=timeout), |
| 216 | + } |
| 217 | + payload.update(kwargs) |
| 218 | + |
| 219 | + secret = signing_secret(userid) |
| 220 | + token = jwt.encode(payload, secret, algorithm="HS256") |
| 221 | + return api.safe_unicode(token) |
0 commit comments