Skip to content

Commit c5a99cf

Browse files
author
wangyue.demon
committed
auth(veauth): support query tts app_key from openapi
1 parent db0f804 commit c5a99cf

File tree

3 files changed

+127
-29
lines changed

3 files changed

+127
-29
lines changed
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import pytest
16+
from unittest.mock import patch, MagicMock
17+
from veadk.auth.veauth.speech_veauth import get_speech_token
18+
19+
20+
# Test cases
21+
22+
23+
def test_get_speech_token_with_env_vars(monkeypatch):
24+
"""Test when credentials are available in environment variables"""
25+
# Setup
26+
monkeypatch.setenv("VOLCENGINE_ACCESS_KEY", "test_access_key")
27+
monkeypatch.setenv("VOLCENGINE_SECRET_KEY", "test_secret_key")
28+
29+
mock_response = {"Result": {"APIKeys": [{"APIKey": "test_api_key"}]}}
30+
31+
with patch("veadk.auth.veauth.speech_veauth.ve_request") as mock_ve_request:
32+
mock_ve_request.return_value = mock_response
33+
34+
# Execute
35+
result = get_speech_token()
36+
37+
# Verify
38+
assert result == "test_api_key"
39+
mock_ve_request.assert_called_once_with(
40+
request_body={
41+
"ProjectName": "default",
42+
"OnlyAvailable": True,
43+
"Filter": {},
44+
},
45+
header={"X-Security-Token": ""},
46+
action="ListApiKeys",
47+
ak="test_access_key",
48+
sk="test_secret_key",
49+
service="speech_saas_prod",
50+
version="2025-05-20",
51+
region="cn-beijing",
52+
host="open.volcengineapi.com",
53+
)
54+
55+
56+
def test_get_speech_token_with_vefaas_iam(monkeypatch):
57+
"""Test when credentials are obtained from vefaas iam"""
58+
# Setup
59+
monkeypatch.delenv("VOLCENGINE_ACCESS_KEY", raising=False)
60+
monkeypatch.delenv("VOLCENGINE_SECRET_KEY", raising=False)
61+
62+
mock_cred = MagicMock()
63+
mock_cred.access_key_id = "vefaas_access_key"
64+
mock_cred.secret_access_key = "vefaas_secret_key"
65+
mock_cred.session_token = "vefaas_session_token"
66+
67+
mock_response = {"Result": {"APIKeys": [{"APIKey": "vefaas_api_key"}]}}
68+
69+
with (
70+
patch(
71+
"veadk.auth.veauth.speech_veauth.get_credential_from_vefaas_iam"
72+
) as mock_get_cred,
73+
patch("veadk.auth.veauth.speech_veauth.ve_request") as mock_ve_request,
74+
):
75+
mock_get_cred.return_value = mock_cred
76+
mock_ve_request.return_value = mock_response
77+
78+
# Execute
79+
result = get_speech_token(region="cn-shanghai")
80+
81+
# Verify
82+
assert result == "vefaas_api_key"
83+
mock_get_cred.assert_called_once()
84+
mock_ve_request.assert_called_once_with(
85+
request_body={
86+
"ProjectName": "default",
87+
"OnlyAvailable": True,
88+
"Filter": {},
89+
},
90+
header={"X-Security-Token": "vefaas_session_token"},
91+
action="ListApiKeys",
92+
ak="vefaas_access_key",
93+
sk="vefaas_secret_key",
94+
service="speech_saas_prod",
95+
version="2025-05-20",
96+
region="cn-shanghai",
97+
host="open.volcengineapi.com",
98+
)
99+
100+
101+
def test_get_speech_token_invalid_response():
102+
"""Test when API response is invalid"""
103+
# Setup
104+
monkeypatch = pytest.MonkeyPatch()
105+
monkeypatch.setenv("VOLCENGINE_ACCESS_KEY", "test_access_key")
106+
monkeypatch.setenv("VOLCENGINE_SECRET_KEY", "test_secret_key")
107+
108+
mock_response = {"Error": {"Message": "Invalid request"}}
109+
110+
with patch("veadk.auth.veauth.speech_veauth.ve_request") as mock_ve_request:
111+
mock_ve_request.return_value = mock_response
112+
113+
# Execute & Verify
114+
with pytest.raises(ValueError, match="Failed to get speech api key list"):
115+
get_speech_token()

veadk/auth/veauth/speech_veauth.py

Lines changed: 9 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
logger = get_logger(__name__)
2222

2323

24-
def get_tts_token(region: str = "cn-beijing") -> str:
25-
logger.info("Fetching TTS token...")
24+
def get_speech_token(region: str = "cn-beijing") -> str:
25+
logger.info("Fetching speech token...")
2626

2727
access_key = os.getenv("VOLCENGINE_ACCESS_KEY")
2828
secret_key = os.getenv("VOLCENGINE_SECRET_KEY")
@@ -36,36 +36,19 @@ def get_tts_token(region: str = "cn-beijing") -> str:
3636
session_token = cred.session_token
3737

3838
res = ve_request(
39-
request_body={"ProjectName": "default", "Filter": {}},
39+
request_body={"ProjectName": "default", "OnlyAvailable": True, "Filter": {}},
4040
header={"X-Security-Token": session_token},
4141
action="ListApiKeys",
4242
ak=access_key,
4343
sk=secret_key,
44-
service="ark",
45-
version="2024-01-01",
44+
service="speech_saas_prod",
45+
version="2025-05-20",
4646
region=region,
4747
host="open.volcengineapi.com",
4848
)
4949
try:
50-
first_api_key_id = res["Result"]["Items"][0]["Id"]
50+
first_api_key_id = res["Result"]["APIKeys"][0]["APIKey"]
51+
logger.info("Successfully fetching speech API Key.")
52+
return first_api_key_id
5153
except KeyError:
52-
raise ValueError(f"Failed to get ARK api key list: {res}")
53-
54-
# get raw api key
55-
res = ve_request(
56-
request_body={"Id": first_api_key_id},
57-
header={"X-Security-Token": session_token},
58-
action="GetRawApiKey",
59-
ak=access_key,
60-
sk=secret_key,
61-
service="ark",
62-
version="2024-01-01",
63-
region=region,
64-
host="open.volcengineapi.com",
65-
)
66-
try:
67-
api_key = res["Result"]["ApiKey"]
68-
logger.info("Successfully fetching ARK API Key.")
69-
return api_key
70-
except KeyError:
71-
raise ValueError(f"Failed to get ARK api key: {res}")
54+
raise ValueError(f"Failed to get speech api key list: {res}")

veadk/tools/builtin_tools/tts.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def text_to_speech(text: str, tool_context: ToolContext) -> Dict[str, Any]:
6363
app_id = getenv("TOOL_TTS_APP_ID")
6464
api_key = getenv("TOOL_TTS_API_KEY")
6565
speaker = getenv(
66-
"TOOL_TTS_SPEAKER", "zh_female_vv_mars_bigtts"
66+
"TOOL_TTS_SPEAKER", "zh_female_vv_uranus_bigtts"
6767
) # e.g. zh_female_vv_mars_bigtts
6868
if not all([app_id, api_key, speaker]):
6969
return {
@@ -75,8 +75,8 @@ def text_to_speech(text: str, tool_context: ToolContext) -> Dict[str, Any]:
7575

7676
headers = {
7777
"X-Api-App-Id": app_id,
78-
"X-Api-Access-Key": api_key,
79-
"X-Api-Resource-Id": "seed-tts-1.0", # seed-tts-1.0 or seed-tts-2.0
78+
"X-Api-Key": api_key,
79+
"X-Api-Resource-Id": "seed-tts-2.0", # seed-tts-1.0 or seed-tts-2.0
8080
"Content-Type": "application/json",
8181
"Connection": "keep-alive",
8282
}

0 commit comments

Comments
 (0)