mattermost/server/channels/app/authorization.go
Miguel de la Cruz 48f2fd0873
Merge the Integrated Boards MVP feature branch (#35796)
* Add CreatedBy and UpdatedBy to the properties fields and values (#34485)

* Add CreatedBy and UpdatedBy to the properties fields and values

* Fix types

---------

Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es>

* Adds ObjectType to the property fields table (#34908)

Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es>

* Update ObjectType migration setting an empty value and marking the column as not null (#34915)

Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es>

* Adds uniqueness mechanisms to the property fields (#35058)

* Adds uniqueness mechanisms to the property fields

After adding ObjectType, this commit ensures that both the PSAv1 and
PSAv2 schemas are supported, and enforces property uniqueness through
both database indexes and a logical check when creating new property
fields.

* Adds uniqueness check to property updates

Updates are covered on this commit and we refactor as well the SQL
code to use the squirrel builder and work better with the conditional
addition of the `existingID` piece of the query.

* Add translations to error messages

* Fixing retrylayer mocks

* Remove retrylayer duplication

* Address review comments

* Fix comment to avoid linter issues

* Address PR comments

* Update server/channels/db/migrations/postgres/000157_add_object_type_to_property_fields.down.sql

Co-authored-by: Alejandro García Montoro <alejandro.garciamontoro@gmail.com>

* Update server/channels/db/migrations/postgres/000157_add_object_type_to_property_fields.up.sql

Co-authored-by: Alejandro García Montoro <alejandro.garciamontoro@gmail.com>

* Update server/channels/db/migrations/postgres/000157_add_object_type_to_property_fields.up.sql

Co-authored-by: Alejandro García Montoro <alejandro.garciamontoro@gmail.com>

* Update field validation to check only for valid target types

* Update migrations to avoid concurrent index creation within a transaction

* Update migrations to make all index ops concurrent

* Update tests to use valid PSAv2 property fields

* Adds a helper for valid PSAv2 TargetTypes

---------

Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es>
Co-authored-by: Alejandro García Montoro <alejandro.garciamontoro@gmail.com>

* Fix property tests (#35388)

Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es>

* Adds Integrated Boards feature flag (#35378)

Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es>

* Adds Integrated Boards MVP API changes (#34822)

This PR includes the necessary changes for channels and posts
endpoints and adds a set of generic endpoints to retrieve and manage
property fields and values following the new Property System approach.

Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es>
Co-authored-by: Mattermost Build <build@mattermost.com>

* Property System Architecture permissions for v2 (#35113)

* Adds uniqueness mechanisms to the property fields

After adding ObjectType, this commit ensures that both the PSAv1 and
PSAv2 schemas are supported, and enforces property uniqueness through
both database indexes and a logical check when creating new property
fields.

* Adds uniqueness check to property updates

Updates are covered on this commit and we refactor as well the SQL
code to use the squirrel builder and work better with the conditional
addition of the `existingID` piece of the query.

* Add translations to error messages

* Add the permissions to the migrations, model and update the store calls

* Adds the property field and property group app layer

* Adds authorization helpers for property fields and values

* Make sure that users cannot lock themselves out of property fields

* Migrate permissions from a JSON column to three normalized columns

* Remove the audit comment

* Use target level constants in authorization

* Log authorization membership failures

* Rename admin to sysadmin

* Fix i18n sorting

---------

Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es>

* Add Views store and app layer (#35361)

* Add Views store and app layer for Integrated Boards

Implements the View entity (model, SQL store, service, app) as described
in the Integrated Boards tech spec. Views are channel-scoped board
configurations with typed props (board, kanban subviews) and soft-delete.

- public/model: View, ViewBoardProps, Subview, ViewPatch types with
  PreSave/PreUpdate/IsValid/Patch/Clone/Auditable
- Migration 158: Views table with jsonb Props column and indexes
- SqlViewStore: CRUD with nil-safe Props marshaling (AppendBinaryFlag)
- ViewService: CreateView seeds default kanban subview and links the
  boards property field; caches boardPropertyFieldID at startup
- App layer: CreateView/GetView/GetViewsForChannel/UpdateView/DeleteView
  with channel-membership permission checks and WebSocket events
  (view_created, view_updated, view_deleted)
- doSetupBoardsPropertyField: registers the Boards property group and
  board field in NewServer() before ViewService construction
- GetFieldByName now returns store.ErrNotFound instead of raw sql.ErrNoRows

* Move permission checks out of App layer for views

- Remove HasPermissionToChannel calls from all App view methods
- Drop userID params from GetView, GetViewsForChannel, UpdateView, DeleteView
- Fix doSetupBoardsPropertyField to include required TargetType for PSAv2 field

* Make View service generic and enforce board validation in model

- Remove board-specific auto-setup from service and server startup
- Enforce that board views require Props, at least one subview, and at least one linked property in IsValid()
- Move default subview seeding out of app layer; callers must provide valid props
- Call PreSave on subviews during PreUpdate to assign IDs to new subviews
- Update all tests to reflect the new validation requirements

* Restore migrations files to match base branch

* Distinguish ErrNotFound from other errors in view store Get

* Use CONCURRENTLY and nontransactional for index operations in views migration

* Split views index creation into separate nontransactional migrations

* Update migrations.list

* Update i18n translations for views

* Fix makeView helper to include required Props for board view validation

* Rename ctx parameter from c to rctx in OAuthProvider mock

* Remove views service layer, call store directly from app

* Return 500 for unexpected DB errors in GetView, 404 only for not-found

* Harden View model: deep-copy Props, validate linked property IDs

- Add ViewBoardProps.Clone() to deep-copy LinkedProperties and Subviews
- Use it in View.Clone() and View.Patch() to prevent shared-slice aliasing
- Iterate over LinkedProperties in View.IsValid() and reject invalid IDs
  with a dedicated i18n key
- Register ViewStore in storetest AssertExpectations so mock expectations
  are enforced
- Add tests covering all new behaviours

* Restore autotranslation worker_stopped i18n translation

* Fix view store test IDs and improve error handling in app layer

- Use model.NewId() for linked property IDs in testUpdateView to fix
  validation failure (IsValid rejects non-UUID strings)
- Fix import grouping in app/view.go (stdlib imports in one block)
- Return 404 instead of 500 when Update/Delete store calls return
  ErrNotFound (e.g. concurrent deletion TOCTOU race)

* Add View store mock to retrylayer test genStore helper

The View store was added to the store interface but the genStore()
helper in retrylayer_test.go was not updated, causing TestRetry to panic.
Also removes the duplicate Recap mock registration.

* Refactor view deletion and websocket event handling; update SQL store methods to use query builder

* revert property field store

* Remove useless migrations

* Add cursor-based pagination to View store GetForChannel

- Add ViewQueryCursor and ViewQueryOpts types with validation
- Return (views, cursor, error) for caller-driven pagination
- PerPage clamping: <=0 defaults to 20, >200 clamps to 200
- Support IncludeDeleted filter
- Add comprehensive store tests for pagination, cursor edge cases,
  PerPage clamping, and invalid input rejection
- Add app layer test for empty channelID → 400
- Update interface, retrylayer, timerlayer, and mock signatures

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Refactor test loops in ViewStore tests for improved readability

* change pagination to limit/offset

* Add upper-bound limits on View Subviews and LinkedProperties

Defense-in-depth validation: cap Subviews at 50 and LinkedProperties
at 500 to prevent abuse below the 300KB payload limit.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* MM-67388, MM-66528, MM-67750: Add View REST API endpoints, websocket events, and sort order (#35442)

* Add Views store and app layer for Integrated Boards

Implements the View entity (model, SQL store, service, app) as described
in the Integrated Boards tech spec. Views are channel-scoped board
configurations with typed props (board, kanban subviews) and soft-delete.

- public/model: View, ViewBoardProps, Subview, ViewPatch types with
  PreSave/PreUpdate/IsValid/Patch/Clone/Auditable
- Migration 158: Views table with jsonb Props column and indexes
- SqlViewStore: CRUD with nil-safe Props marshaling (AppendBinaryFlag)
- ViewService: CreateView seeds default kanban subview and links the
  boards property field; caches boardPropertyFieldID at startup
- App layer: CreateView/GetView/GetViewsForChannel/UpdateView/DeleteView
  with channel-membership permission checks and WebSocket events
  (view_created, view_updated, view_deleted)
- doSetupBoardsPropertyField: registers the Boards property group and
  board field in NewServer() before ViewService construction
- GetFieldByName now returns store.ErrNotFound instead of raw sql.ErrNoRows

* Move permission checks out of App layer for views

- Remove HasPermissionToChannel calls from all App view methods
- Drop userID params from GetView, GetViewsForChannel, UpdateView, DeleteView
- Fix doSetupBoardsPropertyField to include required TargetType for PSAv2 field

* Make View service generic and enforce board validation in model

- Remove board-specific auto-setup from service and server startup
- Enforce that board views require Props, at least one subview, and at least one linked property in IsValid()
- Move default subview seeding out of app layer; callers must provide valid props
- Call PreSave on subviews during PreUpdate to assign IDs to new subviews
- Update all tests to reflect the new validation requirements

* Restore migrations files to match base branch

* Distinguish ErrNotFound from other errors in view store Get

* Use CONCURRENTLY and nontransactional for index operations in views migration

* Split views index creation into separate nontransactional migrations

* Update migrations.list

* Update i18n translations for views

* Fix makeView helper to include required Props for board view validation

* Rename ctx parameter from c to rctx in OAuthProvider mock

* Remove views service layer, call store directly from app

* Return 500 for unexpected DB errors in GetView, 404 only for not-found

* Harden View model: deep-copy Props, validate linked property IDs

- Add ViewBoardProps.Clone() to deep-copy LinkedProperties and Subviews
- Use it in View.Clone() and View.Patch() to prevent shared-slice aliasing
- Iterate over LinkedProperties in View.IsValid() and reject invalid IDs
  with a dedicated i18n key
- Register ViewStore in storetest AssertExpectations so mock expectations
  are enforced
- Add tests covering all new behaviours

* Restore autotranslation worker_stopped i18n translation

* Fix view store test IDs and improve error handling in app layer

- Use model.NewId() for linked property IDs in testUpdateView to fix
  validation failure (IsValid rejects non-UUID strings)
- Fix import grouping in app/view.go (stdlib imports in one block)
- Return 404 instead of 500 when Update/Delete store calls return
  ErrNotFound (e.g. concurrent deletion TOCTOU race)

* Add View store mock to retrylayer test genStore helper

The View store was added to the store interface but the genStore()
helper in retrylayer_test.go was not updated, causing TestRetry to panic.
Also removes the duplicate Recap mock registration.

* Refactor view deletion and websocket event handling; update SQL store methods to use query builder

* revert property field store

* Add View API endpoints with OpenAPI spec, client methods, and i18n

Implement REST API for channel views (board-type) behind the
IntegratedBoards feature flag. Adds CRUD endpoints under
/api/v4/channels/{channel_id}/views with permission checks
matching the channel bookmark pattern.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove useless migrations

* Add cursor-based pagination to View store GetForChannel

- Add ViewQueryCursor and ViewQueryOpts types with validation
- Return (views, cursor, error) for caller-driven pagination
- PerPage clamping: <=0 defaults to 20, >200 clamps to 200
- Support IncludeDeleted filter
- Add comprehensive store tests for pagination, cursor edge cases,
  PerPage clamping, and invalid input rejection
- Add app layer test for empty channelID → 400
- Update interface, retrylayer, timerlayer, and mock signatures

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add cursor-based pagination to View API for channel views

* Enhance cursor handling in getViewsForChannel and update tests for pagination

* Refactor test loops in ViewStore tests for improved readability

* Refactor loop in TestGetViewsForChannel for improved readability

* change pagination to limit/offset

* switch to limit/offset pagination

* Add upper-bound limits on View Subviews and LinkedProperties

Defense-in-depth validation: cap Subviews at 50 and LinkedProperties
at 500 to prevent abuse below the 300KB payload limit.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add view sort order API endpoint

Add POST /api/v4/channels/{channel_id}/views/{view_id}/sort_order
endpoint following the channel bookmarks reorder pattern. Includes
store, app, and API layers with full test coverage at each layer.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add connectionId to view WebSocket events and sort_order API spec

Thread connectionId from request header through all view handlers
(create, update, delete, sort_order) to WebSocket events, matching
the channel bookmarks pattern. Add sort_order endpoint to OpenAPI
spec. Update minimum server version to 11.6.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove duplicate View/ViewPatch definitions from definitions.yaml

The merge from integrated-boards-mvp introduced duplicate View and
ViewPatch schema definitions that were already defined earlier in
the file with more detail (including ViewBoardProps ref and enums).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Update minimum server version to 11.6 in views API spec

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add missing translations for view sort order error messages

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Merge integrated-boards-mvp into ibmvp_api-views; remove spec files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix flaky TestViewStore timestamp test on CI

Add sleep before UpdateSortOrder to ensure timestamps differ,
preventing same-millisecond comparisons on fast CI machines.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* remove duplicate views.yaml imclude

* Use c.boolString() for include_deleted query param in GetViewsForChannel

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix views.yaml sort order schema: use integer type and require body

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Refactor view sort order tests to use named IDs instead of array indices

Extract idA/idB/idC from views slice and add BEFORE/AFTER comments
to make stateful subtest ordering easier to follow.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Return 404 instead of 403 for view operations on deleted channels

Deleted channels should appear non-existent to callers rather than
revealing their existence via a 403. Detailed error text explains
the context for debugging.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add missing channel deleteat checks

* Use c.Params.Page instead of manual page query param parsing in getViewsForChannel

c.Params already validates and defaults page/per_page, so the manual
parsing was redundant.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add support for total count in views retrieval

* Add tests for handling deleted views in GetViewsForChannel and GetView

* Short-circuit negative newIndex in UpdateSortOrder before opening transaction

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add per-channel limit on views to bound UpdateSortOrder cost

Without a cap, unbounded view creation makes sort-order updates
increasingly expensive (CASE WHEN per view, row locks). Adds
MaxViewsPerChannel=50 constant and enforces it in the app layer
before saving. Includes API and app layer tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove include_deleted support from views API

Soft-deleted views are structural metadata with low risk, but no other
similar endpoint (e.g. channel bookmarks) exposes deleted records without
an admin gate. Rather than adding an admin-only permission check for
consistency, remove the feature entirely since there is no current use case.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Update view permissions to require `create_post` instead of channel management permissions

* Remove obsolete view management error messages for direct and group messages

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* feat(migrations): add user tracking and object type to property fields

- Introduced user tracking columns (CreatedBy, UpdatedBy) to PropertyFields and PropertyValues.
- Added ObjectType column to PropertyFields with associated unique indexes for legacy and typed properties.
- Created new migration scripts for adding and dropping these features, including necessary indexes for data integrity.
- Established views for managing property fields with new attributes.

This update enhances the schema to support better tracking and categorization of property fields.

* Add Property System Architecture v2 API endpoints (#35583)

* Adds uniqueness mechanisms to the property fields

After adding ObjectType, this commit ensures that both the PSAv1 and
PSAv2 schemas are supported, and enforces property uniqueness through
both database indexes and a logical check when creating new property
fields.

* Adds uniqueness check to property updates

Updates are covered on this commit and we refactor as well the SQL
code to use the squirrel builder and work better with the conditional
addition of the `existingID` piece of the query.

* Add translations to error messages

* Add the permissions to the migrations, model and update the store calls

* Adds the property field and property group app layer

* Adds authorization helpers for property fields and values

* Make sure that users cannot lock themselves out of property fields

* Migrate permissions from a JSON column to three normalized columns

* Remove the audit comment

* Use target level constants in authorization

* Log authorization membership failures

* Rename admin to sysadmin

* Adds the Property System Architecture v2 API endpoints

* Adds permission checks to the create field endpoint

* Add target access checks to value endpoints

* Add default branches for object_type and target_type and extra guards for cursor client4 methods

* Fix vet API mismatch

* Fix error checks

* Fix linter

* Add merge semantics for property patch logic and API endpoint

* Fix i18n

* Fix duplicated patch elements and early return on bad cursor

* Update docs to use enums

* Fix i18n sorting

* Update app layer to return model.AppError

* Adds a limit to the number of property values that can be patched in the same request

* Require target_type filter when searching property fields

* Add objectType validation as part of field.IsValid()

* Fix linter

* Fix test with bad objecttpye

* Fix test grouping

---------

Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es>

* MM-67968: Flatten view model — remove icon, subviews, typed board props (#35726)

* feat(views): flatten view model by removing icon, subview, and board props

Simplifies the View data model as part of MM-67968: removes Icon, Subview,
and ViewBoardProps types; renames ViewTypeBoard to ViewTypeKanban; replaces
typed Props with StringInterface (map[string]any); adds migration 000167
to drop the Icon column from the Views table.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>

* feat(api): update views OpenAPI spec to reflect flattened model

Removes ViewBoardProps, Subview, and icon from the View and ViewPatch
schemas. Changes type enum from board to kanban. Replaces typed props
with a free-form StringInterface object. Aligns with MM-67968.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>

* refactor(views): simplify store by dropping dbView and marshalViewProps

StringInterface already implements driver.Valuer and sql.Scanner, so the
manual JSON marshal/unmarshal and the dbView intermediate struct were
redundant. model.View now scans directly from the database. Also removes
the dead ViewMaxLinkedProperties constant and wraps the Commit() error in
UpdateSortOrder.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>

* fix(api): allow arbitrary JSON in view props OpenAPI schema

The props field was restricted to string values via
additionalProperties: { type: string }, conflicting with the Go model's
StringInterface (map[string]any). Changed to additionalProperties: true
in View, ViewPatch, and inline POST schemas.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>

* Adds basic implementation of the generic redux store for PSAv2 (#35512)

* Adds basic implementation of the generic redux store for PSAv2

* Add created_by and updated_by to the test fixtures

* Make target_id, target_type and object_type mandatory

* Wrap getPropertyFieldsByIds and getPropertyValuesForTargetByFieldIds with createSelector

* Address PR comments

---------

Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es>

* Adds websocket messages for the PSAv2 API events (#35696)

* Adds uniqueness mechanisms to the property fields

After adding ObjectType, this commit ensures that both the PSAv1 and
PSAv2 schemas are supported, and enforces property uniqueness through
both database indexes and a logical check when creating new property
fields.

* Adds uniqueness check to property updates

Updates are covered on this commit and we refactor as well the SQL
code to use the squirrel builder and work better with the conditional
addition of the `existingID` piece of the query.

* Add translations to error messages

* Add the permissions to the migrations, model and update the store calls

* Adds the property field and property group app layer

* Adds authorization helpers for property fields and values

* Make sure that users cannot lock themselves out of property fields

* Migrate permissions from a JSON column to three normalized columns

* Remove the audit comment

* Use target level constants in authorization

* Log authorization membership failures

* Rename admin to sysadmin

* Adds the Property System Architecture v2 API endpoints

* Adds permission checks to the create field endpoint

* Add target access checks to value endpoints

* Add default branches for object_type and target_type and extra guards for cursor client4 methods

* Fix vet API mismatch

* Fix error checks

* Fix linter

* Add merge semantics for property patch logic and API endpoint

* Fix i18n

* Fix duplicated patch elements and early return on bad cursor

* Update docs to use enums

* Fix i18n sorting

* Update app layer to return model.AppError

* Adds a limit to the number of property values that can be patched in the same request

* Adds websocket messages for the PSAv2 API events

* Add IsPSAv2 helper to the property field for clarity

* Add guard against nil returns on field deletion

* Add docs to the websocket endpoints

---------

Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es>

* migrations: consolidate views migrations and reorder after master

- Merged 000165 (create Views) with 000167 (drop Icon) since Icon was never needed
- Renumbered branch migrations 159-166 → 160-167 so master's 000159 (deduplicate_policy_names) runs first
- Regenerated migrations.list

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Add API endpoint to retrieve posts for a specific view (#35604)

Automatic Merge

* Apply fixes after merge

* Return a more specific error from getting multiple fields

* Prevent getting broadcast params on field deletion if not needed

* Remove duplicated migration code

* Update property conflict code to always use master

* Adds nil guard when iterating on property fields

* Check that permission level is valid before getting rejected by the database

* Validate correctness on TargetID for PSAv2 fields

* Avoid PSAv1 using permissions or protected

* Fix test data after validation change

* Fix flaky search test

* Adds more posts for filter use cases to properly test exclusions

---------

Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es>
Co-authored-by: Alejandro García Montoro <alejandro.garciamontoro@gmail.com>
Co-authored-by: Julien Tant <julien@craftyx.fr>
Co-authored-by: Mattermost Build <build@mattermost.com>
Co-authored-by: Julien Tant <785518+JulienTant@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 10:36:35 +01:00

626 lines
21 KiB
Go

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package app
import (
"database/sql"
"errors"
"net/http"
"slices"
"strings"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
)
func (a *App) SessionHasPermissionTo(session model.Session, permission *model.Permission) bool {
if session.IsUnrestricted() {
return true
}
return a.RolesGrantPermission(session.GetUserRoles(), permission.Id)
}
// SessionHasPermissionToAndNotRestrictedAdmin is a variant of [App.SessionHasPermissionTo] that
// denies access to restricted system admins. Note that a local session is always unrestricted.
func (a *App) SessionHasPermissionToAndNotRestrictedAdmin(session model.Session, permission *model.Permission) bool {
if session.IsUnrestricted() {
return true
}
if *a.Config().ExperimentalSettings.RestrictSystemAdmin {
return false
}
return a.RolesGrantPermission(session.GetUserRoles(), permission.Id)
}
func (a *App) SessionHasPermissionToAny(session model.Session, permissions []*model.Permission) bool {
for _, perm := range permissions {
if a.SessionHasPermissionTo(session, perm) {
return true
}
}
return false
}
func (a *App) SessionHasPermissionToTeam(session model.Session, teamID string, permission *model.Permission) bool {
if teamID == "" {
return false
}
if session.IsUnrestricted() {
return true
}
teamMember := session.GetTeamByTeamId(teamID)
if teamMember != nil {
if a.RolesGrantPermission(teamMember.GetRoles(), permission.Id) {
return true
}
}
return a.RolesGrantPermission(session.GetUserRoles(), permission.Id)
}
// SessionHasPermissionToTeams returns true only if user has access to all teams.
func (a *App) SessionHasPermissionToTeams(rctx request.CTX, session model.Session, teamIDs []string, permission *model.Permission) bool {
if len(teamIDs) == 0 {
return true
}
if slices.Contains(teamIDs, "") {
return false
}
// Check session permission, if it allows access, no need to check teams.
if a.SessionHasPermissionTo(session, permission) {
return true
}
for _, teamID := range teamIDs {
tm := session.GetTeamByTeamId(teamID)
if tm != nil {
// If a team member has permission, then no need to check further.
if a.RolesGrantPermission(tm.GetRoles(), permission.Id) {
continue
}
}
return false
}
return true
}
// SessionHasPermissionToChannel checks if the session has permission to the given channel.
//
// Returns:
//
// (hasPermission, isMember)
//
// hasPermission: true if the user has the specified permission for the channel, otherwise false.
// isMember: used for auditing access without membership. True if the user is a member of the channel, otherwise false.
func (a *App) SessionHasPermissionToChannel(rctx request.CTX, session model.Session, channelID string, permission *model.Permission) (hasPermission bool, isMember bool) {
if channelID == "" {
return false, false
}
channel, appErr := a.GetChannel(rctx, channelID)
if appErr != nil && appErr.StatusCode == http.StatusNotFound {
return false, false
} else if appErr != nil {
rctx.Logger().Warn("Failed to get channel", mlog.String("channel_id", channelID), mlog.Err(appErr))
return false, false
}
if session.IsUnrestricted() {
return true, false
}
isMember = false
ids, err := a.Srv().Store().Channel().GetAllChannelMembersForUser(rctx, session.UserId, true, true)
var channelRoles []string
if err == nil {
if roles, ok := ids[channelID]; ok {
isMember = true
channelRoles = strings.Fields(roles)
if a.RolesGrantPermission(channelRoles, permission.Id) {
return true, isMember
}
}
}
if a.RolesGrantPermission(session.GetUserRoles(), model.PermissionManageSystem.Id) {
return true, isMember
}
if channel.TeamId != "" {
return a.SessionHasPermissionToTeam(session, channel.TeamId, permission), isMember
}
return a.SessionHasPermissionTo(session, permission), isMember
}
// SessionHasPermissionToChannels returns true only if user has access to all channels.
func (a *App) SessionHasPermissionToChannels(rctx request.CTX, session model.Session, channelIDs []string, permission *model.Permission) bool {
if len(channelIDs) == 0 {
return true
}
if session.IsUnrestricted() || a.RolesGrantPermission(session.GetUserRoles(), model.PermissionManageSystem.Id) {
return true
}
// make sure all channels exist, otherwise return false.
for _, channelID := range channelIDs {
if channelID == "" {
return false
}
_, appErr := a.GetChannel(rctx, channelID)
if appErr != nil {
return false
}
}
// if System Roles (i.e. Admin, TeamAdmin) allow permissions
// if so, no reason to check team
if a.SessionHasPermissionTo(session, permission) {
return true
}
ids, err := a.Srv().Store().Channel().GetAllChannelMembersForUser(rctx, session.UserId, true, true)
var channelRoles []string
for _, channelID := range channelIDs {
if err == nil {
// If a channel member has permission, then no need to check further.
if roles, ok := ids[channelID]; ok {
channelRoles = strings.Fields(roles)
if a.RolesGrantPermission(channelRoles, permission.Id) {
continue
}
}
}
return false
}
return true
}
func (a *App) SessionHasPermissionToGroup(session model.Session, groupID string, permission *model.Permission) bool {
groupMember, err := a.Srv().Store().Group().GetMember(groupID, session.UserId)
// don't reject immediately on ErrNoRows error because there's further authz logic below for non-groupmembers
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return false
}
// each member of a group is implicitly considered to have the 'custom_group_user' role in that group, so if the user is a member of the
// group and custom_group_user on their system has the requested permission then return true
if groupMember != nil && a.RolesGrantPermission([]string{model.CustomGroupUserRoleId}, permission.Id) {
return true
}
// Not implemented: group-override schemes.
// ...otherwise check their system roles to see if they have the requested permission system-wide
return a.SessionHasPermissionTo(session, permission)
}
func (a *App) SessionHasPermissionToChannelByPost(session model.Session, postID string, permission *model.Permission) bool {
if postID == "" {
return false
}
if channelMember, err := a.Srv().Store().Channel().GetMemberForPost(postID, session.UserId); err == nil {
if a.RolesGrantPermission(channelMember.GetRoles(), permission.Id) {
return true
}
}
if channel, err := a.Srv().Store().Channel().GetForPost(postID); err == nil {
if channel.TeamId != "" {
return a.SessionHasPermissionToTeam(session, channel.TeamId, permission)
}
}
return a.SessionHasPermissionTo(session, permission)
}
func (a *App) SessionHasPermissionToReadPost(rctx request.CTX, session model.Session, postID string) (hasPErmission bool, isMember bool) {
if postID == "" {
return false, false
}
channel, err := a.Srv().Store().Channel().GetForPost(postID)
if err != nil {
// Original implementation (SessionHasPermissionToChannelByPost) still checks for
// general permissions even if the channel is not found, and some tests rely on this behavior.
return a.SessionHasPermissionTo(session, model.PermissionReadChannelContent), false
}
return a.SessionHasPermissionToReadChannel(rctx, session, channel)
}
func (a *App) SessionHasPermissionToCategory(rctx request.CTX, session model.Session, userID, teamID, categoryId string) bool {
if a.SessionHasPermissionTo(session, model.PermissionEditOtherUsers) {
return true
}
category, err := a.GetSidebarCategory(rctx, categoryId)
return err == nil && category != nil && category.UserId == session.UserId && category.UserId == userID && category.TeamId == teamID
}
func (a *App) SessionHasPermissionToUser(session model.Session, userID string) bool {
if userID == "" {
return false
}
if session.IsUnrestricted() || a.SessionHasPermissionTo(session, model.PermissionManageSystem) {
return true
}
if session.UserId == userID {
return true
}
if !a.SessionHasPermissionTo(session, model.PermissionEditOtherUsers) {
return false
}
user, err := a.GetUser(userID)
if err != nil {
return false
}
if user.IsSystemAdmin() {
return false
}
return true
}
func (a *App) SessionHasPermissionToUserOrBot(rctx request.CTX, session model.Session, userID string) bool {
if session.IsUnrestricted() {
return true
}
err := a.SessionHasPermissionToManageBot(rctx, session, userID)
if err == nil {
return true
}
if err.Id == "store.sql_bot.get.missing.app_error" && err.Where == "SqlBotStore.Get" {
if a.SessionHasPermissionToUser(session, userID) {
return true
}
}
return false
}
func (a *App) HasPermissionTo(askingUserId string, permission *model.Permission) bool {
user, err := a.GetUser(askingUserId)
if err != nil {
return false
}
roles := user.GetRoles()
return a.RolesGrantPermission(roles, permission.Id)
}
func (a *App) HasPermissionToTeam(rctx request.CTX, askingUserId string, teamID string, permission *model.Permission) bool {
if teamID == "" || askingUserId == "" {
return false
}
teamMember, _ := a.GetTeamMember(rctx, teamID, askingUserId)
if teamMember != nil && teamMember.DeleteAt == 0 {
if a.RolesGrantPermission(teamMember.GetRoles(), permission.Id) {
return true
}
}
return a.HasPermissionTo(askingUserId, permission)
}
// HasPermissionToChannel determines if the specified user has the given permission on the provided channel.
//
// Returns:
//
// (hasPermission, isMember)
//
// hasPermission: true if the user has the specified permission for the channel, otherwise false.
// isMember: used for auditing access without membership. True if the user is a member of the channel, otherwise false.
func (a *App) HasPermissionToChannel(rctx request.CTX, askingUserId string, channelID string, permission *model.Permission) (hasPermission bool, isMember bool) {
if channelID == "" || askingUserId == "" {
return false, false
}
isMember = false
// We call GetAllChannelMembersForUser instead of just getting
// a single member from the DB, because it's cache backed
// and this is a very frequent call.
ids, err := a.Srv().Store().Channel().GetAllChannelMembersForUser(rctx, askingUserId, true, true)
var channelRoles []string
if err == nil {
if roles, ok := ids[channelID]; ok {
isMember = true
channelRoles = strings.Fields(roles)
if a.RolesGrantPermission(channelRoles, permission.Id) {
return true, isMember
}
}
}
channel, appErr := a.GetChannel(rctx, channelID)
if appErr == nil && channel.TeamId != "" {
return a.HasPermissionToTeam(rctx, askingUserId, channel.TeamId, permission), isMember
}
return a.HasPermissionTo(askingUserId, permission), isMember
}
func (a *App) HasPermissionToChannelByPost(rctx request.CTX, askingUserId string, postID string, permission *model.Permission) bool {
if channelMember, err := a.Srv().Store().Channel().GetMemberForPost(postID, askingUserId); err == nil {
if a.RolesGrantPermission(channelMember.GetRoles(), permission.Id) {
return true
}
}
if channel, err := a.Srv().Store().Channel().GetForPost(postID); err == nil {
return a.HasPermissionToTeam(rctx, askingUserId, channel.TeamId, permission)
}
return a.HasPermissionTo(askingUserId, permission)
}
func (a *App) HasPermissionToUser(askingUserId string, userID string) bool {
if askingUserId == userID {
return true
}
if a.HasPermissionTo(askingUserId, model.PermissionEditOtherUsers) {
return true
}
return false
}
func (a *App) RolesGrantPermission(roleNames []string, permissionId string) bool {
roles, err := a.GetRolesByNames(roleNames)
if err != nil {
// This should only happen if something is very broken. We can't realistically
// recover the situation, so deny permission and log an error.
mlog.Error("Failed to get roles from database with role names: "+strings.Join(roleNames, ",")+" ", mlog.Err(err))
return false
}
for _, role := range roles {
if role.DeleteAt != 0 {
continue
}
permissions := role.Permissions
if slices.Contains(permissions, permissionId) {
return true
}
}
return false
}
// SessionHasPermissionToManageBot returns nil if the session has access to manage the given bot.
// This function deviates from other authorization checks in returning an error instead of just
// a boolean, allowing the permission failure to be exposed with more granularity.
func (a *App) SessionHasPermissionToManageBot(rctx request.CTX, session model.Session, botUserId string) *model.AppError {
existingBot, err := a.GetBot(rctx, botUserId, true)
if err != nil {
return err
}
if session.IsUnrestricted() {
return nil
}
if existingBot.OwnerId == session.UserId {
if !a.SessionHasPermissionTo(session, model.PermissionManageBots) {
if !a.SessionHasPermissionTo(session, model.PermissionReadBots) {
// If the user doesn't have permission to read bots, pretend as if
// the bot doesn't exist at all.
return model.MakeBotNotFoundError("permissions", botUserId)
}
return model.MakePermissionError(&session, []*model.Permission{model.PermissionManageBots})
}
} else {
if !a.SessionHasPermissionTo(session, model.PermissionManageOthersBots) {
if !a.SessionHasPermissionTo(session, model.PermissionReadOthersBots) {
// If the user doesn't have permission to read others' bots,
// pretend as if the bot doesn't exist at all.
return model.MakeBotNotFoundError("permissions", botUserId)
}
return model.MakePermissionError(&session, []*model.Permission{model.PermissionManageOthersBots})
}
}
return nil
}
// SessionHasPermissionToReadChannel checks whether the given session has permission
// to read the specified channel.
//
// Returns:
//
// (hasPermission, isMember)
//
// hasPermission: true if the user has permission to read the channel, false otherwise
// isMember: used for auditing access without membership. True if the user is a member of the channel, false otherwise
func (a *App) SessionHasPermissionToReadChannel(rctx request.CTX, session model.Session, channel *model.Channel) (hasPermission bool, isMember bool) {
if session.IsUnrestricted() {
return true, false
}
return a.HasPermissionToReadChannel(rctx, session.UserId, channel)
}
// HasPermissionToReadChannel determines if the specified user has permission to read the given channel.
//
// Returns:
//
// (hasPermission, isMember)
//
// hasPermission: true if the user has permission to read the channel, false otherwise
// isMember: used for auditing access without membership. True if the user is a member of the channel, false otherwise
func (a *App) HasPermissionToReadChannel(rctx request.CTX, userID string, channel *model.Channel) (hasPermission bool, isMember bool) {
if ok, member := a.HasPermissionToChannel(rctx, userID, channel.Id, model.PermissionReadChannelContent); ok {
return true, member
}
if channel.Type == model.ChannelTypeOpen && !*a.Config().ComplianceSettings.Enable {
return a.HasPermissionToTeam(rctx, userID, channel.TeamId, model.PermissionReadPublicChannel), false
}
return false, false
}
func (a *App) HasPermissionToChannelMemberCount(rctx request.CTX, userID string, channel *model.Channel) bool {
if ok, _ := a.HasPermissionToChannel(rctx, userID, channel.Id, model.PermissionReadChannelContent); ok {
return true
}
if channel.Type == model.ChannelTypeOpen {
return a.HasPermissionToTeam(rctx, userID, channel.TeamId, model.PermissionListTeamChannels)
}
return false
}
// SessionHasPermissionToEditPropertyField checks if the session has permission to edit the field definition.
// Returns false if the field is nil, protected, or if PermissionField is nil (legacy fields).
func (a *App) SessionHasPermissionToEditPropertyField(rctx request.CTX, session model.Session, field *model.PropertyField) bool {
if field == nil {
return false
}
if field.Protected {
return false
}
if field.PermissionField == nil {
return false
}
if session.IsUnrestricted() {
return true
}
return a.hasPropertyFieldPermissionLevel(rctx, session.UserId, field, *field.PermissionField)
}
// SessionHasPermissionToSetPropertyFieldValues checks if the session has permission to set values on objects.
// Returns false if the field is nil or if PermissionValues is nil (legacy fields).
func (a *App) SessionHasPermissionToSetPropertyFieldValues(rctx request.CTX, session model.Session, field *model.PropertyField) bool {
if field == nil {
return false
}
if field.PermissionValues == nil {
return false
}
if session.IsUnrestricted() {
return true
}
return a.hasPropertyFieldPermissionLevel(rctx, session.UserId, field, *field.PermissionValues)
}
// SessionHasPermissionToManagePropertyFieldOptions checks if the session has permission to manage field options.
// Returns false if the field is nil or if PermissionOptions is nil (legacy fields).
func (a *App) SessionHasPermissionToManagePropertyFieldOptions(rctx request.CTX, session model.Session, field *model.PropertyField) bool {
if field == nil {
return false
}
if field.PermissionOptions == nil {
return false
}
if session.IsUnrestricted() {
return true
}
return a.hasPropertyFieldPermissionLevel(rctx, session.UserId, field, *field.PermissionOptions)
}
// HasPermissionToEditPropertyField checks if the user has permission to edit the field definition.
// Returns false if the field is nil, protected, userID is empty, or if PermissionField is nil (legacy fields).
func (a *App) HasPermissionToEditPropertyField(rctx request.CTX, userID string, field *model.PropertyField) bool {
if field == nil || userID == "" {
return false
}
if field.Protected {
return false
}
if field.PermissionField == nil {
return false
}
return a.hasPropertyFieldPermissionLevel(rctx, userID, field, *field.PermissionField)
}
// HasPermissionToSetPropertyFieldValues checks if the user has permission to set values on objects.
// Returns false if the field is nil, userID is empty, or if PermissionValues is nil (legacy fields).
func (a *App) HasPermissionToSetPropertyFieldValues(rctx request.CTX, userID string, field *model.PropertyField) bool {
if field == nil || userID == "" {
return false
}
if field.PermissionValues == nil {
return false
}
return a.hasPropertyFieldPermissionLevel(rctx, userID, field, *field.PermissionValues)
}
// HasPermissionToManagePropertyFieldOptions checks if the user has permission to manage field options.
// Returns false if the field is nil, userID is empty, or if PermissionOptions is nil (legacy fields).
func (a *App) HasPermissionToManagePropertyFieldOptions(rctx request.CTX, userID string, field *model.PropertyField) bool {
if field == nil || userID == "" {
return false
}
if field.PermissionOptions == nil {
return false
}
return a.hasPropertyFieldPermissionLevel(rctx, userID, field, *field.PermissionOptions)
}
// hasPropertyFieldPermissionLevel checks if the user has the specified permission level for the field.
func (a *App) hasPropertyFieldPermissionLevel(rctx request.CTX, userID string, field *model.PropertyField, level model.PermissionLevel) bool {
switch level {
case model.PermissionLevelNone:
return false
case model.PermissionLevelSysadmin:
return a.HasPermissionTo(userID, model.PermissionManageSystem)
case model.PermissionLevelMember:
return a.hasPropertyFieldScopeAccess(rctx, userID, field)
}
return false
}
// hasPropertyFieldScopeAccess checks if the user has access to the property field's scope.
// For system-level properties, any authenticated user has access.
// For channel-level properties, the user must be a member of the channel.
func (a *App) hasPropertyFieldScopeAccess(rctx request.CTX, userID string, field *model.PropertyField) bool {
switch field.TargetType {
case string(model.PropertyFieldTargetLevelSystem):
// System-level property: any authenticated user
return true
case string(model.PropertyFieldTargetLevelTeam):
// Team-level property: must be team member
member, err := a.Srv().Store().Team().GetMember(rctx, field.TargetID, userID)
if err != nil {
rctx.Logger().Warn("Failed to get team member for property field scope check",
mlog.String("team_id", field.TargetID),
mlog.String("user_id", userID),
mlog.String("field_id", field.ID),
mlog.Err(err),
)
return false
}
return member != nil
case string(model.PropertyFieldTargetLevelChannel):
// Channel-level property: must be channel member
member, err := a.Srv().Store().Channel().GetMember(rctx, field.TargetID, userID)
if err != nil {
rctx.Logger().Warn("Failed to get channel member for property field scope check",
mlog.String("channel_id", field.TargetID),
mlog.String("user_id", userID),
mlog.String("field_id", field.ID),
mlog.Err(err),
)
return false
}
return member != nil
}
return false
}