Skip to content

fix: Remove unused permissions from v2 remnants - #7966

Merged
shaohuzhang1 merged 1 commit into
v3from
pr@v3@fix_permission
Nov 17, 2026
Merged

shaohuzhang1 merged 1 commit into
v3from
pr@v3@fix_permission

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

fix: Remove unused permissions from v2 remnants

paragraph_id: str,
):
return result.success(
ApplicationChatRecordImproveSerializer.Operate(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Main issue: this patch is not just formatting/import cleanup — it removes the ViewPermission(...) authorization clause from every affected endpoint. That is a functional/security change.

  • Authorization regression/change (high priority): The removed clause allowed RoleConstants.USER plus PermissionConstants.APPLICATION with compare=AND. Depending on has_permissions semantics, removing it either:

    • narrows access, if the decorator treats arguments as OR alternatives, or
    • widens access, if it treats them as AND requirements.

    Either way, the permission matrix changes for ApplicationChatRecord.get, Page.get, ApplicationChatRecordOperateAPI.get, ApplicationChatRecordAddKnowledge.post, ApplicationChatRecordImprove.get, ApplicationChatRecordImproveParagraph.put, and Operate.delete. Confirm this is intentional and add/adjust permission tests.

  • Removed imports: ViewPermission and CompareConstants imports are removed. This is correct only if there are no remaining references anywhere in the file. Run grep -n "ViewPermission\|CompareConstants" and the linter to confirm there is no NameError.

  • Import ordering: Moving common.* imports after local serializer imports may violate your project’s isort/lint rules. Run isort/ruff/flake8. Also verify whether TokenAuth is actually used; if not, remove it.

  • Formatting changes: The parameter indentation fixes and the added trailing comma in Page.get’s decorator are good.

  • Optimization suggestion: Several endpoints repeat similar permission lists. Consider a shared permission tuple/helper for chat-log read/annotation permissions, but only if it keeps the decorator behavior clear.

  • Testing recommendation: Add tests for each changed endpoint covering at least:

    • workspace user with application permission,
    • workspace user with chat-log permission,
    • workspace manager,
    • unauthenticated user,
    • expected 403/200 behavior.

Overall: the code is syntactically plausible in the shown diff, but the authorization changes should be reviewed and tested before merging.

TagSerializers.BatchDelete(
data={"workspace_id": workspace_id, "knowledge_id": knowledge_id, "tag_ids": request.data}
).batch_delete()
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of the Diff

🔴 Critical / Behavioral Change

1. Permission semantics changed — ViewPermission removed from all 5 endpoints
Every @has_permissions(...) block lost:

ViewPermission([RoleConstants.USER.get_workspace_role()],
               [PermissionConstants.KNOWLEDGE.get_workspace_knowledge_permission()],
               compare=CompareConstants.AND)

Previously a user with USER role AND the KNOWLEDGE permission could access these endpoints. Now access requires one of the remaining permissions (KNOWLEDGE_TAG_*, workspace-manage, etc.).

  • If this is intentional (tightening access), it's a security-relevant change and should be covered by permission tests.
  • If has_permissions uses OR semantics, this silently removes a valid access path → likely a regression.
  • Verify no other usage of CompareConstants / ViewPermission remains in this file (the import removal will raise NameError at runtime otherwise). Run linters/unit tests.

🟠 Bugs (pre-existing, but touched by this diff)

2. Wrong audit-log operation on the GET handler

@log(menu="tag", operate="Create a knowledge tag", ...)   # in `get()`

This is a GET, but the operation string says "Create". Audit logs will be misleading. Should be e.g. "Get knowledge tag" / "Query knowledge tags".

3. Wrong API schema on GET

parameters=TagCreateAPI.get_parameters(),
request=TagCreateAPI.get_request(),
responses=TagCreateAPI.get_response(),

A GET endpoint documents a request body (request=...) and reuses the Create schema. This produces incorrect OpenAPI docs. Should use a read/query API definition.

4. BatchDelete reuses TagDeleteAPI

parameters=TagDeleteAPI.get_parameters(),
request=TagDeleteAPI.get_request(),
responses=TagDeleteAPI.get_response(),

Batch deletion likely accepts tag_ids (a list), while TagDeleteAPI is for a single tag. Schema/docs mismatch; consider a dedicated TagBatchDeleteAPI.

5. request.query_params.get("name") returns None when absent
Fine only if the serializer treats None as "no filter". If it does an exact match, this can produce unexpected results. Consider an explicit if "name" in request.query_params check.

🟡 Style / Consistency

6. Inconsistent operation strings — "Batch Delete knowledge tag" vs "Create a knowledge tag" vs "Update a knowledge tag". Standardize capitalization/wording.

7. Unused lambda parameter — lambda r, keywords: ... — r is unused; rename to _request or _ for clarity.

8. Double-quote conversion is fine — consistent with Black. The trailing comma added to tags=[...], is also Black-normalization, no issue.

🟢 Optimization Suggestions

9. Extract the repeated permission list into a constant/helper
The same 3-permission tuple is repeated in all 5 endpoints. E.g.:

TAG_PERMISSIONS = (
    PermissionConstants.KNOWLEDGE_TAG_*.get_workspace_knowledge_permission(),
    ...
)

or a custom @tag_permissions(operation) decorator. This prevents drift (as happened here — one removal missing one endpoint would be a hidden bug).

10. Extract the repeated logging helper

def _get_tag_operation_object(r, keywords):
    return get_knowledge_operation_object(keywords.get("knowledge_id"))

and use get_operation_object=_get_tag_operation_object in all 5 @log decorators.

11. Extract the repeated OpenAPI tag

TAG_OPENAPI_TAG = [_("Knowledge Base/Tag")]

avoids 5 duplicated _() calls and guarantees consistency.

12. TagSerializers.*(data={...}) repetition — the {"workspace_id": ..., "knowledge_id": ...} dict is repeated 4 times. A small helper (_base_tag_data(workspace_id, knowledge_id, **extra)) would reduce duplication.

✅ Summary

Severity Item
🔴 High Permission behavior change from removing ViewPermission; confirm intentional + covered by tests; check for leftover references to removed imports
🟠 Medium GET audit log says "Create"; GET/BatchDelete use wrong API schemas; name filter None handling
🟡 Low Operation string consistency; unused lambda arg
🟢 Suggestion Factor out repeated permissions, log object, OpenAPI tag, and data dicts

Most of the diff is harmless reformatting (Black-style quotes/commas). The only functionally meaningful change is the permission removal, which deserves explicit review and test coverage.

),
)
@log(
menu="Knowledge Base",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No syntax irregularities are visible in the shown diff. However, this is not a pure refactor: it changes authorization behavior.

Key findings

  1. Security/authorization behavior changed

    • Multiple @has_permissions(...) decorators and one check_batch_permissions(...) call no longer include:
      ViewPermission(
          [RoleConstants.USER.get_workspace_role()],
          [PermissionConstants.KNOWLEDGE.get_workspace_knowledge_permission()],
          compare=CompareConstants.AND,
      )
    • This may broaden or narrow access depending on how has_permissions and check_batch_permissions combine arguments. In particular, the removed condition was the only one requiring the base KNOWLEDGE permission together with the USER workspace role.
    • Verify that normal users who previously qualified only through this ViewPermission still have access through another permission.
  2. Affected endpoints are numerous

    • The change touches delete, batch delete, sync, hit test, embedding, tokenize, export, export ZIP, export knowledge, generate related, and transform workflow APIs.
    • Ensure this is intentional for all endpoints. If only some endpoints should change, the current patch is inconsistent.
  3. Batch permission check also changed

    • The check_batch_permissions(...) tuple no longer contains the ViewPermission. Confirm its semantics: if it requires any permission in the tuple, removing an item narrows access; if it requires all, it broadens access.
  4. Import cleanup is mostly correct but not fully tidy

    • Removing CompareConstants and ViewPermission imports is correct only if no remaining references exist in the full file.
    • Combine duplicate imports for cleanliness:
      from knowledge.models import Knowledge, KnowledgeScope
      from knowledge.serializers.knowledge import (
          KnowledgeSerializer,
          KnowledgeBatchOperateSerializer,
          preserve_knowledge_metadata,
      )
    • from common import result was moved, but import ordering is still slightly non-standard. This is cosmetic.
  5. No obvious unused imports after the shown diff

    • RoleConstants is still needed for WORKSPACE_MANAGE.
    • PermissionConstants is still used.
    • QuerySet, Knowledge, and preserve_knowledge_metadata appear to remain in use.

Recommendations

  • Treat this as a permission-model change, not a refactor.
  • Add or update authorization tests for each affected endpoint covering:
    • USER role with KNOWLEDGE permission,
    • USER role without KNOWLEDGE permission,
    • operation-specific permission only,
    • workspace-manage role,
    • no permission.
  • Confirm whether the removed ViewPermission was redundant. If it was redundant, document why in the PR/commit message.
  • Centralize repeated permission lists into a shared constant or helper to avoid future drift across knowledge APIs.
  • Run grep/IDE search for remaining ViewPermission and CompareConstants references in the full file before keeping the import removals.
  • Combine the duplicate model/serializer imports as noted above.

Overall: the patch is syntactically plausible, but it is a high-risk authorization change and needs explicit verification and tests before merge.

@shaohuzhang1
shaohuzhang1 merged commit d1d6795 into v3 Nov 17, 2026
3 of 4 checks passed
@shaohuzhang1
shaohuzhang1 deleted the pr@v3@fix_permission branch November 17, 2026 06:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant