Repository navigation
fix: Remove unused permissions from v2 remnants - #7966
Conversation
| paragraph_id: str, | ||
| ): | ||
| return result.success( | ||
| ApplicationChatRecordImproveSerializer.Operate( |
There was a problem hiding this comment.
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.USERplusPermissionConstants.APPLICATIONwithcompare=AND. Depending onhas_permissionssemantics, 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, andOperate.delete. Confirm this is intentional and add/adjust permission tests. -
Removed imports:
ViewPermissionandCompareConstantsimports are removed. This is correct only if there are no remaining references anywhere in the file. Rungrep -n "ViewPermission\|CompareConstants"and the linter to confirm there is noNameError. -
Import ordering: Moving
common.*imports after local serializer imports may violate your project’sisort/lint rules. Runisort/ruff/flake8. Also verify whetherTokenAuthis 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() | ||
| ) |
There was a problem hiding this comment.
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_permissionsuses OR semantics, this silently removes a valid access path → likely a regression. - Verify no other usage of
CompareConstants/ViewPermissionremains in this file (the import removal will raiseNameErrorat 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", |
There was a problem hiding this comment.
No syntax irregularities are visible in the shown diff. However, this is not a pure refactor: it changes authorization behavior.
Key findings
-
Security/authorization behavior changed
- Multiple
@has_permissions(...)decorators and onecheck_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_permissionsandcheck_batch_permissionscombine arguments. In particular, the removed condition was the only one requiring the baseKNOWLEDGEpermission together with theUSERworkspace role. - Verify that normal users who previously qualified only through this
ViewPermissionstill have access through another permission.
- Multiple
-
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.
-
Batch permission check also changed
- The
check_batch_permissions(...)tuple no longer contains theViewPermission. Confirm its semantics: if it requires any permission in the tuple, removing an item narrows access; if it requires all, it broadens access.
- The
-
Import cleanup is mostly correct but not fully tidy
- Removing
CompareConstantsandViewPermissionimports 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 resultwas moved, but import ordering is still slightly non-standard. This is cosmetic.
- Removing
-
No obvious unused imports after the shown diff
RoleConstantsis still needed forWORKSPACE_MANAGE.PermissionConstantsis still used.QuerySet,Knowledge, andpreserve_knowledge_metadataappear 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:
USERrole withKNOWLEDGEpermission,USERrole withoutKNOWLEDGEpermission,- operation-specific permission only,
- workspace-manage role,
- no permission.
- Confirm whether the removed
ViewPermissionwas 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 remainingViewPermissionandCompareConstantsreferences 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.
fix: Remove unused permissions from v2 remnants