<span id="为角色授予指定工作流的运行权限"></span>
<span id="管理角色与对象权限"></span>

# Manage Roles and Object Permissions

Use the workspace IAM handle to inspect the role directory and permission schema, pre-validate object grant mutations, and apply changes after reviewing their impact. This guide demonstrates granting the `workflow.run` permission on a workflow to an ordinary role.

(sdk-ai-studio-iam-flow)=
<span id="任务流程"></span>

## Task flow

```text
Workspace IAM handle
         │
         ▼
1. Inspect role directory, permission schema, and current object permissions
         │
         ▼
2. Build object grant mutation and pre-validate (validate only, no write)
         │
         ▼
3. Apply object grants ──▶ Re-read permission view to confirm direct grant
```

(sdk-ai-studio-iam-prepare)=
<span id="准备"></span>

## Prerequisites

1. Complete the endpoint, personal access token, and workspace setup in [Use the SDK](../../../quickstart/ai-studio/sdk.md).
2. Ensure the current identity has permission to read role permissions and manage object grants in the target workspace.
3. Determine the editable ordinary role ID and the target workflow ID; both can be retrieved from the role directory and workflow list calls in step 1.

(sdk-ai-studio-iam-s1)=
<span id="列出角色和工作流再校验授权"></span>
<span id="1-查看角色与对象当前权限"></span>

## 1. Inspect roles and current object permissions

List the workspace role directory and workflows first, then read the target role's permission view (verifying that it is not a protected role and permits policy mutations), the workspace permission schema version, and the current permission view of the target workflow.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
import os
import uuid

import moi_product_sdk as sdk

client = sdk.new_with_personal_access_token(
    os.environ["PRODUCT_API_BASE_URL"],
    os.environ["PRODUCT_API_KEY"],
)
workspace = client.workspace(os.environ["WORKSPACE_ID"])
iam = workspace.iam()

for item in iam.roles().roles:
    print(
        "role:",
        item.role_id,
        item.role_name,
        item.lifecycle_state,
        "editable:",
        item.policy_mutation_allowed,
    )

page = workspace.workflows().list()
for wf in page.workflows:
    print("workflow:", wf.id, wf.name)

role_id = os.environ["TARGET_ROLE_ID"]
workflow_id = os.environ["WORKFLOW_ID"]

role = iam.role_permission_view(role_id)
if role.protected_role or not role.policy_mutation_allowed:
    raise RuntimeError("Target role does not allow policy mutations")

schema = iam.permission_schema()
before = iam.object_permission_view("workflow", workflow_id)
print("owner role:", before.owner.role_id, "policy version:", role.policy_version)
```

::::

::::{tab-item} Go
:sync: go

```go
package main

import (
	"context"
	"fmt"
	"os"
	"time"

	sdk "github.com/matrixorigin/matrixflow/sdk/go-sdk"
)

func main() {
	ctx := context.Background()
	client, err := sdk.NewWithPersonalAccessToken(
		os.Getenv("PRODUCT_API_BASE_URL"),
		os.Getenv("PRODUCT_API_KEY"),
	)
	if err != nil {
		panic(err)
	}
	defer client.Close()
	workspace, err := client.Workspace(os.Getenv("WORKSPACE_ID"))
	if err != nil {
		panic(err)
	}
	iam := workspace.IAM()

	roles, err := iam.Roles(ctx)
	if err != nil {
		panic(err)
	}
	for _, item := range roles.GetRoles() {
		fmt.Println("role:", item.GetRoleId(), item.GetRoleName(), item.GetLifecycleState(), "editable:", item.GetPolicyMutationAllowed())
	}

	page, err := workspace.Workflows().List(ctx)
	if err != nil {
		panic(err)
	}
	for _, wf := range page.GetWorkflows() {
		fmt.Println("workflow:", wf.GetId(), wf.GetName())
	}

	roleID := os.Getenv("TARGET_ROLE_ID")
	workflowID := os.Getenv("WORKFLOW_ID")

	role, err := iam.RolePermissionView(ctx, roleID)
	if err != nil {
		panic(err)
	}
	if role.GetProtectedRole() || !role.GetPolicyMutationAllowed() {
		panic("Target role does not allow policy mutations")
	}

	schema, err := iam.PermissionSchema(ctx)
	if err != nil {
		panic(err)
	}
	before, err := iam.ObjectPermissionView(ctx, "workflow", workflowID)
	if err != nil {
		panic(err)
	}
	fmt.Println("owner role:", before.GetOwner().GetRoleId(), "policy version:", role.GetPolicyVersion())
	_ = time.Now
}
```

::::

:::::

(sdk-ai-studio-iam-s2)=
(sdk-ai-studio-iam-s3)=
<span id="配置目标并保存授权"></span>
<span id="2-预校验对象授权变更"></span>

## 2. Pre-validate object grant changes

Construct an object grant mutation request using the schema version, expected policy version, and expected role lifecycle version obtained in step 1, then run pre-validation to inspect expected additions and removals. Pre-validation checks versions and policy rules without writing or locking saved grants.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
request = sdk.IAMObjectGrantsMutationRequest(
    schema_version=schema.schema_version,
    expected_policy_version=role.policy_version,
    expected_role_lifecycle_version=role.expected_role_lifecycle_version,
    request_id=str(uuid.uuid4()),
    changes=[sdk.IAMObjectGrantChange(action_id="workflow.run", remove=False)],
)

checked = iam.validate_object_grants("workflow", workflow_id, role_id, request)
print(
    "validate_only:",
    checked.validate_only,
    "would_add:",
    checked.added_count,
    "would_remove:",
    checked.removed_count,
)
```

::::

::::{tab-item} Go
:sync: go

```go
request := &sdk.IAMObjectGrantsMutationRequest{
	SchemaVersion:                schema.GetSchemaVersion(),
	ExpectedPolicyVersion:        role.GetPolicyVersion(),
	ExpectedRoleLifecycleVersion: role.GetExpectedRoleLifecycleVersion(),
	RequestId:                    fmt.Sprintf("workflow-grant-%d", time.Now().UnixNano()),
	Changes: []*sdk.IAMObjectGrantChange{
		{ActionId: "workflow.run", Remove: false},
	},
}

checked, err := iam.ValidateObjectGrants(ctx, "workflow", workflowID, roleID, request)
if err != nil {
	panic(err)
}
fmt.Println("validate_only:", checked.GetValidateOnly(), "would_add:", checked.GetAddedCount(), "would_remove:", checked.GetRemovedCount())
```

::::

:::::

(sdk-ai-studio-iam-limit)=
(sdk-ai-studio-iam-confirm)=
<span id="确认授权结果"></span>
<span id="3-提交授权并确认结果"></span>

## 3. Apply grants and confirm the result

Once pre-validation output matches your intended scope, submit the same request and re-read the workflow's permission view to verify that the role's direct grants include `workflow.run`. If the grant already existed, the added count can be `0`.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
saved = iam.apply_object_grants("workflow", workflow_id, role_id, request)
print(
    "saved_role:",
    saved.target_role_id,
    "policy_version:",
    saved.policy_version,
    "added:",
    saved.added_count,
    "removed:",
    saved.removed_count,
)

current = iam.object_permission_view("workflow", workflow_id)
granted = any(
    grant.role_id == role_id
    and grant.action_id == "workflow.run"
    and grant.resource_id == workflow_id
    for grant in current.direct_grants
)
if not granted:
    raise RuntimeError("Direct workflow.run grant not found in refreshed permission view")
print("Confirmed direct workflow.run grant.")
```

::::

::::{tab-item} Go
:sync: go

```go
saved, err := iam.ApplyObjectGrants(ctx, "workflow", workflowID, roleID, request)
if err != nil {
	panic(err)
}
fmt.Println("saved_role:", saved.GetTargetRoleId(), "policy_version:", saved.GetPolicyVersion(), "added:", saved.GetAddedCount(), "removed:", saved.GetRemovedCount())

current, err := iam.ObjectPermissionView(ctx, "workflow", workflowID)
if err != nil {
	panic(err)
}
granted := false
for _, grant := range current.GetDirectGrants() {
	if grant.GetRoleId() == roleID && grant.GetActionId() == "workflow.run" && grant.GetResourceId() == workflowID {
		granted = true
		break
	}
}
if !granted {
	panic("Direct workflow.run grant not found in refreshed permission view")
}
fmt.Println("Confirmed direct workflow.run grant.")
```

::::

:::::

If a concurrent edit triggers a version conflict, re-read the role's permission view to fetch the latest version numbers and review the changes before submitting again. Granting workflow execution permission does not automatically grant access to tables or connectors referenced inside the workflow; authorize dependent resources separately.

(sdk-ai-studio-iam-next)=
<span id="下一步"></span>

## Next steps

- [Configure Role Inheritance](配置角色继承.md)
- [Configure Row and Column Privileges](配置行列数据权限.md)
- [Delete Roles and Resolve Dependencies](删除角色并处理依赖.md)
- [Bind a Workspace](绑定工作区.md#sdk-ai-studio-workspace-current-role)
