or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-foundation.mdconfiguration-profiles.mdcredential-management.mdhttp-infrastructure.mdindex.mdresilience-reliability.mdsecurity-authentication.md

security-authentication.mddocs/

0

# Security and Authentication

1

2

Digital signature utilities supporting multiple signature methods and comprehensive exception handling for authentication and API errors. Provides secure request signing and robust error management for all Tencent Cloud API interactions.

3

4

## Capabilities

5

6

### Digital Signature Utilities

7

8

Cryptographic signing utilities supporting multiple signature algorithms for secure API authentication.

9

10

```python { .api }

11

class Sign:

12

@staticmethod

13

def sign(secret_key: str, sign_str: str, sign_method: str) -> str:

14

"""

15

Generate signature using specified method.

16

17

Args:

18

secret_key (str): Secret key for signing

19

sign_str (str): String to be signed

20

sign_method (str): Signature method ("HmacSHA1" or "HmacSHA256")

21

22

Returns:

23

str: Base64-encoded signature

24

25

Raises:

26

TencentCloudSDKException: If signature method is not supported

27

"""

28

29

@staticmethod

30

def sign_tc3(secret_key: str, date: str, service: str, str2sign: str) -> str:

31

"""

32

Generate TC3-HMAC-SHA256 signature.

33

34

Args:

35

secret_key (str): Secret key for signing

36

date (str): Date in YYYY-MM-DD format

37

service (str): Service name (e.g., "cvm", "cos")

38

str2sign (str): String to be signed

39

40

Returns:

41

str: Hexadecimal signature

42

"""

43

```

44

45

### Exception Handling

46

47

Comprehensive exception class for handling all types of SDK and API errors.

48

49

```python { .api }

50

class TencentCloudSDKException(Exception):

51

def __init__(self, code: str = None, message: str = None,

52

requestId: str = None):

53

"""

54

Create SDK exception.

55

56

Args:

57

code (str, optional): Error code

58

message (str, optional): Error message

59

requestId (str, optional): Request ID for tracing

60

"""

61

62

def get_code(self) -> str:

63

"""

64

Get error code.

65

66

Returns:

67

str: Error code

68

"""

69

70

def get_message(self) -> str:

71

"""

72

Get error message.

73

74

Returns:

75

str: Error message

76

"""

77

78

def get_request_id(self) -> str:

79

"""

80

Get request ID.

81

82

Returns:

83

str: Request ID for tracing

84

"""

85

```

86

87

## Common Error Codes

88

89

The following error codes are commonly encountered when using the SDK:

90

91

### Client-Side Errors

92

93

- **ClientError**: General client configuration or parameter errors

94

- **ClientNetworkError**: Network connectivity issues from client side

95

- **ClientParamsError**: Invalid parameters provided to API calls

96

- **InvalidCredential**: Authentication credential issues

97

98

### Server-Side Errors

99

100

- **ServerNetworkError**: Server-side network or connectivity problems

101

- **InternalError**: Internal server errors

102

- **RequestLimitExceeded**: API rate limiting errors

103

- **RequestLimitExceeded.UinLimitExceeded**: Account-level rate limiting

104

- **RequestLimitExceeded.GlobalRegionUinLimitExceeded**: Global region rate limiting

105

106

### Authentication Errors

107

108

- **AuthFailure**: General authentication failures

109

- **AuthFailure.InvalidSecretId**: Invalid secret ID

110

- **AuthFailure.MFAFailure**: Multi-factor authentication failures

111

- **AuthFailure.SecretIdNotFound**: Secret ID not found

112

- **AuthFailure.SignatureExpire**: Request signature expired

113

- **AuthFailure.SignatureFailure**: Invalid signature

114

- **AuthFailure.TokenFailure**: Invalid temporary token

115

- **AuthFailure.UnauthorizedOperation**: Insufficient permissions

116

117

## Usage Examples

118

119

### Basic Signature Generation

120

121

```python

122

from tencentcloud.common.sign import Sign

123

124

# Generate HmacSHA256 signature

125

secret_key = "your-secret-key"

126

string_to_sign = "POST\ncvm.tencentcloudapi.com\n/\nAction=DescribeInstances&Nonce=12345"

127

signature = Sign.sign(secret_key, string_to_sign, "HmacSHA256")

128

print("Signature:", signature)

129

130

# Generate TC3-HMAC-SHA256 signature

131

date = "2023-01-15"

132

service = "cvm"

133

string_to_sign = "TC3-HMAC-SHA256\n1673740800\n2023-01-15/cvm/tc3_request\n..."

134

signature = Sign.sign_tc3(secret_key, date, service, string_to_sign)

135

print("TC3 Signature:", signature)

136

```

137

138

### Exception Handling

139

140

```python

141

from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException

142

from tencentcloud.common.common_client import CommonClient

143

144

client = CommonClient("cvm", "2017-03-12", cred, "ap-guangzhou")

145

146

try:

147

response = client.call_json("DescribeInstances", {})

148

print("Success:", response)

149

150

except TencentCloudSDKException as e:

151

error_code = e.get_code()

152

error_message = e.get_message()

153

request_id = e.get_request_id()

154

155

print(f"API Error Code: {error_code}")

156

print(f"Error Message: {error_message}")

157

print(f"Request ID: {request_id}")

158

159

# Handle specific error types

160

if error_code == "AuthFailure.SignatureFailure":

161

print("Check your secret key and signature method")

162

elif error_code == "RequestLimitExceeded":

163

print("Rate limited, implementing backoff...")

164

elif error_code.startswith("ClientNetworkError"):

165

print("Network issue, check connectivity")

166

elif error_code.startswith("InvalidCredential"):

167

print("Credential issue, check secret ID and key")

168

169

except Exception as e:

170

print(f"Unexpected error: {e}")

171

```

172

173

### Custom Exception Handling

174

175

```python

176

from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException

177

178

def handle_api_call(api_func, *args, **kwargs):

179

"""Wrapper function with comprehensive error handling"""

180

try:

181

return api_func(*args, **kwargs)

182

183

except TencentCloudSDKException as e:

184

error_code = e.get_code()

185

186

# Categorize errors

187

if error_code.startswith("AuthFailure"):

188

raise AuthenticationError(f"Authentication failed: {e.get_message()}")

189

elif error_code.startswith("RequestLimitExceeded"):

190

raise RateLimitError(f"Rate limited: {e.get_message()}")

191

elif error_code.startswith("ClientNetworkError"):

192

raise NetworkError(f"Network error: {e.get_message()}")

193

else:

194

raise APIError(f"API error {error_code}: {e.get_message()}")

195

196

# Custom exception classes

197

class AuthenticationError(Exception):

198

pass

199

200

class RateLimitError(Exception):

201

pass

202

203

class NetworkError(Exception):

204

pass

205

206

class APIError(Exception):

207

pass

208

209

# Usage

210

try:

211

response = handle_api_call(client.call_json, "DescribeInstances", {})

212

except AuthenticationError:

213

print("Fix authentication credentials")

214

except RateLimitError:

215

print("Implement retry with backoff")

216

except NetworkError:

217

print("Check network connectivity")

218

except APIError as e:

219

print(f"API error: {e}")

220

```

221

222

### Signature Method Validation

223

224

```python

225

from tencentcloud.common.sign import Sign

226

from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException

227

228

def validate_signature_method(method):

229

"""Validate signature method before use"""

230

valid_methods = ["HmacSHA1", "HmacSHA256"]

231

232

if method not in valid_methods:

233

raise TencentCloudSDKException(

234

"InvalidSignatureMethod",

235

f"Invalid signature method: {method}. Valid methods: {valid_methods}"

236

)

237

238

return method

239

240

# Usage

241

try:

242

method = validate_signature_method("HmacSHA256")

243

signature = Sign.sign("secret", "data", method)

244

except TencentCloudSDKException as e:

245

print(f"Validation error: {e.get_message()}")

246

```

247

248

### Request ID Tracking

249

250

```python

251

from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException

252

import logging

253

254

# Setup logging with request ID tracking

255

logging.basicConfig(

256

format='%(asctime)s - %(levelname)s - %(message)s',

257

level=logging.INFO

258

)

259

logger = logging.getLogger(__name__)

260

261

def make_tracked_api_call(client, action, params):

262

"""Make API call with request ID tracking"""

263

try:

264

response = client.call_json(action, params)

265

request_id = response.get("Response", {}).get("RequestId")

266

logger.info(f"API call succeeded - Action: {action}, RequestId: {request_id}")

267

return response

268

269

except TencentCloudSDKException as e:

270

request_id = e.get_request_id()

271

logger.error(f"API call failed - Action: {action}, RequestId: {request_id}, Error: {e.get_code()}")

272

raise

273

274

# Usage

275

try:

276

response = make_tracked_api_call(client, "DescribeInstances", {"Limit": 10})

277

except TencentCloudSDKException as e:

278

print(f"Request {e.get_request_id()} failed: {e.get_message()}")

279

```

280

281

### Credential Validation

282

283

```python

284

from tencentcloud.common.credential import Credential

285

from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException

286

287

def create_validated_credential(secret_id, secret_key, token=None):

288

"""Create credential with validation"""

289

try:

290

return Credential(secret_id, secret_key, token)

291

except TencentCloudSDKException as e:

292

if e.get_code() == "InvalidCredential":

293

print(f"Credential validation failed: {e.get_message()}")

294

print("Please check:")

295

print("- Secret ID and key are not empty")

296

print("- No leading/trailing spaces")

297

print("- Correct format")

298

raise

299

300

# Usage

301

try:

302

cred = create_validated_credential("AKID...", "your-secret-key")

303

print("Credentials created successfully")

304

except TencentCloudSDKException as e:

305

print(f"Failed to create credentials: {e.get_message()}")

306

```

307

308

### Security Best Practices

309

310

```python

311

import os

312

from tencentcloud.common.credential import DefaultCredentialProvider

313

314

def get_secure_credentials():

315

"""Get credentials using secure methods"""

316

317

# Use credential chain for flexibility

318

provider = DefaultCredentialProvider()

319

320

try:

321

cred = provider.get_credentials()

322

print("Using credential chain (recommended)")

323

return cred

324

except Exception:

325

print("No credentials found in chain")

326

327

# Fallback to environment variables (better than hardcoding)

328

secret_id = os.getenv("TENCENTCLOUD_SECRET_ID")

329

secret_key = os.getenv("TENCENTCLOUD_SECRET_KEY")

330

331

if secret_id and secret_key:

332

print("Using environment variables")

333

return Credential(secret_id, secret_key)

334

335

raise TencentCloudSDKException(

336

"NoCredentialsFound",

337

"No valid credentials found. Use environment variables or credential files."

338

)

339

340

# Security recommendations:

341

# 1. Never hardcode credentials in source code

342

# 2. Use environment variables or credential files

343

# 3. Use IAM roles when possible (CVM, TKE)

344

# 4. Rotate credentials regularly

345

# 5. Use minimum required permissions

346

# 6. Monitor API usage and errors

347

```