Skip to content

fix(mattermost): tighten sanitizeActionId to alphanumeric-only, add empty-id and collision guards - #49920

Closed
kevins88288 wants to merge 1 commit into
openclaw:mainfrom
kevins88288:fix/mattermost-actionid-sanitization
Closed

kevins88288 wants to merge 1 commit into
openclaw:mainfrom
kevins88288:fix/mattermost-actionid-sanitization

Conversation

@kevins88288

Copy link
Copy Markdown

Summary

Fixes Mattermost interactive button 404s caused by action IDs containing (and other non-alphanumeric chars) used as URL path segments.

Spec: /home/ubuntu/workspace/metalab/specs/mattermost-actionid-sanitization/SPEC.md

Changes

interactions.ts

  • sanitizeActionId(): regex tightened from /[-_]/g to /[^a-zA-Z0-9]/g — strips colons, unicode, and all non-alphanumeric chars
  • Added shortHash() helper: first 8 hex chars of SHA-256 for deterministic fallback IDs
  • buildButtonAttachments(): empty-id fallback ("action" + shortHash(originalId)) when sanitization yields empty string
  • buildButtonAttachments(): within-message collision dedup via seenIds Set

interactions.test.ts

9 new test cases (57 total):

  • Strips colons: softgate:approve:0001 → softgateapprove0001
  • Strips hyphens/underscores (legacy preserved)
  • No-op on alphanumeric-only IDs
  • Unicode stripped: héllo → hllo
  • All-punct fallback: ::: → action{hash}
  • Empty ID fallback: "" → action{hash}
  • All produced IDs match /^[a-zA-Z0-9]+$/
  • actions[].id === integration.context.action_id invariant
  • Collision case: unique IDs produced for "a:b" and "ab"

Testing

All 57 tests pass. HMAC verification model unaffected (both send and receive paths use the sanitized safeId).

Rollout Note

After merge + deploy, Lucius owns #approval remediation: audit pending broken posts and re-post.

@kevins88288
kevins88288 requested a review from a team as a code owner March 18, 2026 16:41
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: discord Channel integration: discord channel: mattermost Channel integration: mattermost gateway Gateway runtime cli CLI command changes agents Agent runtime and tooling size: XL labels Mar 18, 2026
@greptile-apps

greptile-apps Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR tightens Mattermost action ID sanitization to strip all non-alphanumeric characters (previously only hyphens and underscores), adds a deterministic SHA-256 fallback for IDs that are empty post-sanitization, and introduces a seenIds dedup guard for within-message collisions. The core fix in interactions.ts/interactions.test.ts is well-implemented and thoroughly tested.

The PR also bundles several other changes (DM channel resolution refactor in send.ts, Slack/Telegram/Mattermost auto-threading helpers, plugin loader/runtime updates, etc.) that are not described in the title or summary.

Key findings:

  • dmChannelCache dead code (send.ts): The cache write (dmChannelCache.set(...)) was removed during the resolveDmChannelId refactor, making every user-DM send incur an extra createMattermostDirectChannel API call and making the dmChannelCache.clear() in the test helper a no-op. If intentional, the dead variable and its clear should be removed; if accidental, the write should be re-added inside resolveDmChannelId.
  • Two overlapping test cache-clearing exports (send.ts): resetMattermostSendCachesForTests and _testOnly_clearBotUserCache share 2 of 4 caches with no clear guidance on when to use each.
  • Counter fallback targets original safeId (interactions.ts): In the pathological hash-collision case the counter is appended to the pre-hash safeId ("ab2") rather than the hash candidate ("ab{hash}2"), which is functionally correct but less traceable.

Confidence Score: 3/5

  • The core sanitization fix is safe, but the DM caching removal in send.ts introduces a latent performance regression that should be confirmed as intentional before merging.
  • The sanitizeActionId fix and collision-guard logic in interactions.ts are correct and well-covered by tests. However, send.ts silently drops DM channel caching as a side-effect of the resolveDmChannelId refactor — every user-DM send now makes a redundant createMattermostDirectChannel API call. The PR also bundles 50+ other file changes that are undescribed in the title/summary, making it harder to reason about full impact.
  • extensions/mattermost/src/mattermost/send.ts — dmChannelCache is declared and cleared but never written to after the refactor.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/mattermost/src/mattermost/send.ts
Line: 55

Comment:
**`dmChannelCache` is declared but never written to**

`dmChannelCache` was populated by `dmChannelCache.set(dmKey, channel.id)` in the old `resolveTargetChannelId` code, but that write was removed when the logic was refactored into `resolveDmChannelId`. The new `resolveDmChannelId` function makes a fresh `createMattermostDirectChannel` call every time without writing to the cache. As a result, `dmChannelCache` is now dead state — the map is declared, cleared in `resetMattermostSendCachesForTests`, but never populated.

This has two side effects:
1. Every user-DM send now makes an extra `createMattermostDirectChannel` API call instead of returning a cached channel ID.
2. The `dmChannelCache.clear()` call in `resetMattermostSendCachesForTests` is a no-op.

If the caching was intentionally removed (e.g., stale-cache bugs), the dead variable and its clear should be removed too. If it was accidentally dropped, re-add caching inside `resolveDmChannelId`.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: extensions/mattermost/src/mattermost/send.ts
Line: 248-253

Comment:
**Two overlapping test-cache-clearing functions with different scopes**

This PR adds both `resetMattermostSendCachesForTests` (clears all 4 caches) and `_testOnly_clearBotUserCache` (clears only `botUserCache` + `userByNameCache`). Both are exported and their docstrings don't explain when to prefer one over the other. They also share 2 of the 4 caches (`botUserCache`, `userByNameCache`), making it easy to pick the wrong one and leave `channelByNameCache` or `dmChannelCache` dirty across tests.

Consider removing `_testOnly_clearBotUserCache` and using only `resetMattermostSendCachesForTests`, or clarifying in the docstrings exactly which scenarios call for each.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: extensions/mattermost/src/mattermost/interactions.ts
Line: 301-313

Comment:
**Counter fallback uses original `safeId`, not the hash candidate**

In the pathological counter branch, `safeId + String(counter)` is checked (e.g. `"ab2"`, `"ab3"`), not `candidate + String(counter)` (`"ab{hash}2"`). The while loop does correctly avoid already-seen IDs, but the resulting ID drops the hash entirely, so a counter-resolved ID looks identical to a naturally-occurring short ID and may cause confusion in logs or debugging. Consider using `candidate + String(counter)` to make the origin clearer:

```typescript
// Pathological: same hash collision, use counter
let counter = 2;
while (seenIds.has(candidate + String(counter))) {
  counter++;
}
safeId = candidate + String(counter);
```

How can I resolve this? If you propose a fix, please make it concise.

Last reviewed commit: "fix(mattermost): tig..."

const botUserCache = new Map<string, MattermostUser>();
const userByNameCache = new Map<string, MattermostUser>();
const channelByNameCache = new Map<string, string>();
const dmChannelCache = new Map<string, string>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 dmChannelCache is declared but never written to

dmChannelCache was populated by dmChannelCache.set(dmKey, channel.id) in the old resolveTargetChannelId code, but that write was removed when the logic was refactored into resolveDmChannelId. The new resolveDmChannelId function makes a fresh createMattermostDirectChannel call every time without writing to the cache. As a result, dmChannelCache is now dead state — the map is declared, cleared in resetMattermostSendCachesForTests, but never populated.

This has two side effects:

  1. Every user-DM send now makes an extra createMattermostDirectChannel API call instead of returning a cached channel ID.
  2. The dmChannelCache.clear() call in resetMattermostSendCachesForTests is a no-op.

If the caching was intentionally removed (e.g., stale-cache bugs), the dead variable and its clear should be removed too. If it was accidentally dropped, re-add caching inside resolveDmChannelId.

Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/mattermost/src/mattermost/send.ts
Line: 55

Comment:
**`dmChannelCache` is declared but never written to**

`dmChannelCache` was populated by `dmChannelCache.set(dmKey, channel.id)` in the old `resolveTargetChannelId` code, but that write was removed when the logic was refactored into `resolveDmChannelId`. The new `resolveDmChannelId` function makes a fresh `createMattermostDirectChannel` call every time without writing to the cache. As a result, `dmChannelCache` is now dead state — the map is declared, cleared in `resetMattermostSendCachesForTests`, but never populated.

This has two side effects:
1. Every user-DM send now makes an extra `createMattermostDirectChannel` API call instead of returning a cached channel ID.
2. The `dmChannelCache.clear()` call in `resetMattermostSendCachesForTests` is a no-op.

If the caching was intentionally removed (e.g., stale-cache bugs), the dead variable and its clear should be removed too. If it was accidentally dropped, re-add caching inside `resolveDmChannelId`.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +248 to 253

/** @internal — test-only, clears bot user cache between test runs */
export function _testOnly_clearBotUserCache(): void {
botUserCache.clear();
userByNameCache.clear();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Two overlapping test-cache-clearing functions with different scopes

This PR adds both resetMattermostSendCachesForTests (clears all 4 caches) and _testOnly_clearBotUserCache (clears only botUserCache + userByNameCache). Both are exported and their docstrings don't explain when to prefer one over the other. They also share 2 of the 4 caches (botUserCache, userByNameCache), making it easy to pick the wrong one and leave channelByNameCache or dmChannelCache dirty across tests.

Consider removing _testOnly_clearBotUserCache and using only resetMattermostSendCachesForTests, or clarifying in the docstrings exactly which scenarios call for each.

Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/mattermost/src/mattermost/send.ts
Line: 248-253

Comment:
**Two overlapping test-cache-clearing functions with different scopes**

This PR adds both `resetMattermostSendCachesForTests` (clears all 4 caches) and `_testOnly_clearBotUserCache` (clears only `botUserCache` + `userByNameCache`). Both are exported and their docstrings don't explain when to prefer one over the other. They also share 2 of the 4 caches (`botUserCache`, `userByNameCache`), making it easy to pick the wrong one and leave `channelByNameCache` or `dmChannelCache` dirty across tests.

Consider removing `_testOnly_clearBotUserCache` and using only `resetMattermostSendCachesForTests`, or clarifying in the docstrings exactly which scenarios call for each.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +301 to +313
if (seenIds.has(safeId)) {
const candidate = safeId + shortHash(btn.id);
if (!seenIds.has(candidate)) {
safeId = candidate;
} else {
// Pathological: same hash collision, use counter
let counter = 2;
while (seenIds.has(safeId + String(counter))) {
counter++;
}
safeId = safeId + String(counter);
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Counter fallback uses original safeId, not the hash candidate

In the pathological counter branch, safeId + String(counter) is checked (e.g. "ab2", "ab3"), not candidate + String(counter) ("ab{hash}2"). The while loop does correctly avoid already-seen IDs, but the resulting ID drops the hash entirely, so a counter-resolved ID looks identical to a naturally-occurring short ID and may cause confusion in logs or debugging. Consider using candidate + String(counter) to make the origin clearer:

// Pathological: same hash collision, use counter
let counter = 2;
while (seenIds.has(candidate + String(counter))) {
  counter++;
}
safeId = candidate + String(counter);
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/mattermost/src/mattermost/interactions.ts
Line: 301-313

Comment:
**Counter fallback uses original `safeId`, not the hash candidate**

In the pathological counter branch, `safeId + String(counter)` is checked (e.g. `"ab2"`, `"ab3"`), not `candidate + String(counter)` (`"ab{hash}2"`). The while loop does correctly avoid already-seen IDs, but the resulting ID drops the hash entirely, so a counter-resolved ID looks identical to a naturally-occurring short ID and may cause confusion in logs or debugging. Consider using `candidate + String(counter)` to make the origin clearer:

```typescript
// Pathological: same hash collision, use counter
let counter = 2;
while (seenIds.has(candidate + String(counter))) {
  counter++;
}
safeId = candidate + String(counter);
```

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cea334c6af

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +12 to +13
// Mattermost server MaxPostSize limit — matches the textChunkLimit in channel.ts outbound config.
export const MATTERMOST_DEFAULT_CHUNK_LIMIT = 50000;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Restore Mattermost chunk limit below server MaxPostSize

This constant now feeds outbound chunking through extensions/mattermost/src/channel.ts and src/channels/plugins/outbound/direct-text-media.ts:84. With MATTERMOST_DEFAULT_CHUNK_LIMIT raised to 50000, any reply between ~16k and 50k chars is emitted as a single post, but extensions/mattermost/AGENTS.md still documents the deployed Mattermost MaxPostSize as 16383. In that environment, long agent replies will now fail with 400s instead of being split safely.

Useful? React with 👍 / 👎.

Comment thread src/config/validation.ts Outdated
Comment on lines +516 to +517
if (!knownIds.has(pluginId)) {
pushMissingPluginIssue("plugins.allow", pluginId);
pushMissingPluginIssue("plugins.allow", pluginId, { warnOnly: true });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Keep unknown allowlist plugin ids as hard validation errors

Downgrading missing plugins.allow ids to warnings makes typos look valid even though resolveEnableState in src/plugins/config-state.ts:256 treats any non-empty allowlist as authoritative and disables every plugin that is not explicitly named. A config such as plugins.allow: ["memroy-core"] will now pass validation but silently turn off workspace plugins and other non-listed plugins until the typo is discovered.

Useful? React with 👍 / 👎.

Comment thread src/config/validation.ts Outdated
Comment on lines +539 to +542
memorySlot.trim() &&
!knownIds.has(memorySlot)
) {
pushMissingPluginIssue("plugins.slots.memory", memorySlot);
pushMissingPluginIssue("plugins.slots.memory", memorySlot, { warnOnly: true });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Reject unknown memory slot ids instead of warning only

Making plugins.slots.memory warn-only has the same problem for memory selection: resolveMemorySlotDecision in src/plugins/config-state.ts:319 disables every memory plugin whenever the slot contains some other string. So a typo like slots.memory: memory-cor now boots successfully but leaves memory completely unavailable, which is a much harder failure mode than the previous validation error.

Useful? React with 👍 / 👎.

Comment thread src/providers/gcp-adc-token.ts Outdated
Comment on lines +32 to +36
const cachePath = resolveGcpAdcTokenCachePath(env);
const cached = loadJsonFile(cachePath) as CachedGcpAdcToken | undefined;

// Return cached token if still valid
if (cached && typeof cached.token === "string" && typeof cached.expiresAt === "number") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Scope GCP ADC cache to the actual credential source

The new ADC cache is keyed only by resolveStateDir(env) and is returned before GoogleAuth is consulted. On hosts that reuse one ~/.openclaw while switching GOOGLE_APPLICATION_CREDENTIALS, gcloud ADC accounts, or other ADC sources between runs, the second run will keep using the first account's bearer token until it expires. That means requests can be sent under the wrong GCP principal for up to an hour.

Useful? React with 👍 / 👎.

…mpty-id and collision guards

- sanitizeActionId: /[^a-zA-Z0-9]/g (was /[-_]/g)
- buildButtonAttachments: deterministic fallback ("action"+shortHash) for empty safeId
- buildButtonAttachments: within-message dedup via seenIds set
- Tests: colon strip, hyphen/underscore, no-op, unicode, empty fallback, all-punct fallback, all-alnum invariant, id===action_id, collision uniqueness

Fixes: softgate:approve:* style IDs returning 404 from Mattermost router
Spec: /home/ubuntu/workspace/metalab/specs/mattermost-actionid-sanitization/SPEC.md

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@kevins88288
kevins88288 force-pushed the fix/mattermost-actionid-sanitization branch from cea334c to 8efe3f3 Compare March 18, 2026 17:21
@openclaw-barnacle openclaw-barnacle Bot added size: S and removed docs Improvements or additions to documentation channel: discord Channel integration: discord gateway Gateway runtime cli CLI command changes agents Agent runtime and tooling size: XL labels Mar 18, 2026
@kevins88288

Copy link
Copy Markdown
Author

Closing — opened in error. Should never target upstream openclaw/openclaw.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: mattermost Channel integration: mattermost size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant