Skip to content

Commit 702f0c6

Browse files
committed
refactor(mattermost): streamline API path validation
1 parent ff6f374 commit 702f0c6

1 file changed

Lines changed: 11 additions & 37 deletions

File tree

  • extensions/mattermost/src/mattermost

‎extensions/mattermost/src/mattermost/client.ts‎

Lines changed: 11 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -91,48 +91,22 @@ export function normalizeMattermostBaseUrl(raw?: string | null): string | undefi
9191
return withoutTrailing.replace(/\/api\/v4$/i, "");
9292
}
9393

94-
function decodeMattermostPathSegment(segment: string): string | undefined {
95-
try {
96-
return decodeURIComponent(segment);
97-
} catch {
98-
return undefined;
99-
}
100-
}
101-
102-
function stripMattermostUrlIgnoredPathControls(value: string): string {
103-
return value.replace(/[\t\r\n]/g, "");
104-
}
105-
106-
function mattermostPathnameForSegmentValidation(path: string): string {
107-
const withoutQueryOrFragment = path.split(/[?#]/, 1)[0] ?? "";
108-
return stripMattermostUrlIgnoredPathControls(withoutQueryOrFragment).replace(/\\/g, "/");
109-
}
110-
111-
function containsMattermostUnsafePathSegment(path: string): boolean {
112-
const pathname = mattermostPathnameForSegmentValidation(path);
113-
const suffix = pathname.startsWith("/") ? pathname : `/${pathname}`;
114-
return suffix.split("/").some((segment) => {
115-
if (segment === "." || segment === "..") {
116-
return true;
117-
}
118-
const decodedSegment = decodeMattermostPathSegment(segment);
119-
if (decodedSegment == null) {
120-
return true;
121-
}
122-
const decoded = stripMattermostUrlIgnoredPathControls(decodedSegment);
123-
return decoded.split(/[\\/]/).some((decodedComponent) => {
124-
return decodedComponent === "." || decodedComponent === "..";
125-
});
126-
});
127-
}
128-
12994
export function buildMattermostApiUrl(baseUrl: string, path: string): string {
13095
const normalized = normalizeMattermostBaseUrl(baseUrl);
13196
if (!normalized) {
13297
throw new Error("Mattermost baseUrl is required");
13398
}
134-
if (containsMattermostUnsafePathSegment(path)) {
135-
throw new Error("Mattermost API path must not contain unsafe path segments");
99+
const pathname = (path.split(/[?#]/, 1)[0] ?? "").replace(/[\t\r\n]/g, "").replace(/\\/g, "/");
100+
for (const segment of pathname.split("/")) {
101+
let decoded: string;
102+
try {
103+
decoded = decodeURIComponent(segment).replace(/[\t\r\n]/g, "");
104+
} catch {
105+
throw new Error("Mattermost API path must not contain unsafe path segments");
106+
}
107+
if (decoded.split(/[\\/]/).some((part) => part === "." || part === "..")) {
108+
throw new Error("Mattermost API path must not contain unsafe path segments");
109+
}
136110
}
137111
const suffix = path.startsWith("/") ? path : `/${path}`;
138112
return `${normalized}/api/v4${suffix}`;

0 commit comments

Comments
 (0)