Skip to content

Commit 7fda2c3

Browse files
author
wallisyan
committed
modify comnment
add bear token; modify credentails.py; add user providerchain; modify signfactory close UT test; del chinese modify lint fix credentials exceptions fix compat add credentials UT
1 parent 49d87a6 commit 7fda2c3

28 files changed

+628
-116
lines changed
File renamed without changes.

aliyun-python-sdk-core/__init__.py

Whitespace-only changes.

aliyun-python-sdk-core/aliyunsdkcore/acs_exception/error_msg.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@
4242
SDK_INVALID_REQUEST='The request is not a valid AcsRequest.',
4343
SDK_MISSING_ENDPOINTS_FILER='Internal endpoints info is missing.',
4444
SDK_UNKNOWN_SERVER_ERROR="Can not parse error message from server response.",
45-
SDK_INVALID_CREDENTIAL="Need a ak&secret pair or public_key_id&private_key pair to auth.",
45+
SDK_INVALID_CREDENTIAL="Need a ak&secret pair or public_key_id&private_key pair or "
46+
"Credentials objects to auth.",
4647
SDK_INVALID_SESSION_EXPIRATION="Session expiration must between {0} and {1} seconds")
4748

4849

aliyun-python-sdk-core/aliyunsdkcore/acs_exception/exceptions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def __init__(self, code, msg):
3333
"""
3434
3535
:param code: error code
36-
:param message: error message
36+
:param msg: error msg
3737
:return:
3838
"""
3939
Exception.__init__(self)

aliyun-python-sdk-core/aliyunsdkcore/auth/signers/access_key_signer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626

2727

2828
class AccessKeySigner(Signer):
29-
def __init__(self, access_key_credential):
29+
def __init__(self, access_key_credential, region_id=None, do_action_api=None, debug=None):
3030
self._credential = access_key_credential
3131

3232
def sign(self, region_id, request):
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# coding:utf-8
2+
3+
# Licensed to the Apache Software Foundation (ASF) under one
4+
# or more contributor license agreements. See the NOTICE file
5+
# distributed with this work for additional information
6+
# regarding copyright ownership. The ASF licenses this file
7+
# to you under the Apache License, Version 2.0 (the
8+
# "License"); you may not use this file except in compliance
9+
# with the License. You may obtain a copy of the License at
10+
#
11+
# http://www.apache.org/licenses/LICENSE-2.0
12+
#
13+
#
14+
#
15+
# Unless required by applicable law or agreed to in writing,
16+
# software distributed under the License is distributed on an
17+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
18+
# KIND, either express or implied. See the License for the
19+
# specific language governing permissions and limitations
20+
# under the License.
21+
22+
import time
23+
import logging
24+
import json
25+
26+
from aliyunsdkcore.vendored.six.moves.urllib.request import urlopen
27+
from aliyunsdkcore.auth.signers.signer import Signer
28+
from aliyunsdkcore.acs_exception.exceptions import ServerException
29+
30+
logger = logging.getLogger(__name__)
31+
32+
33+
class BearTokenSigner(Signer):
34+
# bear token
35+
# https://help.aliyun.com/document_detail/69962.html?spm=a2c4g.11186623.2.15.5dad35f6MtkJkX
36+
# TODO not sure
37+
def __init__(self, bear_token_credential, region_id=None, do_action_api=None, debug=None):
38+
self._credential = bear_token_credential
39+
40+
def sign(self, region_id, request):
41+
self._check_session_credential()
42+
token = self._session_credential
43+
# which token
44+
if request.get_style() == 'RPC':
45+
request.add_query_param("BearerToken", token)
46+
else:
47+
request.add_header("x-acs-bearer-token", token)
48+
header = request.get_signed_header(region_id, None, None)
49+
url = request.get_url(region_id, None, None)
50+
return header, url
51+
52+
def _check_session_credential(self):
53+
now = int(time.time())
54+
if now - self._last_update_time > (self._expiration * self._REFRESH_SCALE):
55+
self._refresh_session_ak_and_sk()
56+
57+
def _refresh_session_ak_and_sk(self):
58+
import requests
59+
payload = {
60+
'refresh_token': self._credential.bear_token,
61+
'client_id': 'client_id', # 应用的Identifier
62+
'grant_type': 'refresh_token'
63+
}
64+
content = requests.post("https://oauth.aliyun.com/v1/token", data=payload)
65+
response = json.loads(content.text.decode('utf-8'))
66+
if response.get("status_code") != "200":
67+
message = 'refresh bear token err, code is ' + \
68+
response.get("Code")
69+
raise ServerException(
70+
response.get("Code"), message, None)
71+
72+
self._session_credential = response.get("access_token")
73+
self._expiration = response.get("expires_in")
74+
self._last_update_time = int(time.time())

aliyun-python-sdk-core/aliyunsdkcore/auth/signers/ecs_ram_role_signer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
class EcsRamRoleSigner(Signer):
3434
_REFRESH_SCALE = 0.8
3535

36-
def __init__(self, ecs_ram_role_credential):
36+
def __init__(self, ecs_ram_role_credential, region_id=None, do_action_api=None, debug=None):
3737
self._credential = ecs_ram_role_credential
3838
self._last_update_time = 0
3939
self._expiration = 0

aliyun-python-sdk-core/aliyunsdkcore/auth/signers/ram_role_arn_signer.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@
2727
from aliyunsdkcore.auth.signers.access_key_signer import AccessKeySigner
2828
from aliyunsdkcore.acs_exception import error_code
2929
from aliyunsdkcore.acs_exception import exceptions
30-
from aliyunsdkcore.auth.credentials import RamRoleArnCredential
31-
from aliyunsdkcore.auth.credentials import AccessKeyCredential
30+
from aliyunsdkcore.credentials.credentials import RamRoleArnCredential
31+
from aliyunsdkcore.credentials.credentials import AccessKeyCredential
3232
from aliyunsdkcore.request import CommonRequest
3333
from aliyunsdkcore.compat import ensure_string
3434

@@ -41,7 +41,7 @@ class RamRoleArnSigner(Signer):
4141
_RETRY_DELAY_FAST = 3
4242
_PRIORITY = 1
4343

44-
def __init__(self, credential, do_action_api):
44+
def __init__(self, credential, region_id=None, do_action_api=None, debug=None):
4545
if isinstance(credential, RamRoleArnCredential):
4646
self._credential = credential
4747
self._doAction = do_action_api

aliyun-python-sdk-core/aliyunsdkcore/auth/signers/rsa_key_pair_signer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class RsaKeyPairSigner(Signer):
1818
_MIN_SESSION_PERIOD = 900
1919
_MAX_SESSION_PERIOD = 3600
2020

21-
def __init__(self, credential, region_id, debug=False):
21+
def __init__(self, credential, region_id=None, do_action_api=None, debug=None):
2222
if credential.session_period < self._MIN_SESSION_PERIOD or \
2323
credential.session_period > self._MAX_SESSION_PERIOD:
2424
raise exceptions.ClientException(
Lines changed: 18 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,32 @@
11
# coding:utf-8
22

3-
import logging
4-
import os
53
from aliyunsdkcore.acs_exception import error_msg
64
from aliyunsdkcore.acs_exception import error_code
75
from aliyunsdkcore.acs_exception import exceptions
8-
from aliyunsdkcore.auth import credentials
6+
from aliyunsdkcore.credentials.credentials import AccessKeyCredential, StsTokenCredential, \
7+
RamRoleArnCredential, EcsRamRoleCredential, RsaKeyPairCredential, BearTokenCredential
98
from aliyunsdkcore.auth.signers import access_key_signer
109
from aliyunsdkcore.auth.signers import sts_token_signer
1110
from aliyunsdkcore.auth.signers import ram_role_arn_signer
1211
from aliyunsdkcore.auth.signers import ecs_ram_role_signer
1312
from aliyunsdkcore.auth.signers import rsa_key_pair_signer
13+
from aliyunsdkcore.auth.signers import bear_token_signer
1414

1515

1616
class SignerFactory(object):
1717
@staticmethod
18-
def get_signer(cred, region_id, do_action_api, debug=False):
19-
if cred.get('ak') is not None and cred.get('secret') is not None:
20-
access_key_credential = credentials.AccessKeyCredential(
21-
cred.get('ak'), cred.get('secret'))
22-
return access_key_signer.AccessKeySigner(access_key_credential)
23-
elif os.environ.get('ALIYUN_ACCESS_KEY_ID') is not None \
24-
and os.environ.get('ALIYUN_ACCESS_KEY_SECRET') is not None:
25-
access_key_credential = credentials.AccessKeyCredential(
26-
os.environ.get('ALIYUN_ACCESS_KEY_ID'),
27-
os.environ.get('ALIYUN_ACCESS_KEY_SECRET'))
28-
return access_key_signer.AccessKeySigner(access_key_credential)
29-
elif cred.get('credential') is not None:
30-
credential = cred.get('credential')
31-
if isinstance(credential, credentials.AccessKeyCredential):
32-
return access_key_signer.AccessKeySigner(credential)
33-
elif isinstance(credential, credentials.StsTokenCredential):
34-
return sts_token_signer.StsTokenSigner(credential)
35-
elif isinstance(credential, credentials.RamRoleArnCredential):
36-
return ram_role_arn_signer.RamRoleArnSigner(credential, do_action_api)
37-
elif isinstance(credential, credentials.EcsRamRoleCredential):
38-
return ecs_ram_role_signer.EcsRamRoleSigner(credential)
39-
elif isinstance(credential, credentials.RsaKeyPairCredential):
40-
return rsa_key_pair_signer.RsaKeyPairSigner(credential, region_id, debug)
41-
elif cred.get('public_key_id') is not None and cred.get('private_key') is not None:
42-
logging.info(
43-
"'AcsClient(regionId, pub_key_id, pri_key)' is deprecated")
44-
rsa_key_pair_credential = credentials.RsaKeyPairCredential(cred['public_key_id'],
45-
cred['private_key'],
46-
cred['session_period'])
47-
return rsa_key_pair_signer.RsaKeyPairSigner(rsa_key_pair_credential, region_id, debug)
48-
else:
49-
raise exceptions.ClientException(error_code.SDK_INVALID_CREDENTIAL,
50-
error_msg.get_msg('SDK_INVALID_CREDENTIAL'))
18+
def get_signer(credentials, region_id, do_action_api, debug=False):
19+
signing_type_map = {
20+
AccessKeyCredential: access_key_signer.AccessKeySigner,
21+
StsTokenCredential: sts_token_signer.StsTokenSigner,
22+
RamRoleArnCredential: ram_role_arn_signer.RamRoleArnSigner,
23+
EcsRamRoleCredential: ecs_ram_role_signer.EcsRamRoleSigner,
24+
RsaKeyPairCredential: rsa_key_pair_signer.RsaKeyPairSigner,
25+
BearTokenCredential: bear_token_signer.BearTokenSigner,
26+
}
27+
for credential, sign_func in signing_type_map.items():
28+
if isinstance(credentials, credential):
29+
return sign_func(credentials, region_id=region_id, do_action_api=do_action_api,
30+
debug=debug)
31+
raise exceptions.ClientException(error_code.SDK_INVALID_CREDENTIAL,
32+
error_msg.get_msg('SDK_INVALID_CREDENTIAL'))

0 commit comments

Comments
 (0)