Skip to content

Commit 0ff708a

Browse files
authored
feat: bkpaas-auth 3.0.0 (TencentBlueKing#191)
1 parent 17a16b8 commit 0ff708a

17 files changed

Lines changed: 551 additions & 642 deletions

File tree

.github/workflows/bkpaas-auth.yml

Lines changed: 71 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ name: CI Check for bkpaas-auth
22

33
on:
44
push:
5-
branches: [ master ]
5+
branches: [master]
66
paths:
7-
- 'sdks/bkpaas-auth/**'
7+
- "sdks/bkpaas-auth/**"
88
pull_request:
9-
branches: [ master ]
9+
branches: [master]
1010
paths:
11-
- 'sdks/bkpaas-auth/**'
11+
- "sdks/bkpaas-auth/**"
1212
workflow_dispatch:
1313
release:
1414
types: [published]
@@ -18,79 +18,83 @@ jobs:
1818
runs-on: macos-latest
1919
continue-on-error: true
2020
steps:
21-
- uses: actions/checkout@v2
22-
- name: Set up Python
23-
uses: actions/setup-python@v2
24-
with:
25-
python-version: 3.7
26-
- name: Format with isort
27-
run: |
28-
pip install isort==5.9.2
29-
isort sdks/ --settings-path=sdks/bkpaas-auth/pyproject.toml
30-
- name: Format with black
31-
run: |
32-
pip install black==21.7b0 click==8.0.4
33-
black sdks/ --config=sdks/bkpaas-auth/pyproject.toml
34-
- name: Lint with flake8
35-
run: |
36-
pip install flake8==4.0.1 pyproject-flake8==0.0.1a4
37-
pflake8 sdks/ --config=sdks/bkpaas-auth/pyproject.toml
38-
- name: Lint with mypy
39-
run: |
40-
pip install mypy==0.910 types-requests==2.25.0 types-setuptools==57.0.0 types-dataclasses==0.1.5 types-six==0.1.7 types-toml==0.1.3
41-
mypy sdks/bkpaas-auth --config-file=sdks/bkpaas-auth/pyproject.toml
21+
- uses: actions/checkout@v2
22+
- name: Set up Python
23+
uses: actions/setup-python@v2
24+
with:
25+
python-version: 3.11
26+
- name: Format with isort
27+
working-directory: sdks/bkpaas-auth
28+
run: |
29+
pip install isort==5.12.0
30+
isort . --settings-path=pyproject.toml
31+
- name: Format with black
32+
working-directory: sdks/bkpaas-auth
33+
run: |
34+
pip install black==23.7.0 click==8.1.6
35+
black . --config=pyproject.toml
36+
- name: Lint with flake8
37+
working-directory: sdks/bkpaas-auth
38+
run: |
39+
pip install flake8==4.0.1 pyproject-flake8==0.0.1a5
40+
pflake8 . --config=pyproject.toml
41+
- name: Lint with mypy
42+
working-directory: sdks/bkpaas-auth
43+
run: |
44+
pip install mypy==1.12.0 types-mock==4.0.15.2 types-requests==2.32.0.20241016 types-six==1.16.21.20241009
45+
mypy . --config-file=pyproject.toml
4246
4347
test:
4448
strategy:
4549
fail-fast: false
4650
matrix:
47-
python-version: ['3.7', '3.8', '3.9', '3.10']
51+
python-version: ["3.8", "3.9", "3.10", "3.11"]
4852
os: [ubuntu-latest, macos-latest]
4953
runs-on: ${{ matrix.os }}
5054
steps:
51-
- uses: actions/checkout@v2
52-
- name: Set up Python
53-
uses: actions/setup-python@v2
54-
with:
55-
python-version: ${{ matrix.python-version }}
56-
- name: Set up Poetry
57-
uses: abatilo/actions-poetry@v2.1.0
58-
with:
59-
poetry-version: 1.1.13
60-
- name: Install dependencies
61-
working-directory: sdks/bkpaas-auth
62-
run: |
63-
poetry export --without-hashes --dev -o requirements-dev.txt
64-
python -m pip install --upgrade pip
65-
python -m pip install -r requirements-dev.txt
66-
python -m pip install tox-gh-actions==2.8.1
67-
- name: Run test with tox targets for ${{ matrix.python-version }}
68-
working-directory: sdks/bkpaas-auth
69-
run: tox
55+
- uses: actions/checkout@v2
56+
- name: Set up Python
57+
uses: actions/setup-python@v2
58+
with:
59+
python-version: ${{ matrix.python-version }}
60+
- name: Set up Poetry
61+
uses: abatilo/actions-poetry@v2.3.0
62+
with:
63+
poetry-version: 1.5.1
64+
- name: Install dependencies
65+
working-directory: sdks/bkpaas-auth
66+
run: |
67+
poetry export --without-hashes --dev -o requirements-dev.txt
68+
python -m pip install --upgrade pip
69+
python -m pip install -r requirements-dev.txt
70+
python -m pip install tox-gh-actions==2.8.1
71+
- name: Run test with tox targets for ${{ matrix.python-version }}
72+
working-directory: sdks/bkpaas-auth
73+
run: tox
7074

7175
build:
7276
runs-on: macos-latest
7377
if: github.event.release && contains(github.event.release.tag_name, 'bkpaas-auth')
7478
steps:
75-
- uses: actions/checkout@v2
76-
- name: Set up Python
77-
uses: actions/setup-python@v2
78-
with:
79-
python-version: 3.8
80-
- name: Set up Poetry
81-
uses: abatilo/actions-poetry@v2.1.0
82-
with:
83-
poetry-version: 1.1.13
84-
- name: Build bkpaas-auth
85-
run: |
86-
cd sdks/bkpaas-auth
87-
poetry install
88-
poetry build
89-
echo "${{ github.event.relesae.tag_name }} ${{ github.sha }}" > Release.txt
90-
cat Release.txt
91-
- name: Release
92-
uses: softprops/action-gh-release@v1
93-
with:
94-
files: |
95-
Release.txt
96-
sdks/bkpaas-auth/dist/*
79+
- uses: actions/checkout@v2
80+
- name: Set up Python
81+
uses: actions/setup-python@v2
82+
with:
83+
python-version: 3.8
84+
- name: Set up Poetry
85+
uses: abatilo/actions-poetry@v2.3.0
86+
with:
87+
poetry-version: 1.5.1
88+
- name: Build bkpaas-auth
89+
run: |
90+
cd sdks/bkpaas-auth
91+
poetry install
92+
poetry build
93+
echo "${{ github.event.relesae.tag_name }} ${{ github.sha }}" > Release.txt
94+
cat Release.txt
95+
- name: Release
96+
uses: softprops/action-gh-release@v1
97+
with:
98+
files: |
99+
Release.txt
100+
sdks/bkpaas-auth/dist/*

.github/workflows/blue-krill.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ jobs:
8080
run: tox
8181
build:
8282
runs-on: macos-latest
83-
if: github.event.release && contains(github.event.release.tag_name, 'blue_krill')
83+
if: github.event.release && contains(github.event.release.tag_name, 'blue-krill')
8484
steps:
8585
- uses: actions/checkout@v2
8686
- name: Set up Python

sdks/bkpaas-auth/CHANGES.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
# 版本历史
22

3+
## 3.0.0
4+
- BreakChange: 不再支持 Python 3.6,3.7
5+
- BreakChange: Django 版本要求 >=4.2,<5.0
6+
37
## 2.1.0
4-
- fix: 修复 APIGatewayAuthBackend 不兼容 ^3.0.0 以上的 apigw_manager
8+
- fix: 修复 APIGatewayAuthBackend 不兼容 ^3.0.0 以上的 apigw_manager
59

610
## 2.0.8
711
- 将认证信息标准化到请求头 X-Bkapi-Authorization 中

sdks/bkpaas-auth/bkpaas_auth/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# -*- coding: utf-8 -*-
2-
__version__ = "2.1.0"
2+
__version__ = "3.0.0"
33

44

55
def get_user_by_user_id(user_id: str, username_only: bool = True):

sdks/bkpaas-auth/bkpaas_auth/backends.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ class UniversalAuthBackend:
3737
"""
3838

3939
request: HttpRequest
40+
plugin: Union[BkTicketPlugin, BkTokenPlugin]
41+
request_backend: Union[RequestBackend, TokenRequestBackend]
4042

4143
def __init__(self):
4244
self.backend_type = bkauth_settings.BACKEND_TYPE
@@ -215,11 +217,11 @@ def authenticate_with_signature_v1(self, request, api_name, bk_username, verifie
215217
if get_user_parameters == v3_parameters:
216218
authenticate = authenticate_with_signature_v3
217219
else:
218-
authenticate = authenticate_with_signature_v1
220+
authenticate = authenticate_with_signature_v1 # type: ignore
219221
del get_user_parameters
220222
del v3_parameters
221223
except ImportError:
222-
authenticate = authenticate_with_signature_v1
224+
authenticate = authenticate_with_signature_v1 # type: ignore
223225

224226
def get_user(self, user_id):
225227
raise NotImplementedError(

sdks/bkpaas-auth/bkpaas_auth/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ class Settings:
4949

5050
def reload(self):
5151
for f in fields(self):
52-
setattr(self, f.name, f.default_factory())
52+
setattr(self, f.name, f.default_factory()) # type: ignore
5353

5454

5555
bkauth_settings = Settings()
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class ARC4:
4+
"""ARC4 算法的实现
5+
6+
注意:ARC4 加密算法很容易被破解,目前项目中仅用于解编码(类似 base64 的作用)
7+
"""
8+
9+
def __init__(self, key):
10+
assert (isinstance(key, (bytes, bytearray)))
11+
12+
s = list(range(0x100))
13+
j = 0
14+
for i in range(0x100):
15+
j = (s[i] + key[i % len(key)] + j) & 0xff
16+
s[i], s[j] = s[j], s[i]
17+
18+
self.s = s
19+
self.key_stream = self._key_stream_generator()
20+
21+
def encrypt(self, data):
22+
"""加密数据"""
23+
return self._crypt(data)
24+
25+
def decrypt(self, data):
26+
"""解密数据"""
27+
return self._crypt(data)
28+
29+
def _crypt(self, data):
30+
assert (isinstance(data, (bytes, bytearray)))
31+
return bytes([a ^ b for a, b in zip(data, self.key_stream)])
32+
33+
def _key_stream_generator(self):
34+
s = self.s.copy()
35+
x = y = 0
36+
while True:
37+
x = (x + 1) & 0xff
38+
y = (s[x] + y) & 0xff
39+
s[x], s[y] = s[y], s[x]
40+
i = (s[x] + s[y]) & 0xff
41+
yield s[i]

sdks/bkpaas-auth/bkpaas_auth/core/encoder.py

Lines changed: 3 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,10 @@
22
import binascii
33
from typing import Tuple, Union
44

5-
from cryptography.hazmat.backends.openssl.backend import GetCipherByName, backend
6-
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms
75
from six import ensure_binary, ensure_text
86

97
from bkpaas_auth.core.constants import ProviderType
10-
11-
12-
class _ARC4(algorithms.ARC4):
13-
"""ARC4 should support key sizes bellow 40-2048 bits,
14-
but algorithms.ARC4 only support the kes size to be in [40, 56, 64, 80, 128, 160, 192, 256] bytes.
15-
16-
In order to support the key='jdvoqu3o4', we must overwrite the field `key_sizes` to remove the restriction.
17-
This is the reason why we must implement another ARC4 algorithm.
18-
"""
19-
20-
key_sizes = frozenset(range(40, 2049, 4))
21-
22-
23-
backend.register_cipher_adapter(_ARC4, type(None), GetCipherByName("rc4"))
8+
from bkpaas_auth.core.algorithms import ARC4
249

2510

2611
class BluekingUserIdEncoder:
@@ -38,10 +23,7 @@ def encode(self, provider_type: Union[int, ProviderType], username: Union[str, b
3823
"""
3924
id_prefix = ProviderType(provider_type).get_id_prefix()
4025

41-
algorithm = _ARC4(ensure_binary(self.secret_key))
42-
cipher = Cipher(algorithm, mode=None)
43-
encryptor = cipher.encryptor()
44-
encoded = encryptor.update(ensure_binary(username))
26+
encoded = ARC4(ensure_binary(self.secret_key)).encrypt(ensure_binary(username))
4527
return id_prefix + ensure_text(binascii.hexlify(encoded))
4628

4729
def decode(self, user_id: Union[str, bytes]) -> Tuple[int, str]:
@@ -53,10 +35,7 @@ def decode(self, user_id: Union[str, bytes]) -> Tuple[int, str]:
5335
_provider_type, username = user_id[:2], user_id[2:]
5436
provider_type = int(_provider_type)
5537

56-
algorithm = _ARC4(ensure_binary(self.secret_key))
57-
cipher = Cipher(algorithm, mode=None)
58-
decryptor = cipher.decryptor()
59-
decoded = decryptor.update(binascii.unhexlify(username))
38+
decoded = ARC4(ensure_binary(self.secret_key)).decrypt(binascii.unhexlify(username))
6039
return provider_type, ensure_text(decoded)
6140

6241

sdks/bkpaas-auth/bkpaas_auth/core/services.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ def _get_and_cache_user_info(cache_key, user_params, response_ok_checker):
4949
)
5050
if not is_success:
5151
raise ServiceError('Unable to get user info')
52+
if not isinstance(result, dict):
53+
raise ValueError(f'response type expect dict, got: {result}')
5254

5355
if not response_ok_checker(result):
5456
logger.error(

sdks/bkpaas-auth/bkpaas_auth/core/token.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ def request_username(self, **credentials):
4242
)
4343
if not is_success:
4444
raise ServiceError('unable to fetch token services')
45+
if not isinstance(resp, dict):
46+
raise ValueError(f'response type expect dict, got: {resp}')
4547

4648
# API 返回格式为:{"result": true, "code": 0, "message": "", "data": {"bk_username": "xxx"}}
4749
code = resp.get('code')
@@ -69,6 +71,8 @@ def request_username(self, **credentials):
6971
is_success, resp = http_get(bkauth_settings.USER_COOKIE_VERIFY_URL, params=credentials, timeout=10)
7072
if not is_success:
7173
raise ServiceError('unable to fetch token services')
74+
if not isinstance(resp, dict):
75+
raise ValueError(f'response type expect dict, got: {resp}')
7276

7377
# API 返回格式为:{"msg": "", "data": {"username": "xxx"}, "ret": 0}
7478
if resp.get('ret') != 0:

0 commit comments

Comments
 (0)