Files
team/server/channels/app/custom_profile_attributes_test.go
3e16dc554c 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 <[email protected]>

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

Co-authored-by: Miguel de la Cruz <[email protected]>

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

Co-authored-by: Miguel de la Cruz <[email protected]>

* 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 <[email protected]>

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

Co-authored-by: Alejandro García Montoro <[email protected]>

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

Co-authored-by: Alejandro García Montoro <[email protected]>

* 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 <[email protected]>
Co-authored-by: Alejandro García Montoro <[email protected]>

* Fix property tests (#35388)

Co-authored-by: Miguel de la Cruz <[email protected]>

* Adds Integrated Boards feature flag (#35378)

Co-authored-by: Miguel de la Cruz <[email protected]>

* 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 <[email protected]>
Co-authored-by: Mattermost Build <[email protected]>

* 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 <[email protected]>

* 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

* 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.

---------

* 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.

* 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

* 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.

* 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.

* 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.

* 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).

* Update minimum server version to 11.6 in views API spec

* Add missing translations for view sort order error messages

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

* Fix flaky TestViewStore timestamp test on CI

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

* remove duplicate views.yaml imclude

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

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

* 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.

* 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.

* 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.

* 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

* 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.

* 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.

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

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

---------

* 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 <[email protected]>

* 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.

* 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.

* 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.

* 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.

---------

* 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 <[email protected]>

* 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 <[email protected]>

* 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

* 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 <[email protected]>
Co-authored-by: Alejandro García Montoro <[email protected]>
Co-authored-by: Julien Tant <[email protected]>
Co-authored-by: Mattermost Build <[email protected]>
Co-authored-by: Julien Tant <[email protected]>

Co-authored-by: Hanzo Dev <[email protected]>
2026-03-27 10:36:35 +01:00

1107 lines
37 KiB
Go

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package app
import (
"encoding/json"
"fmt"
"net/http"
"testing"
"time"
"github.com/mattermost/mattermost/server/public/model"
"github.com/stretchr/testify/require"
)
func TestGetCPAField(t *testing.T) {
mainHelper.Parallel(t)
th := Setup(t).InitBasic(t)
cpaID, cErr := th.App.CpaGroupID()
require.Nil(t, cErr)
rctx := th.emptyContextWithCallerID(anonymousCallerId)
t.Run("should fail when getting a non-existent field", func(t *testing.T) {
field, appErr := th.App.GetCPAField(rctx, model.NewId())
require.NotNil(t, appErr)
require.Equal(t, "app.custom_profile_attributes.property_field_not_found.app_error", appErr.Id)
require.Empty(t, field)
})
t.Run("should fail when getting a field from a different group", func(t *testing.T) {
field := &model.PropertyField{
GroupID: model.NewId(),
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
}
createdField, err := th.App.CreatePropertyField(rctx, field, false, "")
require.Nil(t, err)
fetchedField, appErr := th.App.GetCPAField(rctx, createdField.ID)
require.NotNil(t, appErr)
require.Equal(t, "app.custom_profile_attributes.property_field_not_found.app_error", appErr.Id)
require.Empty(t, fetchedField)
})
t.Run("should get an existing CPA field", func(t *testing.T) {
field, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
GroupID: cpaID,
Name: "Test Field",
Type: model.PropertyFieldTypeText,
Attrs: model.StringInterface{model.CustomProfileAttributesPropertyAttrsVisibility: model.CustomProfileAttributesVisibilityHidden},
})
require.NoError(t, err)
createdField, appErr := th.App.CreateCPAField(rctx, field)
require.Nil(t, appErr)
require.NotEmpty(t, createdField.ID)
fetchedField, appErr := th.App.GetCPAField(rctx, createdField.ID)
require.Nil(t, appErr)
require.Equal(t, createdField.ID, fetchedField.ID)
require.Equal(t, "Test Field", fetchedField.Name)
require.Equal(t, model.CustomProfileAttributesVisibilityHidden, fetchedField.Attrs.Visibility)
})
t.Run("should initialize default attrs when field has nil Attrs", func(t *testing.T) {
// Create a field with nil Attrs directly via property service (bypassing CPA validation)
field := &model.PropertyField{
GroupID: cpaID,
Name: "Field with nil attrs",
Type: model.PropertyFieldTypeText,
Attrs: nil,
}
createdField, err := th.App.CreatePropertyField(rctx, field, false, "")
require.Nil(t, err)
// GetCPAField should initialize Attrs with defaults
fetchedField, appErr := th.App.GetCPAField(rctx, createdField.ID)
require.Nil(t, appErr)
require.Equal(t, model.CustomProfileAttributesVisibilityDefault, fetchedField.Attrs.Visibility)
require.Equal(t, float64(0), fetchedField.Attrs.SortOrder)
})
t.Run("should initialize default attrs when field has empty Attrs", func(t *testing.T) {
// Create a field with empty Attrs directly via property service
field := &model.PropertyField{
GroupID: cpaID,
Name: "Field with empty attrs",
Type: model.PropertyFieldTypeText,
Attrs: model.StringInterface{},
}
createdField, err := th.App.CreatePropertyField(rctx, field, false, "")
require.Nil(t, err)
// GetCPAField should add missing default attrs
fetchedField, appErr := th.App.GetCPAField(rctx, createdField.ID)
require.Nil(t, appErr)
require.Equal(t, model.CustomProfileAttributesVisibilityDefault, fetchedField.Attrs.Visibility)
require.Equal(t, float64(0), fetchedField.Attrs.SortOrder)
})
t.Run("should validate LDAP/SAML synced fields", func(t *testing.T) {
// Create LDAP synced field
ldapField, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
GroupID: cpaID,
Name: "LDAP Field",
Type: model.PropertyFieldTypeText,
Attrs: model.StringInterface{
model.CustomProfileAttributesPropertyAttrsLDAP: "ldap_attribute",
},
})
require.NoError(t, err)
createdLDAPField, appErr := th.App.CreateCPAField(rctx, ldapField)
require.Nil(t, appErr)
// Create SAML synced field
samlField, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
GroupID: cpaID,
Name: "SAML Field",
Type: model.PropertyFieldTypeText,
Attrs: model.StringInterface{
model.CustomProfileAttributesPropertyAttrsSAML: "saml_attribute",
},
})
require.NoError(t, err)
createdSAMLField, appErr := th.App.CreateCPAField(rctx, samlField)
require.Nil(t, appErr)
// Test with allowSynced=false
userID := model.NewId()
// Test LDAP field
_, appErr = th.App.PatchCPAValue(rctx, userID, createdLDAPField.ID, json.RawMessage(`"test value"`), false)
require.NotNil(t, appErr)
require.Equal(t, "app.custom_profile_attributes.property_field_is_synced.app_error", appErr.Id)
// Test SAML field
_, appErr = th.App.PatchCPAValue(rctx, userID, createdSAMLField.ID, json.RawMessage(`"test value"`), false)
require.NotNil(t, appErr)
require.Equal(t, "app.custom_profile_attributes.property_field_is_synced.app_error", appErr.Id)
// Test with allowSynced=true
// LDAP field should work
patchedValue, appErr := th.App.PatchCPAValue(rctx, userID, createdLDAPField.ID, json.RawMessage(`"test value"`), true)
require.Nil(t, appErr)
require.NotNil(t, patchedValue)
require.Equal(t, json.RawMessage(`"test value"`), patchedValue.Value)
// SAML field should work
patchedValue, appErr = th.App.PatchCPAValue(rctx, userID, createdSAMLField.ID, json.RawMessage(`"test value"`), true)
require.Nil(t, appErr)
require.NotNil(t, patchedValue)
require.Equal(t, json.RawMessage(`"test value"`), patchedValue.Value)
})
}
func TestListCPAFields(t *testing.T) {
mainHelper.Parallel(t)
th := Setup(t).InitBasic(t)
cpaID, cErr := th.App.CpaGroupID()
require.Nil(t, cErr)
rctx := th.emptyContextWithCallerID(anonymousCallerId)
t.Run("should list the CPA property fields", func(t *testing.T) {
field1 := model.PropertyField{
GroupID: cpaID,
Name: "Field 1",
Type: model.PropertyFieldTypeText,
Attrs: model.StringInterface{model.CustomProfileAttributesPropertyAttrsSortOrder: 1},
}
_, err := th.App.CreatePropertyField(rctx, &field1, false, "")
require.Nil(t, err)
field2 := &model.PropertyField{
GroupID: model.NewId(),
Name: "Field 2",
Type: model.PropertyFieldTypeText,
}
_, err = th.App.CreatePropertyField(rctx, field2, false, "")
require.Nil(t, err)
field3 := model.PropertyField{
GroupID: cpaID,
Name: "Field 3",
Type: model.PropertyFieldTypeText,
Attrs: model.StringInterface{model.CustomProfileAttributesPropertyAttrsSortOrder: 0},
}
_, err = th.App.CreatePropertyField(rctx, &field3, false, "")
require.Nil(t, err)
fields, appErr := th.App.ListCPAFields(rctx)
require.Nil(t, appErr)
require.Len(t, fields, 2)
require.Equal(t, "Field 3", fields[0].Name)
require.Equal(t, "Field 1", fields[1].Name)
})
t.Run("should initialize default attrs for fields with nil or empty Attrs", func(t *testing.T) {
// Create a field with nil Attrs
fieldWithNilAttrs := &model.PropertyField{
GroupID: cpaID,
Name: "Field with nil attrs",
Type: model.PropertyFieldTypeText,
Attrs: nil,
}
_, err := th.App.CreatePropertyField(rctx, fieldWithNilAttrs, false, "")
require.Nil(t, err)
// Create a field with empty Attrs
fieldWithEmptyAttrs := &model.PropertyField{
GroupID: cpaID,
Name: "Field with empty attrs",
Type: model.PropertyFieldTypeText,
Attrs: model.StringInterface{},
}
_, err = th.App.CreatePropertyField(rctx, fieldWithEmptyAttrs, false, "")
require.Nil(t, err)
// ListCPAFields should initialize Attrs with defaults
fields, appErr := th.App.ListCPAFields(rctx)
require.Nil(t, appErr)
require.NotEmpty(t, fields)
// Find our test fields and verify default attrs are set
for _, field := range fields {
if field.Name == "Field with nil attrs" || field.Name == "Field with empty attrs" {
require.Equal(t, model.CustomProfileAttributesVisibilityDefault, field.Attrs.Visibility)
require.Equal(t, float64(0), field.Attrs.SortOrder)
}
}
})
t.Run("list fields should return defaults for fields created without visibility and sort_order", func(t *testing.T) {
// Create a field with minimal attrs (no visibility or sort_order)
fieldMinimal, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
Name: "Field Without Defaults",
Type: model.PropertyFieldTypeText,
Attrs: model.StringInterface{}, // Empty attrs - no visibility or sort_order
})
require.NoError(t, err)
createdFieldMinimal, appErr := th.App.CreateCPAField(rctx, fieldMinimal)
require.Nil(t, appErr)
require.NotNil(t, createdFieldMinimal)
// Create another field to ensure we test list results with explicit values
fieldNormal, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
Name: "Normal Field",
Type: model.PropertyFieldTypeText,
Attrs: model.StringInterface{
model.CustomProfileAttributesPropertyAttrsVisibility: model.CustomProfileAttributesVisibilityAlways,
model.CustomProfileAttributesPropertyAttrsSortOrder: 5.0,
},
})
require.NoError(t, err)
createdFieldNormal, appErr := th.App.CreateCPAField(rctx, fieldNormal)
require.Nil(t, appErr)
require.NotNil(t, createdFieldNormal)
// List all fields
fields, appErr := th.App.ListCPAFields(rctx)
require.Nil(t, appErr)
require.NotEmpty(t, fields)
// Find our test fields and verify defaults
foundMinimal := false
foundNormal := false
for _, f := range fields {
if f.ID == createdFieldMinimal.ID {
foundMinimal = true
// Verify defaults are set for field created without them
require.Equal(t, model.CustomProfileAttributesVisibilityDefault, f.Attrs.Visibility, "visibility should have default value")
require.Equal(t, float64(0), f.Attrs.SortOrder, "sort_order should default to 0")
}
if f.ID == createdFieldNormal.ID {
foundNormal = true
// Verify createdFieldNormal are preserved
require.Equal(t, model.CustomProfileAttributesVisibilityAlways, f.Attrs.Visibility)
require.Equal(t, float64(5), f.Attrs.SortOrder)
}
}
require.True(t, foundMinimal, "should have found createdFieldMinimal in list")
require.True(t, foundNormal, "should have found createdFieldNormal in list")
})
}
func TestCreateCPAField(t *testing.T) {
mainHelper.Parallel(t)
th := Setup(t).InitBasic(t)
cpaID, cErr := th.App.CpaGroupID()
require.Nil(t, cErr)
rctx := th.emptyContextWithCallerID(anonymousCallerId)
t.Run("should fail if the field is not valid", func(t *testing.T) {
field, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{Name: model.NewId()})
require.NoError(t, err)
createdField, err := th.App.CreateCPAField(rctx, field)
require.Error(t, err)
require.Empty(t, createdField)
})
t.Run("should not be able to create a property field for a different feature", func(t *testing.T) {
field, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
GroupID: model.NewId(),
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
})
require.NoError(t, err)
createdField, appErr := th.App.CreateCPAField(rctx, field)
require.Nil(t, appErr)
require.Equal(t, cpaID, createdField.GroupID)
})
t.Run("should correctly create a CPA field", func(t *testing.T) {
field, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
GroupID: cpaID,
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
Attrs: model.StringInterface{model.CustomProfileAttributesPropertyAttrsVisibility: model.CustomProfileAttributesVisibilityHidden},
})
require.NoError(t, err)
createdField, appErr := th.App.CreateCPAField(rctx, field)
require.Nil(t, appErr)
require.NotZero(t, createdField.ID)
require.Equal(t, cpaID, createdField.GroupID)
require.Equal(t, model.CustomProfileAttributesVisibilityHidden, createdField.Attrs.Visibility)
fetchedField, gErr := th.App.GetPropertyField(rctx, "", createdField.ID)
require.Nil(t, gErr)
require.Equal(t, field.Name, fetchedField.Name)
require.NotZero(t, fetchedField.CreateAt)
require.Equal(t, fetchedField.CreateAt, fetchedField.UpdateAt)
})
t.Run("should create CPA field with DeleteAt set to 0 even if input has non-zero DeleteAt", func(t *testing.T) {
// Create a CPAField with DeleteAt != 0
field, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
GroupID: cpaID,
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
Attrs: model.StringInterface{model.CustomProfileAttributesPropertyAttrsVisibility: model.CustomProfileAttributesVisibilityHidden},
})
require.NoError(t, err)
// Set DeleteAt to non-zero value before creation
field.DeleteAt = time.Now().UnixMilli()
require.NotZero(t, field.DeleteAt, "Pre-condition: field should have non-zero DeleteAt")
createdField, appErr := th.App.CreateCPAField(rctx, field)
require.Nil(t, appErr)
require.NotZero(t, createdField.ID)
require.Equal(t, cpaID, createdField.GroupID)
// Verify that DeleteAt has been reset to 0
require.Zero(t, createdField.DeleteAt, "DeleteAt should be 0 after creation")
// Double-check by fetching the field from the database
fetchedField, gErr := th.App.GetPropertyField(rctx, "", createdField.ID)
require.Nil(t, gErr)
require.Zero(t, fetchedField.DeleteAt, "DeleteAt should be 0 in database")
})
t.Run("CPA should honor the field limit", func(t *testing.T) {
th := Setup(t).InitBasic(t)
t.Run("should not be able to create CPA fields above the limit", func(t *testing.T) {
// we create the rest of the fields required to reach the limit
for i := 1; i <= CustomProfileAttributesFieldLimit; i++ {
field, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
})
require.NoError(t, err)
createdField, appErr := th.App.CreateCPAField(rctx, field)
require.Nil(t, appErr)
require.NotZero(t, createdField.ID)
}
// then, we create a last one that would exceed the limit
field := &model.CPAField{
PropertyField: model.PropertyField{
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
},
}
createdField, appErr := th.App.CreateCPAField(rctx, field)
require.NotNil(t, appErr)
require.Equal(t, http.StatusUnprocessableEntity, appErr.StatusCode)
require.Zero(t, createdField)
})
t.Run("deleted fields should not count for the limit", func(t *testing.T) {
// we retrieve the list of fields and check we've reached the limit
fields, appErr := th.App.ListCPAFields(rctx)
require.Nil(t, appErr)
require.Len(t, fields, CustomProfileAttributesFieldLimit)
// then we delete one field
require.Nil(t, th.App.DeleteCPAField(rctx, fields[0].ID))
// creating a new one should work now
field := &model.CPAField{
PropertyField: model.PropertyField{
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
},
}
createdField, appErr := th.App.CreateCPAField(rctx, field)
require.Nil(t, appErr)
require.NotZero(t, createdField.ID)
})
})
}
func TestPatchCPAField(t *testing.T) {
mainHelper.Parallel(t)
th := Setup(t).InitBasic(t)
cpaID, cErr := th.App.CpaGroupID()
require.Nil(t, cErr)
rctx := th.emptyContextWithCallerID(anonymousCallerId)
newField, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
GroupID: cpaID,
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
Attrs: model.StringInterface{model.CustomProfileAttributesPropertyAttrsVisibility: model.CustomProfileAttributesVisibilityHidden},
})
require.NoError(t, err)
createdField, appErr := th.App.CreateCPAField(rctx, newField)
require.Nil(t, appErr)
patch := &model.PropertyFieldPatch{
Name: model.NewPointer("Patched name"),
Attrs: model.NewPointer(model.StringInterface{model.CustomProfileAttributesPropertyAttrsVisibility: model.CustomProfileAttributesVisibilityWhenSet}),
TargetID: model.NewPointer(model.NewId()),
TargetType: model.NewPointer(model.NewId()),
}
t.Run("should fail if the field doesn't exist", func(t *testing.T) {
updatedField, appErr := th.App.PatchCPAField(rctx, model.NewId(), patch)
require.NotNil(t, appErr)
require.Empty(t, updatedField)
})
t.Run("should not allow to patch a field outside of CPA", func(t *testing.T) {
newField := &model.PropertyField{
GroupID: model.NewId(),
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
}
field, err := th.App.CreatePropertyField(rctx, newField, false, "")
require.Nil(t, err)
updatedField, uErr := th.App.PatchCPAField(rctx, field.ID, patch)
require.NotNil(t, uErr)
require.Equal(t, "app.custom_profile_attributes.property_field_not_found.app_error", uErr.Id)
require.Empty(t, updatedField)
})
t.Run("should correctly patch the CPA property field", func(t *testing.T) {
time.Sleep(10 * time.Millisecond) // ensure the UpdateAt is different than CreateAt
updatedField, appErr := th.App.PatchCPAField(rctx, createdField.ID, patch)
require.Nil(t, appErr)
require.Equal(t, createdField.ID, updatedField.ID)
require.Equal(t, "Patched name", updatedField.Name)
require.Equal(t, model.CustomProfileAttributesVisibilityWhenSet, updatedField.Attrs.Visibility)
require.Empty(t, updatedField.TargetID, "CPA should not allow to patch the field's target ID")
require.Empty(t, updatedField.TargetType, "CPA should not allow to patch the field's target type")
require.Greater(t, updatedField.UpdateAt, createdField.UpdateAt)
})
t.Run("should preserve option IDs when patching select field options", func(t *testing.T) {
// Create a select field with options
selectField, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
GroupID: cpaID,
Name: "Select Field",
Type: model.PropertyFieldTypeSelect,
Attrs: map[string]any{
model.PropertyFieldAttributeOptions: []any{
map[string]any{
"name": "Option 1",
"color": "#111111",
},
map[string]any{
"name": "Option 2",
"color": "#222222",
},
},
},
})
require.NoError(t, err)
createdSelectField, appErr := th.App.CreateCPAField(rctx, selectField)
require.Nil(t, appErr)
// Get the original option IDs
options := createdSelectField.Attrs.Options
require.Len(t, options, 2)
originalID1 := options[0].ID
originalID2 := options[1].ID
require.NotEmpty(t, originalID1)
require.NotEmpty(t, originalID2)
// Patch the field with updated option names and colors
selectPatch := &model.PropertyFieldPatch{
Attrs: model.NewPointer(model.StringInterface{
model.PropertyFieldAttributeOptions: []any{
map[string]any{
"id": originalID1,
"name": "Updated Option 1",
"color": "#333333",
},
map[string]any{
"name": "New Option 1.5",
"color": "#353535",
},
map[string]any{
"id": originalID2,
"name": "Updated Option 2",
"color": "#444444",
},
},
}),
}
updatedSelectField, appErr := th.App.PatchCPAField(rctx, createdSelectField.ID, selectPatch)
require.Nil(t, appErr)
updatedOptions := updatedSelectField.Attrs.Options
require.Len(t, updatedOptions, 3)
// Verify the options were updated while preserving IDs
require.Equal(t, originalID1, updatedOptions[0].ID)
require.Equal(t, "Updated Option 1", updatedOptions[0].Name)
require.Equal(t, "#333333", updatedOptions[0].Color)
require.Equal(t, originalID2, updatedOptions[2].ID)
require.Equal(t, "Updated Option 2", updatedOptions[2].Name)
require.Equal(t, "#444444", updatedOptions[2].Color)
// Check the new option
require.Equal(t, "New Option 1.5", updatedOptions[1].Name)
require.Equal(t, "#353535", updatedOptions[1].Color)
})
t.Run("Should not delete the values of a field after patching it if the type has not changed", func(t *testing.T) {
// Create a select field with options
field, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
GroupID: cpaID,
Name: "Select Field with values",
Type: model.PropertyFieldTypeSelect,
Attrs: model.StringInterface{
model.PropertyFieldAttributeOptions: []any{
map[string]any{
"name": "Option 1",
"color": "#FF5733",
},
map[string]any{
"name": "Option 2",
"color": "#33FF57",
},
},
},
})
require.NoError(t, err)
createdField, appErr := th.App.CreateCPAField(rctx, field)
require.Nil(t, appErr)
// Get the option IDs
options := createdField.Attrs.Options
require.Len(t, options, 2)
optionID := options[0].ID
require.NotEmpty(t, optionID)
// Create values for this field using the first option
userID := model.NewId()
value, appErr := th.App.PatchCPAValue(rctx, userID, createdField.ID, json.RawMessage(fmt.Sprintf(`"%s"`, optionID)), false)
require.Nil(t, appErr)
require.NotNil(t, value)
// Patch the field without changing type (just update name and add a new option)
patch := &model.PropertyFieldPatch{
Name: model.NewPointer("Updated select field name"),
Attrs: model.NewPointer(model.StringInterface{
model.PropertyFieldAttributeOptions: []any{
map[string]any{
"id": optionID, // Keep the same ID for the first option
"name": "Updated Option 1",
"color": "#FF5733",
},
map[string]any{
"name": "Option 2",
"color": "#33FF57",
},
map[string]any{
"name": "Option 3",
"color": "#5733FF",
},
},
}),
}
updatedField, appErr := th.App.PatchCPAField(rctx, createdField.ID, patch)
require.Nil(t, appErr)
require.Equal(t, "Updated select field name", updatedField.Name)
require.Equal(t, model.PropertyFieldTypeSelect, updatedField.Type)
// Verify values still exist
values, appErr := th.App.ListCPAValues(rctx, userID)
require.Nil(t, appErr)
require.Len(t, values, 1)
require.Equal(t, json.RawMessage(fmt.Sprintf(`"%s"`, optionID)), values[0].Value)
})
t.Run("Should delete the values of a field after patching it if the type has changed", func(t *testing.T) {
// Create a select field with options
field, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
GroupID: cpaID,
Name: "Select Field with type change",
Type: model.PropertyFieldTypeSelect,
Attrs: model.StringInterface{
model.PropertyFieldAttributeOptions: []any{
map[string]any{
"name": "Option A",
"color": "#FF5733",
},
map[string]any{
"name": "Option B",
"color": "#33FF57",
},
},
},
})
require.NoError(t, err)
createdField, appErr := th.App.CreateCPAField(rctx, field)
require.Nil(t, appErr)
// Get the option IDs
options := createdField.Attrs.Options
require.Len(t, options, 2)
optionID := options[0].ID
require.NotEmpty(t, optionID)
// Create values for this field
userID := model.NewId()
value, appErr := th.App.PatchCPAValue(rctx, userID, createdField.ID, json.RawMessage(fmt.Sprintf(`"%s"`, optionID)), false)
require.Nil(t, appErr)
require.NotNil(t, value)
// Verify value exists before type change
values, appErr := th.App.ListCPAValues(rctx, userID)
require.Nil(t, appErr)
require.Len(t, values, 1)
// Patch the field and change type from select to text
patch := &model.PropertyFieldPatch{
Type: model.NewPointer(model.PropertyFieldTypeText),
}
updatedField, appErr := th.App.PatchCPAField(rctx, createdField.ID, patch)
require.Nil(t, appErr)
require.Equal(t, model.PropertyFieldTypeText, updatedField.Type)
// Verify values have been deleted
values, appErr = th.App.ListCPAValues(rctx, userID)
require.Nil(t, appErr)
require.Empty(t, values)
})
}
func TestDeleteCPAField(t *testing.T) {
mainHelper.Parallel(t)
th := Setup(t).InitBasic(t)
cpaID, cErr := th.App.CpaGroupID()
require.Nil(t, cErr)
rctx := th.emptyContextWithCallerID(anonymousCallerId)
newField, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
GroupID: cpaID,
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
})
require.NoError(t, err)
createdField, appErr := th.App.CreateCPAField(rctx, newField)
require.Nil(t, appErr)
for i := range 3 {
newValue := &model.PropertyValue{
TargetID: model.NewId(),
TargetType: model.PropertyValueTargetTypeUser,
GroupID: cpaID,
FieldID: createdField.ID,
Value: json.RawMessage(fmt.Sprintf(`"Value %d"`, i)),
}
value, err := th.App.CreatePropertyValue(rctx, newValue)
require.Nil(t, err)
require.NotZero(t, value.ID)
}
t.Run("should fail if the field doesn't exist", func(t *testing.T) {
err := th.App.DeleteCPAField(rctx, model.NewId())
require.NotNil(t, err)
require.Equal(t, "app.custom_profile_attributes.property_field_not_found.app_error", err.Id)
})
t.Run("should not allow to delete a field outside of CPA", func(t *testing.T) {
newField := &model.PropertyField{
GroupID: model.NewId(),
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
}
field, err := th.App.CreatePropertyField(rctx, newField, false, "")
require.Nil(t, err)
dErr := th.App.DeleteCPAField(rctx, field.ID)
require.NotNil(t, dErr)
require.Equal(t, "app.custom_profile_attributes.property_field_not_found.app_error", dErr.Id)
})
t.Run("should correctly delete the field", func(t *testing.T) {
// check that we have the associated values to the field prior deletion
opts := model.PropertyValueSearchOpts{PerPage: 10, FieldID: createdField.ID}
values, err := th.App.SearchPropertyValues(rctx, cpaID, opts)
require.Nil(t, err)
require.Len(t, values, 3)
// delete the field
require.Nil(t, th.App.DeleteCPAField(rctx, createdField.ID))
// check that it is marked as deleted
fetchedField, err := th.App.GetPropertyField(rctx, "", createdField.ID)
require.Nil(t, err)
require.NotZero(t, fetchedField.DeleteAt)
// ensure that the associated fields have been marked as deleted too
values, err = th.App.SearchPropertyValues(rctx, cpaID, opts)
require.Nil(t, err)
require.Len(t, values, 0)
opts.IncludeDeleted = true
values, err = th.App.SearchPropertyValues(rctx, cpaID, opts)
require.Nil(t, err)
require.Len(t, values, 3)
for _, value := range values {
require.NotZero(t, value.DeleteAt)
}
})
}
func TestGetCPAValue(t *testing.T) {
mainHelper.Parallel(t)
th := Setup(t).InitBasic(t)
cpaID, cErr := th.App.CpaGroupID()
require.Nil(t, cErr)
rctx := th.emptyContextWithCallerID(anonymousCallerId)
field := &model.PropertyField{
GroupID: cpaID,
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
}
createdField, err := th.App.CreatePropertyField(rctx, field, false, "")
require.Nil(t, err)
fieldID := createdField.ID
t.Run("should fail if the value doesn't exist", func(t *testing.T) {
pv, appErr := th.App.GetCPAValue(rctx, model.NewId())
require.NotNil(t, appErr)
require.Nil(t, pv)
})
t.Run("should fail if the group id is invalid", func(t *testing.T) {
propertyValue := &model.PropertyValue{
TargetID: model.NewId(),
TargetType: model.PropertyValueTargetTypeUser,
GroupID: model.NewId(),
FieldID: fieldID,
Value: json.RawMessage(`"Value"`),
}
created, err := th.App.CreatePropertyValue(rctx, propertyValue)
require.Nil(t, err)
require.NotNil(t, created)
pv, appErr := th.App.GetCPAValue(rctx, created.ID)
require.NotNil(t, appErr)
require.Nil(t, pv)
})
t.Run("should succeed if id exists", func(t *testing.T) {
propertyValue := &model.PropertyValue{
TargetID: model.NewId(),
TargetType: model.PropertyValueTargetTypeUser,
GroupID: cpaID,
FieldID: fieldID,
Value: json.RawMessage(`"Value"`),
}
propertyValue, err := th.App.CreatePropertyValue(rctx, propertyValue)
require.Nil(t, err)
pv, appErr := th.App.GetCPAValue(rctx, propertyValue.ID)
require.Nil(t, appErr)
require.NotNil(t, pv)
})
t.Run("should handle array values correctly", func(t *testing.T) {
arrayField := &model.PropertyField{
GroupID: cpaID,
Name: model.NewId(),
Type: model.PropertyFieldTypeMultiselect,
}
createdField, err := th.App.CreatePropertyField(rctx, arrayField, false, "")
require.Nil(t, err)
propertyValue := &model.PropertyValue{
TargetID: model.NewId(),
TargetType: model.PropertyValueTargetTypeUser,
GroupID: cpaID,
FieldID: createdField.ID,
Value: json.RawMessage(`["option1", "option2", "option3"]`),
}
propertyValue, err = th.App.CreatePropertyValue(rctx, propertyValue)
require.Nil(t, err)
pv, appErr := th.App.GetCPAValue(rctx, propertyValue.ID)
require.Nil(t, appErr)
require.NotNil(t, pv)
var arrayValues []string
require.NoError(t, json.Unmarshal(pv.Value, &arrayValues))
require.Equal(t, []string{"option1", "option2", "option3"}, arrayValues)
})
}
func TestListCPAValues(t *testing.T) {
mainHelper.Parallel(t)
th := SetupConfig(t, func(cfg *model.Config) {
cfg.FeatureFlags.CustomProfileAttributes = true
}).InitBasic(t)
cpaID, cErr := th.App.CpaGroupID()
require.Nil(t, cErr)
rctx := th.emptyContextWithCallerID(anonymousCallerId)
userID := model.NewId()
t.Run("should return empty list when user has no values", func(t *testing.T) {
values, appErr := th.App.ListCPAValues(rctx, userID)
require.Nil(t, appErr)
require.Empty(t, values)
})
t.Run("should list all values for a user", func(t *testing.T) {
var expectedValues []json.RawMessage
for i := 1; i <= CustomProfileAttributesFieldLimit; i++ {
field := &model.PropertyField{
GroupID: cpaID,
Name: fmt.Sprintf("Field %d", i),
Type: model.PropertyFieldTypeText,
}
_, err := th.App.CreatePropertyField(rctx, field, false, "")
require.Nil(t, err)
value := &model.PropertyValue{
TargetID: userID,
TargetType: model.PropertyValueTargetTypeUser,
GroupID: cpaID,
FieldID: field.ID,
Value: json.RawMessage(fmt.Sprintf(`"Value %d"`, i)),
}
_, err = th.App.CreatePropertyValue(rctx, value)
require.Nil(t, err)
expectedValues = append(expectedValues, value.Value)
}
// List values for original user
values, appErr := th.App.ListCPAValues(rctx, userID)
require.Nil(t, appErr)
require.Len(t, values, CustomProfileAttributesFieldLimit)
actualValues := make([]json.RawMessage, len(values))
for i, value := range values {
require.Equal(t, userID, value.TargetID)
require.Equal(t, "user", value.TargetType)
require.Equal(t, cpaID, value.GroupID)
actualValues[i] = value.Value
}
require.ElementsMatch(t, expectedValues, actualValues)
})
}
func TestPatchCPAValue(t *testing.T) {
mainHelper.Parallel(t)
th := Setup(t).InitBasic(t)
cpaID, cErr := th.App.CpaGroupID()
require.Nil(t, cErr)
rctx := th.emptyContextWithCallerID(anonymousCallerId)
t.Run("should fail if the field doesn't exist", func(t *testing.T) {
invalidFieldID := model.NewId()
_, appErr := th.App.PatchCPAValue(rctx, model.NewId(), invalidFieldID, json.RawMessage(`"fieldValue"`), true)
require.NotNil(t, appErr)
})
t.Run("should create value if new field value", func(t *testing.T) {
newField := &model.PropertyField{
GroupID: cpaID,
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
}
createdField, err := th.App.CreatePropertyField(rctx, newField, false, "")
require.Nil(t, err)
userID := model.NewId()
patchedValue, appErr := th.App.PatchCPAValue(rctx, userID, createdField.ID, json.RawMessage(`"test value"`), true)
require.Nil(t, appErr)
require.NotNil(t, patchedValue)
require.Equal(t, json.RawMessage(`"test value"`), patchedValue.Value)
require.Equal(t, userID, patchedValue.TargetID)
t.Run("should correctly patch the CPA property value", func(t *testing.T) {
patch2, appErr := th.App.PatchCPAValue(rctx, userID, createdField.ID, json.RawMessage(`"new patched value"`), true)
require.Nil(t, appErr)
require.NotNil(t, patch2)
require.Equal(t, patchedValue.ID, patch2.ID)
require.Equal(t, json.RawMessage(`"new patched value"`), patch2.Value)
require.Equal(t, userID, patch2.TargetID)
})
})
t.Run("should fail if field is deleted", func(t *testing.T) {
newField := &model.PropertyField{
GroupID: cpaID,
Name: model.NewId(),
Type: model.PropertyFieldTypeText,
}
createdField, err := th.App.CreatePropertyField(rctx, newField, false, "")
require.Nil(t, err)
err = th.App.DeletePropertyField(rctx, cpaID, createdField.ID, false, "")
require.Nil(t, err)
userID := model.NewId()
patchedValue, appErr := th.App.PatchCPAValue(rctx, userID, createdField.ID, json.RawMessage(`"test value"`), true)
require.NotNil(t, appErr)
require.Nil(t, patchedValue)
})
t.Run("should handle array values correctly", func(t *testing.T) {
optionsID := []string{model.NewId(), model.NewId(), model.NewId(), model.NewId()}
arrayField := &model.PropertyField{
GroupID: cpaID,
Name: model.NewId(),
Type: model.PropertyFieldTypeMultiselect,
Attrs: model.StringInterface{
"options": []map[string]any{
{"id": optionsID[0], "name": "option1"},
{"id": optionsID[1], "name": "option2"},
{"id": optionsID[2], "name": "option3"},
{"id": optionsID[3], "name": "option4"},
},
},
}
createdField, err := th.App.CreatePropertyField(rctx, arrayField, false, "")
require.Nil(t, err)
// Create a JSON array with option IDs (not names)
optionJSON := fmt.Sprintf(`["%s", "%s", "%s"]`, optionsID[0], optionsID[1], optionsID[2])
userID := model.NewId()
patchedValue, appErr := th.App.PatchCPAValue(rctx, userID, createdField.ID, json.RawMessage(optionJSON), true)
require.Nil(t, appErr)
require.NotNil(t, patchedValue)
var arrayValues []string
require.NoError(t, json.Unmarshal(patchedValue.Value, &arrayValues))
require.Equal(t, []string{optionsID[0], optionsID[1], optionsID[2]}, arrayValues)
require.Equal(t, userID, patchedValue.TargetID)
// Update array values with valid option IDs
updatedOptionJSON := fmt.Sprintf(`["%s", "%s"]`, optionsID[1], optionsID[3])
updatedValue, appErr := th.App.PatchCPAValue(rctx, userID, createdField.ID, json.RawMessage(updatedOptionJSON), true)
require.Nil(t, appErr)
require.NotNil(t, updatedValue)
require.Equal(t, patchedValue.ID, updatedValue.ID)
arrayValues = nil
require.NoError(t, json.Unmarshal(updatedValue.Value, &arrayValues))
require.Equal(t, []string{optionsID[1], optionsID[3]}, arrayValues)
require.Equal(t, userID, updatedValue.TargetID)
t.Run("should fail if it tries to set a value that not valid for a field", func(t *testing.T) {
// Try to use an ID that doesn't exist in the options
invalidID := model.NewId()
invalidOptionJSON := fmt.Sprintf(`["%s", "%s"]`, optionsID[0], invalidID)
invalidValue, appErr := th.App.PatchCPAValue(rctx, userID, createdField.ID, json.RawMessage(invalidOptionJSON), true)
require.NotNil(t, appErr)
require.Nil(t, invalidValue)
require.Equal(t, "app.custom_profile_attributes.validate_value.app_error", appErr.Id)
// Test with completely invalid JSON format
invalidJSON := `[not valid json]`
invalidValue, appErr = th.App.PatchCPAValue(rctx, userID, createdField.ID, json.RawMessage(invalidJSON), true)
require.NotNil(t, appErr)
require.Nil(t, invalidValue)
require.Equal(t, "app.custom_profile_attributes.validate_value.app_error", appErr.Id)
// Test with wrong data type (sending string instead of array)
wrongTypeJSON := `"not an array"`
invalidValue, appErr = th.App.PatchCPAValue(rctx, userID, createdField.ID, json.RawMessage(wrongTypeJSON), true)
require.NotNil(t, appErr)
require.Nil(t, invalidValue)
require.Equal(t, "app.custom_profile_attributes.validate_value.app_error", appErr.Id)
})
})
}
func TestDeleteCPAValues(t *testing.T) {
mainHelper.Parallel(t)
th := SetupConfig(t, func(cfg *model.Config) {
cfg.FeatureFlags.CustomProfileAttributes = true
}).InitBasic(t)
cpaID, cErr := th.App.CpaGroupID()
require.Nil(t, cErr)
rctx := th.emptyContextWithCallerID(anonymousCallerId)
userID := model.NewId()
otherUserID := model.NewId()
// Create multiple fields and values for the user
var createdFields []*model.CPAField
for i := 1; i <= 3; i++ {
field, err := model.NewCPAFieldFromPropertyField(&model.PropertyField{
GroupID: cpaID,
Name: fmt.Sprintf("Field %d", i),
Type: model.PropertyFieldTypeText,
})
require.NoError(t, err)
createdField, appErr := th.App.CreateCPAField(rctx, field)
require.Nil(t, appErr)
createdFields = append(createdFields, createdField)
// Create a value for this field
value, appErr := th.App.PatchCPAValue(rctx, userID, createdField.ID, json.RawMessage(fmt.Sprintf(`"Value %d"`, i)), false)
require.Nil(t, appErr)
require.NotNil(t, value)
}
// Verify values exist before deletion
values, appErr := th.App.ListCPAValues(rctx, userID)
require.Nil(t, appErr)
require.Len(t, values, 3)
// Test deleting values for user
t.Run("should delete all values for a user", func(t *testing.T) {
appErr := th.App.DeleteCPAValues(rctx, userID)
require.Nil(t, appErr)
// Verify values are gone
values, appErr := th.App.ListCPAValues(rctx, userID)
require.Nil(t, appErr)
require.Empty(t, values)
})
t.Run("should handle deleting values for a user with no values", func(t *testing.T) {
appErr := th.App.DeleteCPAValues(rctx, otherUserID)
require.Nil(t, appErr)
})
t.Run("should not affect values for other users", func(t *testing.T) {
// Create values for another user
for _, field := range createdFields {
value, appErr := th.App.PatchCPAValue(rctx, otherUserID, field.ID, json.RawMessage(`"Other user value"`), false)
require.Nil(t, appErr)
require.NotNil(t, value)
}
// Delete values for original user
appErr := th.App.DeleteCPAValues(rctx, userID)
require.Nil(t, appErr)
// Verify other user's values still exist
values, appErr := th.App.ListCPAValues(rctx, otherUserID)
require.Nil(t, appErr)
require.Len(t, values, 3)
})
}