alibaba: a RAM user's NotAuthorised names the grants Token Plan needs (#6506)

hkxhkxhkx on X (#6506, v0.1.4026, gateway on OpenCloudOS): the Token
Plan personal edition's usage, read with a RAM user's AccessKey, fails
with BailianGateway.Team.NotAuthorised. The RAM user had the
AliyunBailian* and AliyunModelStudio* policies.

magpie calls the right API: GenerateCLIAccessToken, then the console
gateway's zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage, the same
call Alibaba's own CLI (modelstudioai/cli, `bl usage token-plan`) makes;
its only other parameter, switchAgent, is for delegated access, not RAM
users. Alibaba's Token Plan docs (personal FAQ; permissions and usage)
list what a RAM user needs, and none of it is a Bailian/ModelStudio
policy:
- the AliyunTokenPlanReadOnlyAccess (or FullAccess) system policy,
- AliyunBSSReadOnlyAccess for the personal edition,
- the Administrator or Subscribe Plan permission for the RAM user on
  Model Studio's Account Management page.
The NotAuthorised error now says those three and where, or to use the
main account's AccessKey. Any other refusal now carries the console's
errorMsg (read as raw JSON, so an odd type doesn't hide the code).

Tests: TestAliGatewayRAMNotAuthorised answers the call with the
console's NotAuthorised envelope and checks each grant is named, and
that another code shows its errorMsg. Broken by hand: the old message
makes it red on five checks.

Run on mica (and again after the rebase onto 49d7adef7): gofmt -l clean; go test ./internal/provider
-run TestAliGateway ok; vet as in the parent commit; go test ./internal/provider red only on
TestHostBuildsNoList (#6479). The editor's alibaba hint is unchanged:
the core script budget is red at base (#6518), and the error on the
Usage page carries the whole list. Not run: a real RAM
user's key (none here); the full suite.
This commit is contained in:
yetone
2026-11-13 18:41:28 +08:00
parent dc1f17c1c8
commit 456b5c6c74
3 changed files with 52 additions and 2 deletions
+1 -1
View File
@@ -412,7 +412,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
- A sub2api key's windows are fixed: each starts at the key's first request after it was empty, aligned to the relay's day, and a window not started yet says `used 0` with no `reset_at`, so it is taken to renew a span from now. They count this key's spend only, not the relay's accounts behind it. `ForgetBalances` (a key or Balance URL changed) has every key's windows read again at its next ask, a read begun before dropped; until then the last reading stands, fresher than the card's, which routing's reads never write. A key changed is another key (`keyID`), with windows of its own.
- A Volcengine Ark provider's access key (`TakesVolcAccessKey`: any of its bases on `ark.<region>.volces.com`) is kept with its keys and never sent to the GUI: `/api/providers` tells the editor its ID and whether a Secret is saved (`accessKey`). A save that leaves the Secret blank keeps it, one that leaves the ID out or sends it blank keeps both (an editor opened before the key was given sends `""`, #1821), and `clearAccessKey` drops both. The ID and Secret go together everywhere the keys go: a copy takes them, also when its form sends the source's ID without the Secret (`AddCopy`), a backup or sync without keys has neither (`withoutKeys`), and a restore, mirror or sync keeps this machine's (`KeepSecrets` in `Restore`, `Mirror`, davsync's `take`) when it came without keys, or with the same key and no access key at all, as a magpie before v0.1.1142 or one the access key was never given on sends it (#1821); another key is another account and brings its own. A copy without keys keeps this machine's secret headers (`SecretHeader`) the same way. A plan endpoint with no provider on it holding the access key is a card that says which to give (`accessKeyCard`, `needsAccessKey`), with a button to the provider's settings, not a card left out. A `providers.json` saved with a UTF-8 BOM is read through it, not taken for a broken file whose `.bak` stands in. The plan read is the endpoint's: `/api/coding` asks `GetCodingPlanUsage`, `/api/plan` asks `GetAFPUsage`, pay-as-you-go (`/api/v3`) has no card; the region is the host's. One card is read for each access key and plan. `GetCodingPlanUsage`'s reply (`QuotaUsage[]` with `Level`, `Percent`, `ResetTimestamp` in seconds) is the one three tools built on it read; `GetAFPUsage`'s buckets are read in each form those tools read (`Used` of `Quota` or `Total`, or `Percent`; `ResetTime` or `ResetTimestamp`), none of them seen from a real account here. A reply none of that reads says so on the card with the reply's head. Changing the access key drops the cached cards (`ForgetPlanQuotas`).
- A Tencent Cloud provider's SecretId and SecretKey are kept, listed and saved the same way, in the same fields (`AccessKeyVendor` tells the editor whose: `accessKey.vendor`, the preset's `accessKeyVendor`). Only the Token Plan's endpoints are read with them (`TakesTencentAccessKey`: `/plan` on `tokenhub.tencentmaas.com`, region `ap-guangzhou`, or `tokenhub-intl.tencentmaas.com`, `ap-singapore`). Since 10-22 Tencent serves 个人版 and 企业版 in China at the same `/plan` endpoints with the same `sk-tp-` keys (product/1823/130060, 130659), so they are one region, `plan` (a key saved on `enterprise` is on it, `regionAliases`/`RegionID`); 个人版 has no usage API, so a Guangzhou provider without a SecretId gets no card asking for one (`tcSharedRegion`), while Singapore's does. A Tencent Cloud provider saved at the old personal host `api.lkeap.cloud.tencent.com/plan/...` is moved to TokenHub's at load (`movedEndpoints`, `moveEndpoints` in `normalize`), with Responses added; one of no preset keeps the address its user typed, and an app imported at the old host lands on the plan. TokenHub's pay as you go has no plan and no card. A custom provider (no preset) at a Token Plan's or Ark plan's address is the user's own: its editor and Usage page ask it for no access key (`AsksAccessKey`) until one is saved on it, and its key goes as typed, `Authorization: Bearer` on chat and Responses (ysm119). The preset lists its regions that take one (`accessKeyRegions`, `presetAccessKey`), and the editor shows SecretId and SecretKey at those alone. `DescribeTokenPlanList` gives the account's team plans (a sub-user sees the ones it made); each is asked `DescribeTokenPlan` for its `PackageInfo` and `TokenSummary`, the list's kept for what the reply leaves out. The card's one window is `TotalUsed` of `CycleQuota` (else `TotalQuota`), resetting at `TokenSummary.CycleEndTime`, else counted in months from `StartTime` and never past `ExpireTime`. A plan not `enable` says its status beside the plan's name. Errors come back as 200 with `Response.Error`; an `AuthFailure…` or `UnauthorizedOperation` one says to check the key. Built from the API docs (api/1823/132270 and siblings) and the signing doc's worked example; never seen from a real account here.
- An Alibaba Cloud Token Plan provider's AccessKey ID and Secret are kept in the same fields (`AccessKeyVendor` "alibaba"). Only the plan's two hosts at `token-plan.<region>.maas.aliyuncs.com` take them (`TakesAlibabaAccessKey`, `aliPlanSite`: `cn-beijing` is `bailian-token-plan`, `ap-southeast-1` is `alibaba-token-plan`, #2940); the Qwen AI platform's (`qianwenaiapi.com`) and Qwen Cloud's plans have no read here (their console takes a browser sign-in, #5829). The plan key only authorizes inference. The usage is on the console's gateway behind a console token, which `POST modelstudio.<region>.aliyuncs.com/modelstudio/cli/generateAccessToken` (ACS3-HMAC-SHA256, `aliACSSign`; Action `GenerateCLIAccessToken`, version `2026-02-10`; reply `cliAccessToken`) makes from the AccessKey, as Alibaba's own `bl` CLI does. The token is kept 20 minutes per AccessKey and region and made again once when the gateway answers `BailianGateway.Login.NotLogined`. The gateway call is `POST <console>/cli/api.json?action=BroadScopeAspnGateway|IntlBroadScopeAspnGateway&product=sfm_bailian&api=zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage` with `Bearer` and a form `params`, `region`; the windows are the `per<N><Hour|Day|Week|Month>Percentage` (a share used, 0 to 1) and `ResetTime` (ms) fields of `data.DataV2.data.data`, so 5 hours, Weekly and Month show as the plan has them. A RAM user not in the Bailian workspace gets `BailianGateway.Team.NotAuthorised`, said in the card. Team plans (团队版) use other APIs and have no card. The gateway has no public doc: built from the official client's source; never seen from a real account here, and the international gateway host (`bailian-singapore-cs.alibabacloud.com`) is the least certain part.
- An Alibaba Cloud Token Plan provider's AccessKey ID and Secret are kept in the same fields (`AccessKeyVendor` "alibaba"). Only the plan's two hosts at `token-plan.<region>.maas.aliyuncs.com` take them (`TakesAlibabaAccessKey`, `aliPlanSite`: `cn-beijing` is `bailian-token-plan`, `ap-southeast-1` is `alibaba-token-plan`, #2940); the Qwen AI platform's (`qianwenaiapi.com`) and Qwen Cloud's plans have no read here (their console takes a browser sign-in, #5829). The plan key only authorizes inference. The usage is on the console's gateway behind a console token, which `POST modelstudio.<region>.aliyuncs.com/modelstudio/cli/generateAccessToken` (ACS3-HMAC-SHA256, `aliACSSign`; Action `GenerateCLIAccessToken`, version `2026-02-10`; reply `cliAccessToken`) makes from the AccessKey, as Alibaba's own `bl` CLI does. The token is kept 20 minutes per AccessKey and region and made again once when the gateway answers `BailianGateway.Login.NotLogined`. The gateway call is `POST <console>/cli/api.json?action=BroadScopeAspnGateway|IntlBroadScopeAspnGateway&product=sfm_bailian&api=zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage` with `Bearer` and a form `params`, `region`; the windows are the `per<N><Hour|Day|Week|Month>Percentage` (a share used, 0 to 1) and `ResetTime` (ms) fields of `data.DataV2.data.data`, so 5 hours, Weekly and Month show as the plan has them. A RAM user's key gets `BailianGateway.Team.NotAuthorised` until the main account grants what Alibaba's Token Plan docs ask for RAM users: the `AliyunTokenPlanReadOnlyAccess` and `AliyunBSSReadOnlyAccess` system policies (the `AliyunBailian*` and `AliyunModelStudio*` ones don't cover the Token Plan) and the Administrator or Subscribe Plan permission on Model Studio's Account Management page; the card and the editor's hint name all three (`aliRAMHint`, #6506). The same API serves the main account and RAM users; `bl` has no other route. Another refusal shows the console's `errorMsg`. Team plans (团队版) use other APIs and have no card. The gateway has no public doc: built from the official client's source; never seen from a real account here, and the international gateway host (`bailian-singapore-cs.alibabacloud.com`) is the least certain part.
- Whether a Codex account spends its credits (`CodexNoCredits` in settings, opt-out, by lower-cased email) is the gateway's routing only. It never changes which account Codex is signed in to: `NextLogin` moves off an account at its routing's spent share, 100% at most, credits or not.
- A Vertex AI provider's credentials are read only when a request is signed (`Sign`), so adding, listing and showing one ask Google nothing. With no `credentials` given and no file where Application Default Credentials are looked for, the request fails with `no Google credentials at <file>`, naming `gcloud auth application-default login` and the provider's credentials file as the ways to give it some. A `credentials` file that isn't there fails with the same words, saying to correct it or clear it. When Google refuses a person's sign-in (revoked, or past the organization's session length), the error says how to sign in again for the file used (`signInAgain`): gcloud's Application Default Credentials with `gcloud auth application-default login`, adding `--impersonate-service-account=<account>` when the file impersonates one; a file under gcloud's `legacy_credentials/<account>/` with `gcloud auth login <account>`; any other file by writing it anew or giving the provider another. The new file is read at the next request, with no restart.
- Not read for Vertex AI: the metadata server of Compute Engine, Cloud Run and GKE; workload identity federation (`external_account`, `external_account_authorized_user`, refused by name); credentials whose `universe_domain` isn't `googleapis.com`; Vertex AI's express-mode API keys (Save refuses a key). No quota project is sent: Vertex AI bills the project in the URL.
+16 -1
View File
@@ -25,6 +25,11 @@ package provider
// personal plan's API is known; the Qwen AI platform's and Qwen Cloud's
// plans sit behind a console of their own that takes a browser sign-in, so
// they have no card (#5829).
//
// A RAM user's key is refused by the console (BailianGateway.Team.
// NotAuthorised) until the main account grants what Alibaba's Token Plan
// docs list for RAM users (aliRAMHint); the same API serves the main
// account and RAM users, the bl CLI has no other route for them.
import (
"bytes"
@@ -54,6 +59,12 @@ const (
aliUsageAPI = "zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage"
aliPlanName = "Token Plan"
aliKeyHint = "check the AccessKey ID and Secret in the provider's editor (Alibaba Cloud console → AccessKey), and that the account may use Model Studio"
// aliRAMHint is what Alibaba asks of a RAM user's key for the Token
// Plan (Token Plan → Permissions and usage → RAM user authorization):
// two system policies the Bailian and ModelStudio ones don't include,
// and a permission given in Model Studio's own console. Without the
// last the console answers BailianGateway.Team.NotAuthorised (#6506).
aliRAMHint = "a RAM user's AccessKey needs, from the main account: the AliyunTokenPlanReadOnlyAccess and AliyunBSSReadOnlyAccess system policies in the RAM console (AliyunBailian* and AliyunModelStudio* policies don't cover the Token Plan), and the Administrator or Subscribe Plan permission for this RAM user on the Account Management page of the Model Studio (Bailian) console. Or use the main account's own AccessKey"
// aliTokenTTL is how long a console token is kept before a new one is
// made; one the console refuses is made again at once
aliTokenTTL = 20 * time.Minute
@@ -343,6 +354,7 @@ func aliGateway(ctx context.Context, token string, site aliSite) ([]byte, error)
Data struct {
Success *bool `json:"success"`
ErrorCode json.RawMessage `json:"errorCode"`
ErrorMsg json.RawMessage `json:"errorMsg"`
DataV2 json.RawMessage `json:"DataV2"`
} `json:"data"`
}
@@ -355,7 +367,10 @@ func aliGateway(ctx context.Context, token string, site aliSite) ([]byte, error)
case strings.Contains(code, "NotLogined"):
return nil, errAliNotLogged
case strings.Contains(code, "NotAuthorised"), strings.Contains(code, "NotAuthorized"):
return nil, fmt.Errorf("Alibaba Cloud's console: %s: this RAM user isn't authorised in Model Studio's workspace; add it there in the Alibaba Cloud console, or use the account's own access key", code)
return nil, fmt.Errorf("Alibaba Cloud's console: %s: %s", code, aliRAMHint)
}
if msg := strings.TrimSpace(strings.Trim(string(env.Data.ErrorMsg), `"`)); msg != "" && msg != "null" {
return nil, fmt.Errorf("Alibaba Cloud's console: %s: %s", code, msg)
}
return nil, fmt.Errorf("Alibaba Cloud's console: %s", code)
}
+35
View File
@@ -188,3 +188,38 @@ func TestAliPlanQuotas(t *testing.T) {
t.Errorf("keyless: %+v", a)
}
}
// #6506 (FuturePrayer, hkxhkxhkx on X): a RAM user's key that had every
// AliyunBailian* and AliyunModelStudio* policy got BailianGateway.Team.
// NotAuthorised, and the card said only "add it there in the Alibaba Cloud
// console". It now names what Alibaba's Token Plan docs ask for a RAM user:
// the two Token Plan and billing policies, and the permission on Model
// Studio's Account Management page. Another refusal keeps the console's own
// errorMsg.
func TestAliGatewayRAMNotAuthorised(t *testing.T) {
reply := `{"code":"200","data":{"success":false,"errorCode":"BailianGateway.Team.NotAuthorised","errorMsg":"team not authorised","requestId":"r1"}}`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Host") != "bailian-cs.console.aliyun.com" {
t.Errorf("asked %s", r.Header.Get("X-Host"))
}
io.WriteString(w, reply)
}))
defer srv.Close()
old := http.DefaultClient.Transport
http.DefaultClient.Transport = rewrite{srv}
t.Cleanup(func() { http.DefaultClient.Transport = old })
_, err := aliGateway(context.Background(), "tok", aliSites["cn-beijing"])
if err == nil {
t.Fatal("no error")
}
for _, want := range []string{"BailianGateway.Team.NotAuthorised", "AliyunTokenPlanReadOnlyAccess", "AliyunBSSReadOnlyAccess", "Account Management", "Administrator or Subscribe Plan", "main account's own AccessKey"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("%q doesn't say %q", err, want)
}
}
reply = `{"code":"200","data":{"success":false,"errorCode":"BailianGateway.Something.Else","errorMsg":"something else went wrong"}}`
if _, err := aliGateway(context.Background(), "tok", aliSites["cn-beijing"]); err == nil || err.Error() != "Alibaba Cloud's console: BailianGateway.Something.Else: something else went wrong" {
t.Errorf("other refusal: %v", err)
}
}