GetChannelCounts was only reachable from App and had no callers.
Remove SqlChannelStore implementation, store interface, timer/retry
layers, tests, mock, model.ChannelCounts, and the orphaned i18n key.
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Julien Tant <JulienTant@users.noreply.github.com>
* add WithRPCErr hooks (server-facing/internal only)
* zero _returns on RPC failure in WithRPCErr companions
Aligns the WithRPCErr template with the HooksRPCErr godoc contract: when
g.client.Call returns a transport error, gob may have partially decoded the
reply. Reassign _returns to a zero value before destructuring so callers always
receive zeroed outputs alongside a non-nil transport error.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* rename HooksRPCErr to HooksWithRPCErr for naming consistency
Every related symbol uses the WithRPCErr suffix (MessageHasBeenPostedWithRPCErr,
RunMultiPluginHookWithRPCErr, RunMultiHookWithRPCErr, etc.). Aligning the
interface name removes the only outlier and makes the convention uniform.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* rename rpcErrImpl to hooksWithRPCErrImpl
Mirrors the existing hooksImpl/Hooks naming pattern on hooksTimerLayer.
* add supervisor.HooksWithRPCErr() and drop runtime type assertion
The old path did rp.supervisor.Hooks().(HooksWithRPCErr) and handled the
"doesn't implement" branch — but that branch was structurally unreachable
(the compile-time `_ HooksWithRPCErr = (*hooksTimerLayer)(nil)` assertion
guards it).
Change supervisor.hooks from `Hooks` to the concrete `*hooksTimerLayer`
(which implements both interfaces, enforced at field assignment), add a
parallel HooksWithRPCErr() accessor, and call it directly. Hooks() keeps
its public Hooks-interface signature via implicit conversion at return.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* drop "implemented by" clause from HooksWithRPCErr godoc
Both hooksRPCClient and hooksTimerLayer satisfy the interface, and naming
implementations in interface godocs adds rot — the contract is what readers
need, not the list of wrappers.
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Implemented edit file permission
* lint fixes
* Updated snapshot
* Updated tests
* Updated test
* CI
* Permission reordering and tooltip text update
* Made a geneeric function
* Report POC
* Including more error logs
* Added localisationj for each reviewer
* Optimisations
* Minor tweaks
* restored go module files
* lint fixes
* Added back transslations
* Added translations
* linter and test fixes
* restored go module files
* e2e lint fix
* lint fixes
* AI fixes
* fixed typo
* fixed nil pointer error
* Added more tests
* Publish report even if deletion fails
* Fixed the e2e test
* Distinguished between no data and deleted data
* lint fixes
* fixed tests
* e2e test fix
* Updated test to also upload actual file
* Removed file name tracking
* Text updates
* fixed e2e test
* lint fix
* Move min_date, max_date, time_interval into DialogElement.datetime_config
Consolidate date/datetime configuration into the datetime_config sub-object
on both DialogElement (Go/TS) and AppField (TS), deprecating the top-level
fields while keeping them for backward compatibility. DateTimeConfig values
take precedence over legacy fields via EffectiveDateTimeConfig() (Go) and
nullish coalescing fallback chains (TS).
Also fixes: timezone indicator now uses FormattedMessage for i18n, CSS class
with theme variable instead of inline styles, and proper DateTimeConfig type
instead of Record<string, unknown> cast.
The new TestRegisterPluginForSharedChannels tests added in #36126 broke
master CI because RegisterPluginForSharedChannels assigned opts.Displayname
directly to RemoteCluster.Name, which IsValid validates against the slug
regex ^[a-zA-Z0-9.\-_]+$. Display names with spaces (e.g. "legacy plugin")
fail validation. The tests didn't run in the PR's final CI shard and the
issue surfaced post-merge.
Add CleanRemoteName to the public model, mirroring CleanTeamName and
CleanUsername: lowercase, replace spaces and other disallowed characters
with hyphens, trim, truncate to RemoteNameMaxLength, fall back to NewId
when the result is empty. Use it in RegisterPluginForSharedChannels so
Name is always slug-valid while DisplayName keeps the human-readable label.
This also lets real plugins register with display names containing spaces.
* MM-67979 MM-67980: Add SMTP and push proxy connectivity to support packet
Adds a `notifications` section to `diagnostics.yaml` in the support
packet with SMTP email and push proxy connectivity probe results.
- `notifications.email.status`: ok/fail/disabled based on whether
SendEmailNotifications is enabled and an SMTP connection can be
established using mail.TestConnection()
- `notifications.push.status`: ok/fail/disabled based on whether
SendPushNotifications is enabled and an HTTP GET to the configured
PushNotificationServer URL succeeds
- Error messages are included in the `error` field on failure
- No email or push notification is sent during the probe
Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
* fix: handle errcheck lint violations in support_packet_test.go
Suppress unhandled error return values from rw.WriteString calls in
the mock SMTP server used in tests.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: use 127.0.0.1 directly in SMTP reachability test
Replace localhost:0 with 127.0.0.1:0 for the mock SMTP listener so
that it always binds to the loopback interface. In CI Docker containers
localhost may resolve to the container IP rather than 127.0.0.1, causing
the SMTP dial to fail with connection refused. Also switch from string
manipulation to net.TCPAddr type assertion for reliable host/port
extraction.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: override MM_EMAILSETTINGS_SMTPSERVER env var in SMTP reachability test
The CI environment sets MM_EMAILSETTINGS_SMTPSERVER=inbucket via
test.env. Mattermost's config Store.Set() calls GetEnvironment()
(os.Environ()) on every UpdateConfig, so env vars silently override
any programmatic config change. Use t.Setenv before UpdateConfig so
the env var points to 127.0.0.1 for the duration of the subtest.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add model.StatusDisabled constant and use it in support_packet.go
Replace "disabled" string literals with model.StatusDisabled for
consistency with model.StatusOk and model.StatusFail.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* refactor: use utils.GetHostnameFromSiteURL, extract testPushProxyConnection helper, set LDAP StatusDisabled
- Replace manual url.Parse with utils.GetHostnameFromSiteURL (consistent with app/config.go)
- Extract push proxy HTTP check into testPushProxyConnection with TODO to move to its own package
- Set d.LDAP.Status = model.StatusDisabled when LDAP is not configured
- Replace "disabled" string literals in tests with model.StatusDisabled
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat: add status field to ElasticSearch diagnostics with ok/fail/disabled
When indexing is enabled, reports ok or fail based on TestConfig result.
When indexing is disabled or the engine is unavailable, reports disabled.
Backend/ServerVersion/ServerPlugins are still collected when the engine
exists regardless of indexing status.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* fix: update Happy path test for LDAP and ES StatusDisabled assertions
Both are disabled in the test environment so they now report StatusDisabled.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* feat: use GET /version endpoint for push proxy connectivity check
Use url.JoinPath to construct the /version path safely, replacing
raw root URL access. Also validate the HTTP status code so non-2xx/3xx
responses are treated as failures.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Mattermost Build <build@mattermost.com>
* Add XML struct tags and multi-remote registration for shared channels plugin API
Phase 1: Add xml struct tags to model types used in SyncMsg (Post, User,
Reaction, Status, PostAcknowledgement, FileInfo, SyncResponse,
MembershipChangeMsg). Add custom MarshalXML/UnmarshalXML for SyncMsg
(Users map, MentionTransforms map), StringMap, and StringInterface.
Exclude Post.Metadata, PrevStatus, and server-internal FileInfo fields
from XML. JSON serialization is unaffected.
Phase 2: Lift the one-remote-per-plugin constraint so plugins can
register multiple remotes with different SiteURLs. Add SiteURL field to
RegisterPluginOpts (defaults to "plugin_<PluginID>" for backward
compatibility). Add GetAllByPluginID and GetBySiteURL store methods.
Rewrite registration to dedup by SiteURL instead of PluginID. Add
UnregisterPluginRemoteForSharedChannels for single-remote removal with
plugin ownership validation. Validate SiteURL is non-empty in
RemoteCluster.IsValid. Simplify IsPlugin() to check PluginID only.
* Adds version to the property group model
* Ensures that the REST API rejects v1 group calls
* Ensures field version and group version match
* Simplify property groups on app layer tests
* Add GetByID to PropertyGroupStore and enforce field/group version match on update
* Simplify bits of the code
* Fix i18n and add generic errors
* Fix PropertyGroupStore mock to return stable IDs and default zero version to V1
* Fix tests that were using nonexistent group IDs
* Fix rigidness on valid group names
* Update group not found slug
* Temporary allow to use tempaltes with v1
* Explicitly including tempaltes in the IsPSAv1 check for conflict check
* Return 404 on group not found and template explicit inclusion on patch API endpoint
* Fix CPA test that would use fields from unregistered groups
---------
Co-authored-by: Miguel de la Cruz <miguel@ctrlz.es>
* Introduce model.SanitizeFilename and model.IsValidFilename, and
apply them in genFileInfoFromReader and FileInfo.IsValid. The
sanitizer uses filepath.Base, NFC-normalizes Unicode, strips ASCII
control characters, collapses backslashes to forward slashes, and
truncates to the VARCHAR(256) fileinfo.name column width.
* MM-67975: Add container CPU and memory limits to support packet diagnostics
Add two new optional fields to SupportPacketDiagnostics.Server:
- container_cpu_limit (float64): effective CPU limit in CPUs (e.g. 0.5, 2.0)
- container_memory_limit_mb (uint64): memory limit in MB
Both fields are populated from cgroups v2 (/sys/fs/cgroup/memory.max and
/sys/fs/cgroup/cpu.max) on Linux. Fields use omitempty so they are absent
from the output on bare metal or when no container limits are configured,
preserving backwards compatibility.
Non-Linux builds compile and produce no output for these fields via a
container_limits_other.go stub, following the existing memory_linux.go /
memory_other.go pattern.
Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
* Fix golangci-lint errors: govet shadow and gofmt formatting
- Fix govet shadow: use var memBytes uint64 + err = instead of memBytes, err :=
to avoid shadowing the outer err variable (which is reused after this block)
- Fix gofmt: add extra space before // 512 MB comment to align with
the longer v2CPUMax line in the same assignment block
* fix(platform): ceil memory MB conversion and return zero-values for missing cgroup files
- Use ceiling division for MemoryLimitMB so sub-1MB limits map to 1 instead
of 0 (which omitempty would silently drop)
- Absorb os.ErrNotExist in getContainerLimits so non-v2/bare-metal hosts
return ContainerLimits{}, nil as the function comment promises
- Update test: missing cgroup file now asserts zero-values, not an error
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* test(platform): add subtest locking ceil-to-MB behavior for sub-MB memory limits
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* test(platform): add subtest for missing cpu.max returning zero values
Locks in the os.ErrNotExist branch for cpu.max (lines 57-60 in
container_limits_linux.go), which was previously unreachable via the
existing missing-memory test since that test returns early before
reading cpu.max.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
* Surface ws_event type in oversized cluster publish message logs
When a best-effort UDP gossip send fails with "message too long", the log
only shows event: publish with no further context. Tag the ClusterMessage
with the originating WebSocket event type so it appears in the error log.
* Update enterprise.pin to latest after enterprise PR #2133 merged
https://claude.ai/code/session_01Y1Abg1eDjKQBJvy7XhCtG6
* Bump
---------
Co-authored-by: Mattermost Build <build@mattermost.com>
Co-authored-by: Claude <noreply@anthropic.com>
* gather plugin metrics and serve on /metrics
* tests
* fix recent conflicts from master
* fix linting
* address review feedback: feature flag, route guard, and unit tests for plugin metrics
- Add PluginMetricsCollection feature flag (default true) to allow disabling plugin metric collection without a deploy
- Only wrap the /metrics handler with plugin metric collection (not arbitrary plugin routes, which would cause double-listing)
- Extract wrapping logic into wrapMetricsHandler for clarity
- Add unit tests for addPluginLabelToMetrics covering no-label, existing-label, comments, empty lines, and multiple metrics cases
* fix integration tests to use /metrics route so wrapMetricsHandler runs
* switch addPluginLabelToMetrics to use expfmt for correct label injection
Replace string manipulation with expfmt parse→mutate→re-encode, which
correctly handles all metric types, timestamps, and malformed input.
Output is normalized: blank lines are dropped and TYPE headers are
injected for undeclared metrics. Update unit tests accordingly.
* refine addPluginLabelToMetrics: log warnings, drop sort, use assert.Contains
- Log a warning (instead of silently discarding) on parse or encode errors,
returning empty string in both cases
- Remove name sorting — metric family order is irrelevant to Prometheus scrapers
- Switch unit test assertions to assert.Contains per line so tests are
order-independent
* replace strPtr helper with model.NewPointer
* fix gofmt: remove extra blank line
* replace existing plugin_id label instead of appending a duplicate
If a plugin already exports a plugin_id label, overwrite it rather than
appending a second one, which would produce invalid Prometheus output.
Add test coverage for the replace path.
* add missing test coverage per mattermost-build feedback
- Unit test: malformed input returns empty string without panicking
- Integration: PluginMetricsCollection=false excludes plugin metrics
- Integration: plugin returning non-200 status excluded from response
- Integration: plugin returning empty body excluded from response
* rename PluginMetricsCollection to AggregatePluginMetrics, default false
---------
Co-authored-by: Jesse Hallam <jesse@mattermost.com>
* MM-67976: Add server uptime to support packet
Add process start time (started_at) and approximate host start time
(host_started_at, Linux only, derived from /proc/uptime) to the support
packet diagnostics. This helps diagnose restart loops and distinguish
process restarts from full machine/container reboots.
Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
* Add HostStartedAt assertions to support packet happy-path test
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Revert unrelated changes
* Add unit tests for getHostUptimeSeconds and fix cross-platform portability
- Extract parseUptimeFile helper in uptime_linux.go to enable unit testing
with synthetic file paths without touching the real /proc/uptime
- Add uptime_linux_test.go covering all error paths (file read error,
empty file, non-numeric value) and happy-path parsing
- Add uptime_other_test.go asserting the non-Linux stub returns
ErrHostUptimeUnsupportedPlatform and zero seconds
- Guard HostStartedAt assertions in support_packet_test.go with
runtime.GOOS so the test correctly asserts zero-time on non-Linux
platforms instead of failing
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* test: use t.TempDir() for guaranteed-missing path in uptime test
Replace the hard-coded /nonexistent/proc/uptime path with a path
constructed from t.TempDir() to guarantee the file is absent without
relying on filesystem layout assumptions. Also remove the misleading
comment about swapping implementations.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Reorder Server struct fields and assignments to group process identity fields together
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* Add macOS support for host uptime in support packet
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
* MM-67978: Add open file descriptor count to support packet diagnostics
Add OpenFileDescriptors and MaxFileDescriptors fields to
SupportPacketDiagnostics.Server. On Linux the open count is read from
/proc/self/fd; on macOS from /dev/fd. Both platforms use
syscall.Getrlimit(RLIMIT_NOFILE) for the soft limit. Unsupported
platforms (e.g. Windows) return -1 for both fields.
Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
* MM-67978: Move OpenFileDescriptors/MaxFileDescriptors after TotalMemoryMB
Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
* fix: guard int64 overflow in getMaxFileDescriptors and update tests for unsupported platforms
Add overflow check before casting rlimit.Cur (uint64) to int64 in
getMaxFileDescriptors on Linux. Update fd_test.go and
support_packet_test.go assertions to accept -1 as a valid sentinel for
unsupported platforms instead of requiring a strictly positive value.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
* revert: remove unrelated test refactoring from support_packet_test.go
Restore the three unrelated changes that crept into this branch:
- SetLogRootPathOverride instead of t.Setenv("MM_LOG_PATH", ...)
- installTypeOverride field instead of t.Setenv(envVarInstallType, ...)
- Restore explanatory comment in TestGetSanitizedConfigFile
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
Add a GoVersion field to SupportPacketDiagnostics.Server populated via
runtime.Version(), so support engineers can determine which Go version
a server was compiled with from the support packet alone.
Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
Populate server.process_id in diagnostics.yaml using os.Getpid(), making it easier to correlate support packet data with OS-level logs and confirm whether the server was restarted between an incident and packet generation.
Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
* [MM-67880] Add /mobile-logs slash command with E2E tests
Add a new /mobile-logs slash command that allows users to manage the
attach_app_logs preference for themselves or other users (admin-only).
Includes unit tests for all code paths and Playwright E2E tests covering
self-management, admin cross-user management, permission denial, and
error handling.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Fix i18n error key suffixes and format E2E tests
Rename error i18n keys to use .app_error suffix matching upstream
convention (no_permission, update_error, user_not_found). Run prettier
on the E2E test file to fix formatting.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Fix E2E test type error: use getUserPreferences instead of getMyPreferences
The getAttachLogsPreference helper was using getMyPreferences() which returns
PreferenceType (not an array), causing TS2345 errors. Switch to
getUserPreferences(userId) which returns the expected array type.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* [MM-67880] Move unreachable usage fallback into switch default case
The return after the switch was unreachable because action is validated
earlier to be "on", "off", or "status". Move it into an explicit default
case with a defensive comment.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* allow up to 2 arguments
* Add audit logging for mobile logs slash command actions
Implement a new function to log audit records when users enable or disable the attach_app_logs preference via the /mobile-logs command. This includes capturing relevant metadata such as user IDs, session information, and the action taken. The logging occurs in both the enable and disable command paths, enhancing traceability and accountability for user preference changes.
* Enhance mobile logs command to handle cross-user permission checks
Add a new response function for cases where a regular user attempts to access mobile log settings for another user, ensuring they receive a neutral error message instead of specific user information. Update the command logic to incorporate this response for both nonexistent users and deactivated accounts. Additionally, modify related tests and internationalization keys to reflect these changes, improving security and user experience.
* Update E2E test for /mobile-logs command to verify permission denial for nonexistent users
Enhance the existing E2E test for the /mobile-logs command by adding assertions to check that users receive a permission denial message when attempting to change mobile log settings for a nonexistent user. This improves test coverage and ensures proper error handling in the application.
* update i18n strings
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Mattermost Build <build@mattermost.com>
* Adding watermarking toggle in server
* Update setting to enterprise
* Adding it to mobile security
* Updating experimental section
* Moved back to experimental settings. Added license checks
* Updating tests
---------
Co-authored-by: maria.nunez <maria.nunez@mattermost.com>
* MM-67592 - be changes for team admin abac channels (#35353)
* MM-67592 - be changes for team admin abac channels
* Revert team-scoped API routes, keep app layer business logic
* move from config to permission; Add cluster-aware LRU cache for policy team scope lookup
* remove unnecessary references to config value
* local/remote cache invalidation consistency for policy scope
* Replace policy scope cache with store-level team scope query
* rename functions and add comments to query
---------
Co-authored-by: Mattermost Build <build@mattermost.com>
* MM 67594 - policies CUD operations to team settings modal channels ABAC (#35590)
* MM-67592 - be changes for team admin abac channels
* Revert team-scoped API routes, keep app layer business logic
* move from config to permission; Add cluster-aware LRU cache for policy team scope lookup
* remove unnecessary references to config value
* local/remote cache invalidation consistency for policy scope
* Replace policy scope cache with store-level team scope query
* format files correctly
* fix mock expectations for store-query approach in tests
* rename functions and add comments to query
* revert error ids to original to prevent break tests
* adjust translations
* MM-67669 - add tab to team settings modal and basic listing
* adjust tests and fix linter
* use existing search api logic
* fix style and adjust flaky test to clean up and restore orinals
* address ai corabbit feedback and fix linter
* fix unit tests
* MM-67592 - be changes for team admin abac channels (#35353)
* MM-67592 - be changes for team admin abac channels
* fix linter
* fix ts linter for playwright
* Revert team-scoped API routes, keep app layer business logic
* move from config to permission; Add cluster-aware LRU cache for policy team scope lookup
* remove unnecessary references to config value
* local/remote cache invalidation consistency for policy scope
* Replace policy scope cache with store-level team scope query
* format files correctly
* fix mock expectations for store-query approach in tests
* rename functions and add comments to query
* revert error ids to original to prevent break tests
* adjust translations
---------
Co-authored-by: Mattermost Build <build@mattermost.com>
* MM-67594 - support cud operations for team abac BE changes
* create the team settings policy edit section, reuse most components, add basic e2e
* move optional refresh policy list button to list component
* temp get team admins cud policies and sync job
* enhance validation and adjust e2e
* Fix testExpression permission; fix pagination of team policies; add isValidId validation
* adjust styles, handling renaming and add permission migrations
* update the permissions names, use the simple confirmation modal, define the delete modal
* fix policy deletion flow
* fix some linter issues and adjust helper tests
* remove delete from list and fix e2e
* code comments clean up
* remove CEL editor for now, clean styles, enhance e2e
* fix linter, adjust unit test
* fix linter and add missing translation
* fix policy deletion ownership and sanitize test expression
* fixed e2e tests
* rollback orphaned policy on failed channel assignment
* enforce channelless check before last_team_id fallback
* enforce channelless guard on assign fallback too
* add translations missing
* add teamId to audit payload when present
* fix refresh button pagination reset
* fix null safety in channel selector loadChannels
* use responsive width cap for team settings modal and adjust header size
* remove redundant raw term from channel search URL, add showRefreshButton prop to PolicyList component
* handle error when stamping last team ID on channelless policy
* replace Props-based ownership with in-memory LRU cache, disable save on zero channels
* make e2e tests more reliable in CI
* test skip if no license valid found
* add childCount guard to cache-hit paths and reduce TTL to 5s
* fix e2e, adjust translation
* address review feedback: flatten permission checks and separate error types
- Flatten nested permission branching in deleteAccessControlPolicy using
early returns to reduce indentation (review: isacikgoz)
- Validate teamID as input (400) before using it for permission checks (403)
in testExpression and validateExpressionAgainstRequester handlers
- Remove redundant hasSystemPermission check in searchAccessControlPolicies
since system_admin role already includes manage_team_access_rules
- Refactor ValidateTeamAdminPolicyOwnership to return (bool, *model.AppError)
separating "not owned" from "internal error" across all 8 call sites
- Update tests to assert on both return values
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* add persistent team scope to access control policies, replace in-memory cache
* fix translation
* fix case-insensitive policy search and sanitize search term input
* make policies tests have a unique name
* decouple scope/scopeID filter from TeamID in policy store
* Fix authZ bypass searchChannelsForAccessControlPolicy by forcing TeamIds to authorized team
* show unsaved changes on navigator back, and list all private channels on load
* filter already applied channels to a policy
* adjust the styles to dark mode; do not show added channels to the policy in the add channels modal
* fix linter
* MM-67967 add sync status footer to team settings (#35729)
* MM-67967 add sync status footer to team settings
* remove magic numbers and strings and polish the code
* fix linter
* fix linter: replace interface{} with any per gofmt rewrite rule
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* refine getJobsByType team-scoped filtering and permissions
* fix sync footer stuck in syncing state on job creation error
* fix team-scoped job pagination in getJobsByType
* Fix authZ bypass searchChannelsForAccessControlPolicy by forcing TeamIds to authorized team
* implement ux feedback, change titles font, fix marging and scroll view jump
* MM-68135 - migrate add channels to policy modal to generic modal (#35907)
* MM-67920 unify e2e team settings tests (#35867)
* MM-67920 - extract duplicated policy editor helpers
* remove duplicate team icon test file
* rename Access Control to Membership Policies in e2e
* replace networkidle with explicit element waits
* fix attribute loading issue
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: Mattermost Build <build@mattermost.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix playwright feedback issues and persist filters to the store layer in the no systemconsole path
* Improve policy scope validation and team admin security checks
* Renamed public channels to "AAA Public Channel %03d" and private ones to "ZZZ Private..." so the 55 public channels now fill the 50-result cap
* fix e2e tests and add new unit tests to improve coverage
* Improve e2e test stability: race condition handling and timeout adjustments
* Improve team-scoped ABAC policies: scope preservation, input validation, shared exclusion
* Add comprehensive ABAC test coverage: team admin ops and security validation to reduce flakyness
* Fix team policy editor back button: preserve navigation intent through Undo
* style: format import statements for better readability
* Enhance access control policy creation for team admins: enforce scope stamping from query parameters to prevent unauthorized team assignments
---------
Co-authored-by: Mattermost Build <build@mattermost.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Add PermissionCreateAgent server-side permission definition
Define PermissionCreateAgent in the model layer with system scope,
add to SystemScopedPermissionsMinusSysconsole (feeds AllPermissions),
grant to system_user in MakeDefaultRoles(), and register a permissions
migration for existing installations (system_admin + system_user).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Add exhaustive tests for PermissionCreateAgent permission
Model tests: verify create_agent is in AllPermissions, has system scope,
correct i18n fields, present in system_admin and system_user default roles,
and absent from system_guest.
Migration test: verify getAddCreateAgentPermissionMigration adds create_agent
to both system_admin and system_user, and is idempotent on re-run.
Also register the migration key in testlib mock store so server initialization
skips it during test setup.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Add webapp permission constants and i18n for create_agent
Add CREATE_AGENT constant to permissions.ts, display strings with
defineMessages in permissions.tsx, and i18n entries in en.json so the
permission appears in System Console Permission Schemes UI.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* Clean up tests and minor fixups for create_agent permission
Consolidate role_test.go into table-driven tests, remove redundant comments
in permissions_migrations_test.go, add .planning/ to .gitignore, and
refresh webapp/package-lock.json.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Split create_agent into manage_own_agent and manage_others_agent
Replace PermissionCreateAgent with system-scoped own/others permissions,
update migration and defaults, and wire System Scheme UI for integrations.
Made-with: Cursor
* fixes
* Stabilize autotranslation E2E by pinning mock source language
Set LibreTranslate mock to English before the pre-enable post and Spanish
before the post-enable message so parallel tests cannot leave the mock in
a state where the new message is not translated.
Made-with: Cursor
* Revert package-lock, add more chnages
* Revert "Revert package-lock, add more chnages"
This reverts commit 7f6752c2e0.
* Drop unrelated autotranslation E2E tweak; restore package-lock
The Playwright autotranslation change was not caused by MM-65671. Revert
that test edit and restore webapp/package-lock.json after an accidental
revert of the prior package-lock update.
Made-with: Cursor
* Put package-lock back again
* fixes
* Fix migration tests for manage_own_agent on system_user role
Made-with: Cursor
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Mattermost Build <build@mattermost.com>
* Add bulk set (replace) channel memberships API
PUT /api/v4/channels/{channel_id}/members accepts a complete desired
membership list and reconciles it against the current state, adding
missing users and removing extras while leaving existing members
untouched. Results stream back as NDJSON with configurable batch size
and delay to manage server load. Sysadmin only. Private channels
cannot be emptied entirely.
* MM-68235: Rename user-visible "Custom Profile Attributes" to "User Attributes"
Update all English i18n translation values and inline
defaultMessage strings to use the current product name
"User Attributes" instead of the old "Custom Profile
Attributes" / CPA naming.
Add naming-history comments to key CPA source files
(model, app, api4, admin component) explaining that
internal identifiers retain the old naming for backward
compatibility with REST APIs, WebSocket events, and the
Property System Architecture group name. This helps
future developers understand the mapping without needing
to track down the rename history.
* Fix missed lowercase "custom profile attribute" strings
* MM-67505 Add AnalyticsQueryTimeout setting and use when refreshing materialized views
* Fix last minute i18n change
* Disallow 0 values for AnalyticsQueryTimeout
* Fix E2E test config
* Fix post store tests crashing
* Update snapshot and revert accidental changes to it
* Remove system_secure_connection_manager role
The dedicated role for delegating secure connection management is no
longer needed. The manage_secure_connections permission remains and
continues to be granted to system admins via AllPermissions.
Removes the role definition, migration, permissions migration, UI
components, i18n strings, and all associated tests across server,
webapp, and e2e-tests.
* adds team member data sanitizing
* assert using require
* adds data sanitizing to team members for user endpoint
* team admin data visibility now tests with different user
* ci: enable fullyparallel mode for server tests
Replace os.Setenv, os.Chdir, and global state mutations with
parallel-safe alternatives (t.Setenv, t.Chdir, test hooks) across
37 files. Refactor GetLogRootPath and MM_INSTALL_TYPE to use
package-level test hooks instead of environment variables.
This enables gotestsum --fullparallel, allowing all test packages
to run with maximum parallelism within each shard.
Co-authored-by: Claude <claude@anthropic.com>
* ci: split fullyparallel from continue-on-error in workflow template
- Add new boolean input 'allow-failure' separate from 'fullyparallel'
- Change continue-on-error to use allow-failure instead of fullyparallel
- Update server-ci.yml to pass allow-failure: true for test coverage job
- Allows independent control of parallel execution and failure tolerance
Co-authored-by: Claude <claude@anthropic.com>
* fix: protect TestOverrideLogRootPath with sync.Mutex for parallel tests
- Replace global var TestOverrideLogRootPath with mutex-protected functions
- Add SetTestOverrideLogRootPath() and getTestOverrideLogRootPath() functions
- Update GetLogRootPath() to use thread-safe getter
- Update all test files to use SetTestOverrideLogRootPath() with t.Cleanup()
- Fixes race condition when running tests with t.Parallel()
Co-authored-by: Claude <claude@anthropic.com>
* fix: configure audit settings before server setup in tests
- Move ExperimentalAuditSettings from UpdateConfig() to config defaults
- Pass audit config via app.Config() option in SetupWithServerOptions()
- Fixes audit test setup ordering to configure BEFORE server initialization
- Resolves CodeRabbit's audit config timing issue in api4 tests
Co-authored-by: Claude <claude@anthropic.com>
* fix: implement SetTestOverrideLogRootPath mutex in logger.go
The previous commit updated test callers to use SetTestOverrideLogRootPath()
but didn't actually create the function in config/logger.go, causing build
failures across all CI shards. This commit:
- Replaces the exported var TestOverrideLogRootPath with mutex-protected
unexported state (testOverrideLogRootPath + testOverrideLogRootMu)
- Adds exported SetTestOverrideLogRootPath() setter
- Adds unexported getTestOverrideLogRootPath() getter
- Updates GetLogRootPath() to use the thread-safe getter
- Fixes log_test.go callers that were missed in the previous commit
Co-authored-by: Claude <claude@anthropic.com>
* fix(test): use SetupConfig for access_control feature flag registration
InitAccessControlPolicy() checks FeatureFlags.AttributeBasedAccessControl
at route registration time during server startup. Setting the flag via
UpdateConfig after Setup() is too late — routes are never registered
and API calls return 404.
Use SetupConfig() to pass the feature flag in the initial config before
server startup, ensuring routes are properly registered.
Co-authored-by: Claude <claude@anthropic.com>
* fix(test): restore BurnOnRead flag state in TestRevealPost subtest
The 'feature not enabled' subtest disables BurnOnRead without restoring
it via t.Cleanup. Subsequent subtests inherit the disabled state, which
can cause 501 errors when they expect the feature to be available.
Add t.Cleanup to restore FeatureFlags.BurnOnRead = true after the
subtest completes.
Co-authored-by: Claude <claude@anthropic.com>
* fix(test): restore EnableSharedChannelsMemberSync flag via t.Cleanup
The test disables EnableSharedChannelsMemberSync without restoring it.
If the subtest exits early (e.g., require failure), later sibling
subtests inherit a disabled flag and become flaky.
Add t.Cleanup to restore the flag after the subtest completes.
Co-authored-by: Claude <claude@anthropic.com>
* Fix test parallelism: use instance-scoped overrides and init-time audit config
Replace package-level test globals (TestOverrideInstallType,
SetTestOverrideLogRootPath) with fields on PlatformService so each test
gets its own instance without process-wide mutation. Fix three audit
tests (TestUserLoginAudit, TestLogoutAuditAuthStatus,
TestUpdatePasswordAudit) that configured the audit logger after server
init — the audit logger only reads config at startup, so pass audit
settings via app.Config() at init time instead.
Also revert the Go 1.24.13 downgrade and bump mattermost-govet to
v2.0.2 for Go 1.25.8 compatibility.
* Fix audit unit tests
* Fix MMCLOUDURL unit tests
* Fixed unit tests using MM_NOTIFY_ADMIN_COOL_OFF_DAYS
* Make app migrations idempotent for parallel test safety
Change System().Save() to System().SaveOrUpdate() in all migration
completion markers. When two parallel tests share a database pool entry,
both may race through the check-then-insert migration pattern. Save()
causes a duplicate key fatal crash; SaveOrUpdate() makes the second
write a harmless no-op.
* test: address review feedback on fullyparallel PR
- Use SetLogRootPathOverride() setter instead of direct field access
in platform/support_packet_test.go and platform/log_test.go (pvev)
- Restore TestGetLogRootPath in config/logger_test.go to keep
MM_LOG_PATH env var coverage; test uses t.Setenv so it runs
serially which is fine (pvev)
- Fix misleading comment in config_test.go: code uses t.Setenv,
not os.Setenv (jgheithcock)
Co-authored-by: Claude <claude@anthropic.com>
* fix: add missing os import in post_test.go
The os import was dropped during a merge conflict resolution while
burn-on-read shared channel tests from master still use os.Setenv.
Co-authored-by: Claude <claude@anthropic.com>
---------
Co-authored-by: Claude <claude@anthropic.com>
Co-authored-by: wiggin77 <wiggin77@warpmail.net>
Co-authored-by: Mattermost Build <build@mattermost.com>
* Replace hardcoded test passwords with model.NewTestPassword()
Add model.NewTestPassword() utility that generates 14+ character
passwords meeting complexity requirements for FIPS compliance. Replace
all short hardcoded test passwords across the test suite with calls to
this function.
* Enforce FIPS compliance for passwords and HMAC keys
FIPS OpenSSL requires HMAC keys to be at least 14 bytes. PBKDF2 uses
the password as the HMAC key internally, so short passwords cause
PKCS5_PBKDF2_HMAC to fail.
- Add FIPSEnabled and PasswordFIPSMinimumLength build-tag constants
- Raise the password minimum length floor to 14 when compiled with
requirefips, applied in SetDefaults only when unset and validated
independently in IsValid
- Return ErrMismatchedHashAndPassword for too-short passwords in
PBKDF2 CompareHashAndPassword rather than a cryptic OpenSSL error
- Validate atmos/camo HMAC key length under FIPS and lengthen test
keys accordingly
- Adjust password validation tests to use PasswordFIPSMinimumLength
so they work under both FIPS and non-FIPS builds
* CI: shard FIPS test suite and extract merge template
Run FIPS tests on PRs that touch go.mod or have 'fips' in the branch
name. Shard FIPS tests across 4 runners matching the normal Postgres
suite. Extract the test result merge logic into a reusable workflow
template to deduplicate the normal and FIPS merge jobs.
* more
* Fix email test helper to respect FIPS minimum password length
* Fix test helpers to respect FIPS minimum password length
* Remove unnecessary "disable strict password requirements" blocks from test helpers
* Fix CodeRabbit review comments on PR #35905
- Add server-test-merge-template.yml to server-ci.yml pull_request.paths
so changes to the reusable merge workflow trigger Server CI validation
- Skip merge-postgres-fips-test-results job when test-postgres-normal-fips
was skipped, preventing failures due to missing artifacts
- Set guest.Password on returned guest in CreateGuestAndClient helper
to keep contract consistent with CreateUserWithClient
- Use shared LowercaseLetters/UppercaseLetters/NUMBERS/PasswordFIPSMinimumLength
constants in NewTestPassword() to avoid drift if FIPS floor changes
https://claude.ai/code/session_01HmE9QkZM3cAoXn2J7XrK2f
* Rename FIPS test artifact to match server-ci-report pattern
The server-ci-report job searches for artifacts matching "*-test-logs",
so rename from postgres-server-test-logs-fips to
postgres-server-fips-test-logs to be included in the report.
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Rename shared_channel_manager and secure_connection_manager roles to use system_ prefix
The new roles added in PR #35354 broke the naming convention that all
system-level roles stored in Users.Roles are prefixed with "system_".
Client-side code (role.includes('system')) and server-side code (explicit
switch cases in applyMultiRoleFilters) relied on this convention, causing
users assigned to these roles to not appear in the System Console.
Also adds both roles to the applyMultiRoleFilters switch statement in
user_store.go, which was missing them entirely.
* Use multi-level logging for shared channel and remote cluster service errors
Service-specific log levels (LvlRemoteClusterServiceError, LvlSharedChannelServiceError)
were hidden from the main log by default, requiring explicit configuration to see them.
Switch all call sites to use LogM with multi-level combos so each log line is attributed
to both the standard level (error/warn) and the service-specific level. This surfaces
errors in the main log while preserving the ability to isolate them into dedicated files.
Each instance was reviewed and either kept as error (DB failures, security issues, config
errors, exhausted retries on critical data) or downgraded to warn (transient network
failures, remote-side reported errors with retry logic, non-critical data like profile
images, reactions, acknowledgements, and status).
* MM-68158: Fix shared channel remote display and add WebSocket notification
Fix getSharedChannelRemotes API handler passing ChannelId instead of
RemoteId to GetRemoteCluster, which always failed the lookup. Add
RemoteId to SharedChannelRemoteStatus model and store query.
Add shared_channel_remote_updated WebSocket event published from the
onInvite callback so the UI refreshes its cached remote names when the
async invite completes, instead of showing the generic "Shared with
trusted organizations" fallback.
* Improved unit tests per review comments
* Move password hashers from server/v8 to server/public to fix layering violation
* Revert "Move password hashers from server/v8 to server/public to fix layering violation"
This reverts commit 8cad5b8dc9.
* invert dependency between hashers and model
* make modules-tidy
---------
Co-authored-by: Jesse Hallam <jesse@mattermost.com>
Co-authored-by: Mattermost Build <build@mattermost.com>