Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions .github/workflows/unit_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,14 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
# The 2.0 surface runs on the odd CPython legs only (3.9/3.11/3.13).
# ubuntu-latest (26.04) ships no CPython 3.9 build, so pin the
# still-supported 3.9 leg to 24.04 and keep the rest on latest.
include:
- os: ubuntu-24.04
python-version: '3.9'
- os: ubuntu-latest
python-version: '3.10'
- os: ubuntu-latest
python-version: '3.11'
- os: ubuntu-latest
python-version: '3.12'
- os: ubuntu-latest
python-version: '3.13'

Expand Down
127 changes: 127 additions & 0 deletions dashscope/management/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# -*- coding: utf-8 -*-
# Copyright (c) Alibaba, Inc. and its affiliates.
"""ManagementClient -- the RAM OpenAPI (ModelStudio/2026-02-10) surface.

An optional extra: ``pip install 'dashscope[management]'`` pulls in
``alibabacloud_credentials`` (the multi-tenant credential chain) and
``alibabacloud_openapi_util`` (ACS3-HMAC-SHA256 V3 signing). The core
``dashscope`` package does not import this module, so installing the base
SDK never forces the aliyun cloud libraries.

This revision is read-only (G1/G2/G5): workspace / API-key / billing /
TokenPlan reads. Write operations are high-risk and deferred.
"""

from __future__ import annotations

try:
import alibabacloud_credentials # noqa: F401
import alibabacloud_openapi_util # noqa: F401
except ImportError as exc: # pragma: no cover - exercised only without extra
raise ImportError(
"dashscope.management requires the optional 'management' extra "
"(alibabacloud_credentials, alibabacloud_openapi_util). "
"Install it with: pip install 'dashscope[management]'",
) from exc

from dashscope.management._credentials import (
CredentialResolver,
ResolvedCredential,
)
from dashscope.management._errors import (
Envelope,
check_management_response,
decode_body,
management_error,
read_envelope,
)
from dashscope.management._pagination import TokenPage
from dashscope.management._redaction import (
REDACTED,
SecretRedactionFilter,
mask_secret,
redact_body,
)
from dashscope.management.client import (
AsyncManagementClient,
ManagementClient,
ManagementConfig,
)
from dashscope.management.types import (
ApiKey,
ApiKeyAuth,
BillingGroup,
BillingOverview,
BillingTrend,
CostTotals,
GroupByTotal,
InferenceMetadata,
ManagementModel,
ModelAccessScope,
ModelInfo,
ModelLimit,
ModelPermission,
OrgMember,
OrgMemberPage,
OrgMembership,
Permissions,
Price,
RateLimit,
ResultByTime,
Seat,
SeatPage,
SeatStats,
SharedPackage,
SharedPackagePage,
SubscriptionSeatItem,
SubscriptionStats,
TokenPlanAccount,
Workspace,
)

__all__ = [
"REDACTED",
"ApiKey",
"ApiKeyAuth",
"AsyncManagementClient",
"BillingGroup",
"BillingOverview",
"BillingTrend",
"CostTotals",
"CredentialResolver",
"Envelope",
"GroupByTotal",
"InferenceMetadata",
"ManagementClient",
"ManagementConfig",
"ManagementModel",
"ModelAccessScope",
"ModelInfo",
"ModelLimit",
"ModelPermission",
"OrgMember",
"OrgMemberPage",
"OrgMembership",
"Permissions",
"Price",
"RateLimit",
"ResolvedCredential",
"ResultByTime",
"Seat",
"SeatPage",
"SeatStats",
"SecretRedactionFilter",
"SharedPackage",
"SharedPackagePage",
"SubscriptionSeatItem",
"SubscriptionStats",
"TokenPage",
"TokenPlanAccount",
"Workspace",
"check_management_response",
"decode_body",
"management_error",
"mask_secret",
"read_envelope",
"redact_body",
]
100 changes: 100 additions & 0 deletions dashscope/management/_credentials.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# -*- coding: utf-8 -*-
# Copyright (c) Alibaba, Inc. and its affiliates.
"""Multi-tenant credential chain for the management surface.

Wraps the official ``alibabacloud_credentials`` client so a ToB backend
can hand the SDK any of: an explicit AK/SK (optionally an STS token), a
``Config`` dict for the richer provider types (ECS RAM role, RAM role
ARN, OIDC, credentials URI), a pre-built credentials ``Client``, or
nothing at all to fall through to the library's default chain
(environment, IMDS, ...). Resolution returns a frozen snapshot; the
library owns refresh, so an STS token that expires mid-process is
re-fetched on the next ``resolve()``.

No secret is ever logged here -- the resolved snapshot is handed
straight to the signer.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Mapping, Optional

from alibabacloud_credentials.client import Client as _CredentialsClient
from alibabacloud_credentials.models import Config as _CredentialsConfig

__all__ = ["CredentialResolver", "ResolvedCredential"]


@dataclass(frozen=True)
class ResolvedCredential:
"""One credential snapshot used to sign a single request."""

access_key_id: str
access_key_secret: str
security_token: Optional[str] = None
provider_name: Optional[str] = None


class CredentialResolver:
"""Resolve management credentials through the official chain.

Precedence: a pre-built ``credential`` client wins, then an explicit
``config`` dict, then explicit ``access_key_id`` / ``access_key_secret``
(with ``security_token`` selecting the STS provider type), then the
library default chain. A *partial* explicit AK (id without secret, or
a lone token) raises instead of falling through: silently signing with
ambient host credentials would swap a tenant's identity.
"""

def __init__(
self,
*,
access_key_id: Optional[str] = None,
access_key_secret: Optional[str] = None,
security_token: Optional[str] = None,
credential: Optional[Any] = None,
config: Optional[Mapping[str, Any]] = None,
) -> None:
if credential is not None:
self._client = credential
elif config is not None:
self._client = _CredentialsClient(
_CredentialsConfig(**dict(config)),
)
elif access_key_id or access_key_secret or security_token:
# Fail loudly on a partial explicit credential: the default
# chain below picks up the host's env/IMDS identity, which in
# a multi-tenant backend is a silent cross-tenant swap.
if not (access_key_id and access_key_secret):
raise ValueError(
"access_key_id and access_key_secret must be provided "
"together; refusing to fall back to ambient credentials",
)
self._client = _CredentialsClient(
_CredentialsConfig(
type="sts" if security_token else "access_key",
access_key_id=access_key_id,
access_key_secret=access_key_secret,
security_token=security_token,
),
)
else:
self._client = _CredentialsClient()

def resolve(self) -> ResolvedCredential:
"""Fetch a credential snapshot synchronously."""
return _snapshot(self._client.get_credential())

async def resolve_async(self) -> ResolvedCredential:
"""Fetch a credential snapshot without blocking the event loop."""
return _snapshot(await self._client.get_credential_async())


def _snapshot(model: Any) -> ResolvedCredential:
return ResolvedCredential(
access_key_id=model.access_key_id,
access_key_secret=model.access_key_secret,
security_token=model.security_token,
provider_name=getattr(model, "provider_name", None),
)
Loading
Loading