Rotate the Workspace Default Collection Token¶
POST /api/v1/workspace/{workspace_uuid}/token/rotate
Overview¶
Rotate the default collection Token of the specified workspace and set a short grace period for the old value.
Before Calling and Usage Steps¶
First inventory the collection agents and integrations that use the default Token, and choose an old-value validity period long enough to complete the replacement. ttl controls the remaining validity period of the old Token, not the validity period of the new Token. After success, securely save content.token and update the collection configuration; references to the default credential are handled during synchronization, but Tokens stored externally must still be replaced separately. This API generates new credentials on each call and is not idempotent. It cannot be rotated again within 24 hours. On failure, be sure to check content.committed; if it has been saved, handle synchronization and do not continue rotating. If the response is lost, ask the administrator to confirm the current value and synchronization status in Workspace Token Management before continuing.
Route Parameters¶
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| workspace_uuid | string | Y | Target workspace UUID; it is not an account UUID or a collection Token. Example: wksp_example001How to obtain or specify: Obtain it from content.data[].uuid in the Workspace List or from content.wsInfo.uuid returned after successful creation, and verify the site and workspace name. |
Request Headers¶
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| X-Df-SVersion | string | Must be consistent with the example; do not omit it and continue using this algorithm. Example: v20240417How to obtain or specify: Specify it together with the signature algorithm of the original path and request body on this page. |
|
| X-Df-Access-Key | string | Y | This API requires External API credentials with w write permission. Example: <external-access-key>How to obtain or specify: The site administrator assigns an External API AK with w permission; this is not a workspace OpenAPI Key. |
| X-Df-Signature | string | Y | The uppercase method, nonce, original full path, timestamp, and original UTF-8 request body are joined with spaces and hashed with HMAC-SHA256 hex digest. Example: <hmac-sha256-hex>How to obtain or specify: Use the matching SK to calculate it according to External API Signature Authentication and the Python template below. |
| X-Df-Timestamp | string | Y | Do not reuse the fixed time in the example; it must fall within the site's signature validity window. Example: 1785427200How to obtain or specify: Generate the current Unix seconds with str(int(time.time())) when sending. |
| X-Df-Nonce | string | Y | Update this value and the signature on every resend as well. Example: 97d275ee9f774315a7885ba7347acbd9How to obtain or specify: Regenerate uuid.uuid4().hex for each request. |
Body Request Parameters¶
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| ttl | string | Y | Required string. Only 0s or a positive integer followed by lowercase s/m/h/d is accepted. 0s means the old value is invalidated immediately; other values specify the remaining grace period for the old value and cannot exceed 24 hours. Whitespace, null, decimals, and uppercase units are not accepted. Allow null: False $matchRegExp: ^(0s|[1-9][0-9]*[smhd])$ Example: 30mHow to obtain or specify: Choose 0s, 30m, 1h, 24h, or 1d, etc., based on the collection agent replacement window; the maximum is 86400 seconds. |
Additional Parameter Notes¶
Use site-level External API credentials with w permission. For authentication, see External API Signature Authentication. The example calculates the signature for v20240417; signing and sending use the same path, query, and original request body. All examples are demonstration values; replace them with actual targets before execution. After a write request times out or returns 500, query the current status first and decide whether to retry only after confirmation.
Request Example¶
import hashlib
import hmac
import json
import time
import uuid
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError
# Replace with the target site address and the External API AK/SK assigned by the administrator.
server = "https://external-api.guance.com"
access_key = "<external-access-key>"
secret_key = "<external-secret-key>"
method = 'POST'
path = '/api/v1/workspace/wksp_example001/token/rotate'
query = {}
data = {'ttl': '30m'}
full_path = path + ("?" + urlencode(query) if query else "")
body = "" if data is None else json.dumps(data, ensure_ascii=False, separators=(",", ":"))
timestamp = str(int(time.time()))
nonce = uuid.uuid4().hex
string_to_sign = " ".join([method, nonce, full_path, timestamp, body])
signature = hmac.new(secret_key.encode("utf-8"), string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
headers = {
"X-Df-Access-Key": access_key,
"X-Df-Timestamp": timestamp,
"X-Df-Nonce": nonce,
"X-Df-Signature": signature,
"X-Df-SVersion": "v20240417",
}
if data is not None:
headers["Content-Type"] = "application/json"
request = Request(server + full_path, data=None if data is None else body.encode("utf-8"), headers=headers, method=method)
try:
with urlopen(request, timeout=30) as result:
payload = json.loads(result.read().decode("utf-8"))
except HTTPError as error:
print("HTTP", error.code, error.read().decode("utf-8")) # Preserve errorCode, content, and traceId to determine whether the change has been committed.
raise SystemExit(1)
except (URLError, TimeoutError):
print("The request result is unknown. Query the target workspace configuration and task status first, and do not automatically retry write requests.")
raise SystemExit(1)
print(json.dumps(payload, ensure_ascii=False, indent=2))
Response¶
HTTP 200 with a unified application/json envelope; External does not automatically inject declaration. content contains the new default collection Token and related status information, not the complete workspace object.
| Field | Type | Description |
|---|---|---|
| content.token | string | The plaintext new default collection Token returned by this call should be securely saved; it is not an External API AK. Users with the appropriate permissions can still read the valid Token later; do not rely on repeated rotation to recover the current value. |
| content.openDataQuery | boolean | Data query permission flag for the current Token; rotation retains the original permission. |
| content.committed | boolean | Returned only for some 409 errors: true means the new Token has been saved; false means it has not been saved in this call. |
| content.nextRotateAt | integer | Returned only for cooldown 409 errors: Unix seconds when the next rotation is allowed. |
| content.syncStatus | string | Returned only for synchronization 409 errors, usually pending. |
| content.syncRequiresVerification | boolean | Provided for some synchronization errors; if true, downstream results must be verified first. |
| content.syncFailureReason | string | Provided for some synchronization errors, for example operation_busy, cache_pending, verification_required, kodo_timeout, kodo_failed. |
| content.tokenRecordUUID | string or null | Provided for some synchronization errors; for the default Token, this is usually null. |
| content.isDefault | boolean | Provided for some synchronization errors; the target of this API is the default Token, and the value is true. |
| Response Header | Type | Description |
|---|---|---|
| Cache-Control | string | The success response is no-store. |
| Pragma | string | The success response is no-cache. |
{
"code": 200,
"content": {
"token": "<new-workspace-token>",
"openDataQuery": false
},
"errorCode": "",
"message": "",
"success": true,
"traceId": "TRACE-EXAMPLE"
}
Error Response¶
For authentication, rate limiting, and common request errors, see Common Error Definitions.
The following table lists the business validation and confirmed main error branches of this API. Downstream services may also return other 4xx errors mapped from specific errors; ordinary 5xx and unknown exceptions are handled globally and return ft.InternalServerError. For write requests, determine whether a change has taken effect based on the current configuration and error content; do not infer rollback solely from the HTTP status.
| HTTP Status | errorCode | Trigger Condition | Message or Response Description | Handling |
|---|---|---|---|---|
| 406 | ft.ParameterValidationFailed | A request field is missing, or the field value violates the declared validation conditions | Parameter parsing failed | Check the parameter location, field name, type, and value. |
| 400 | ft.RequestJsonFormatError | The request JSON syntax is invalid | Request JSON format error | Correct the JSON according to content.reason, line, and column. |
| 400 | ft.JsonFormatError | The top level of the JSON is not an object | Some JSON file format error | Submit a JSON object according to the parameter table; do not use an array or null as the entire request body. |
| 401 | ft.WKSPNotExistOrReleased | The workspace does not exist or status is not 0 | Workspace does not exist or has been released | Confirm the workspace activity status from the list. |
| 404 | ft.ObjectNotExists | The current default Token record for the workspace is missing | The specified object does not exist | Ask the administrator to repair the Token record for the workspace; do not use this API to create a replacement record. |
| 400 | ft.WorkspaceTokenInvalidTTL | The format is valid, but the old value grace period exceeds 24 hours | The old value validity period cannot exceed 24 hours | Use 0s for immediate invalidation, or a validity duration not exceeding 24 hours. |
| 409 | ft.WorkspaceTokenCooling | Less than 24 hours have passed since the last rotation, including the cooldown time retained by the old entry point | It is not yet time to regenerate | Read content.nextRotateAt and wait until that Unix time before requesting again; do not keep retrying. |
| 409 | ft.WorkspaceTokenRevoked | The default Token has been revoked, has expired, or is unavailable | Token has been revoked or is unavailable | Ask the administrator to check the current credential status of the workspace; do not treat rotation as credential recovery. |
| 409 | ft.WorkspaceTokenOperationBusy | Another operation already exists when acquiring the workspace lifecycle lock | Another operation is in progress in the current workspace. This operation was not saved. Try again later. | When content.committed=false, you can retry later with a new signature. |
| 409 | ft.WorkspaceTokenSyncPending | A synchronization is already pending, or synchronization with Kodo after the rotation submission has not completed or the result needs verification | Depending on the branch, the message is "This operation was not saved" or "The change has been saved"; you must determine this together with content.committed | committed=true means rotation has already occurred; do not rotate again. The administrator should first verify the Kodo status, then synchronize the committed current state. When syncRequiresVerification=true, verify first; do not replay blindly. |
| 500 | ft.InternalServerError | Database, cache, resource service, or unhandled parameter conversion exception | Internal error | First check content.committed and the current default Token and synchronization status. If it has been saved, handle only the incomplete synchronization and do not rotate again. Keep the traceId and contact the administrator. |
Example of a submitted change whose downstream synchronization failed (HTTP 409; do not rotate again):
{
"code": 409,
"content": {
"committed": true,
"syncStatus": "pending",
"syncFailureReason": "kodo_failed",
"syncRequiresVerification": false,
"tokenRecordUUID": null,
"isDefault": true
},
"errorCode": "ft.WorkspaceTokenSyncPending",
"message": "变更已保存,但调用 Kodo 接口同步失败。请重试同步,无需重复提交本次操作。",
"success": false,
"traceId": "TRACE-EXAMPLE"
}