@terreno/api 57.10.1 → 57.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -284,7 +284,18 @@ describe("query and list methods", () => {
284
284
  it("list query params not in list", async () => {
285
285
  const res = await agent.get(`/food?ownerId=${admin._id}`).expect(400);
286
286
  expect(res.body.title).toBe("Query parameter not allowed");
287
- expect(res.body.detail).toBe("ownerId is not allowed as a query param.");
287
+ expect(res.body.detail).toContain("ownerId is not allowed as a query param.");
288
+ });
289
+
290
+ it("names the model and allowed queryFields when a filter field is missing", async () => {
291
+ const res = await agent.get(`/food?ownerId=${admin._id}`).expect(400);
292
+ expect(res.body.code).toBe("query-param-not-allowed");
293
+ expect(res.body.source).toEqual({parameter: "ownerId"});
294
+ expect(res.body.detail).toContain('Add "ownerId" to queryFields on the Food modelRouter');
295
+ expect(res.body.meta.queryParam).toBe("ownerId");
296
+ expect(res.body.meta.model).toBe("Food");
297
+ expect(Array.isArray(res.body.meta.allowedQueryFields)).toBe(true);
298
+ expect(res.body.meta.allowedQueryFields).not.toContain("ownerId");
288
299
  });
289
300
 
290
301
  it("list query by nested param", async () => {
@@ -487,18 +498,18 @@ describe("query and list methods", () => {
487
498
  .get(`/food?${qs.stringify({$and: [{ownerId: "healthy"}, {tags: "cheap"}]})}`)
488
499
  .expect(400);
489
500
  expect(res.body.title).toBe("Query parameter not allowed");
490
- expect(res.body.detail).toBe("ownerId is not allowed as a query param.");
501
+ expect(res.body.detail).toContain("ownerId is not allowed as a query param.");
491
502
  res = await agent
492
503
  .get(`/food?${qs.stringify({$and: [{tags: "cheap"}, {ownerId: "healthy"}]})}`)
493
504
  .expect(400);
494
505
  expect(res.body.title).toBe("Query parameter not allowed");
495
- expect(res.body.detail).toBe("ownerId is not allowed as a query param.");
506
+ expect(res.body.detail).toContain("ownerId is not allowed as a query param.");
496
507
 
497
508
  res = await agent
498
509
  .get(`/food?${qs.stringify({$or: [{tags: "cheap"}, {ownerId: "healthy"}]})}`)
499
510
  .expect(400);
500
511
  expect(res.body.title).toBe("Query parameter not allowed");
501
- expect(res.body.detail).toBe("ownerId is not allowed as a query param.");
512
+ expect(res.body.detail).toContain("ownerId is not allowed as a query param.");
502
513
  });
503
514
 
504
515
  it("query with a number", async () => {
package/src/api.ts CHANGED
@@ -496,10 +496,13 @@ const mergeDateRangeQueryParams = <T>(
496
496
  };
497
497
 
498
498
  // Ensures query params are allowed. Also checks nested query params when using $and/$or.
499
+ // The error names the field, the model, and the allowed list so a missing `queryFields`
500
+ // entry is obvious from the client (syncdb raises it as QueryFieldNotAllowedError).
499
501
  const checkQueryParamAllowed = (
500
502
  queryParam: string,
501
503
  queryParamValue: unknown,
502
- queryFields: string[] = []
504
+ queryFields: string[] = [],
505
+ modelName = "this model"
503
506
  ) => {
504
507
  // Cast for iteration through complex query values
505
508
  const complexValue = queryParamValue as Array<Record<string, unknown>>;
@@ -509,15 +512,20 @@ const checkQueryParamAllowed = (
509
512
  // Complex query of the form `$and: [{key1: value1}, {key2: value2}]`
510
513
  for (const subQuery of complexValue) {
511
514
  for (const subKey of Object.keys(subQuery)) {
512
- checkQueryParamAllowed(subKey, subQuery[subKey], queryFields);
515
+ checkQueryParamAllowed(subKey, subQuery[subKey], queryFields, modelName);
513
516
  }
514
517
  }
515
518
  return;
516
519
  }
517
520
  if (!queryFields.includes(queryParam)) {
521
+ const allowed = queryFields.length > 0 ? queryFields.join(", ") : "(none)";
518
522
  throw new BadRequestError({
519
523
  code: "query-param-not-allowed",
520
- detail: `${queryParam} is not allowed as a query param.`,
524
+ detail:
525
+ `${queryParam} is not allowed as a query param. ` +
526
+ `Add "${queryParam}" to queryFields on the ${modelName} modelRouter to filter on it. ` +
527
+ `Allowed: ${allowed}.`,
528
+ meta: {allowedQueryFields: [...queryFields], model: modelName, queryParam},
521
529
  source: {parameter: queryParam},
522
530
  title: "Query parameter not allowed",
523
531
  });
@@ -829,6 +837,22 @@ const _buildModelRouter = <T>(
829
837
  authenticateMiddleware(options.allowAnonymous),
830
838
  permissionMiddleware(model, options),
831
839
  listOpenApiMiddleware(model, options, routePath),
840
+ // Runs before query validation so a field missing from queryFields is always
841
+ // reported with this error, whatever the validator's settings.
842
+ (req: Request, _res: Response, next: NextFunction): void => {
843
+ for (const queryParam of Object.keys(req.query)) {
844
+ if (PAGINATION_QUERY_PARAMS.includes(queryParam)) {
845
+ continue;
846
+ }
847
+ checkQueryParamAllowed(
848
+ queryParam,
849
+ req.query[queryParam],
850
+ options.queryFields,
851
+ model.modelName
852
+ );
853
+ }
854
+ next();
855
+ },
832
856
  queryValidation,
833
857
  ],
834
858
  asyncHandler(async (req: Request, res: Response) => {
@@ -841,7 +865,12 @@ const _buildModelRouter = <T>(
841
865
  if (PAGINATION_QUERY_PARAMS.includes(queryParam)) {
842
866
  continue;
843
867
  }
844
- checkQueryParamAllowed(queryParam, req.query[queryParam], options.queryFields);
868
+ checkQueryParamAllowed(
869
+ queryParam,
870
+ req.query[queryParam],
871
+ options.queryFields,
872
+ model.modelName
873
+ );
845
874
 
846
875
  // Not sure if this is necessary or if mongoose does the right thing.
847
876
  if (req.query[queryParam] === "true") {
package/src/index.ts CHANGED
@@ -118,6 +118,7 @@ export {
118
118
  } from "./notifications/notificationsBeforeSend";
119
119
  export * from "./notifiers/googleChatNotifier";
120
120
  export * from "./notifiers/slackNotifier";
121
+ export * from "./notifiers/slackWebApi";
121
122
  export * from "./notifiers/zoomNotifier";
122
123
  export * from "./openApiBuilder";
123
124
  export * from "./openApiCompat";
@@ -0,0 +1,357 @@
1
+ import {afterEach, beforeEach, describe, expect, it, type Mock, spyOn} from "bun:test";
2
+ import * as Sentry from "@sentry/bun";
3
+ import axios from "axios";
4
+
5
+ import {APIError, isAPIError} from "../errors";
6
+ import {
7
+ createSlackPrivateChannel,
8
+ findSlackChannelByName,
9
+ inviteSlackUsersToChannel,
10
+ normalizeSlackChannelName,
11
+ postSlackMessage,
12
+ } from "./slackWebApi";
13
+
14
+ describe("normalizeSlackChannelName", () => {
15
+ it("lowercases and trims a valid channel name", () => {
16
+ expect(normalizeSlackChannelName(" Case-Room_1 ")).toBe("case-room_1");
17
+ });
18
+
19
+ it("rejects names Slack will not accept", () => {
20
+ expect(() => normalizeSlackChannelName("case room")).toThrow(APIError);
21
+ expect(() => normalizeSlackChannelName("---")).toThrow(APIError);
22
+ });
23
+ });
24
+
25
+ describe("Slack Web API", () => {
26
+ let mockAxiosPost: Mock<typeof axios.post>;
27
+ let mockAxiosGet: Mock<typeof axios.get>;
28
+
29
+ beforeEach(() => {
30
+ mockAxiosPost = spyOn(axios, "post");
31
+ mockAxiosGet = spyOn(axios, "get");
32
+ process.env.SLACK_BOT_TOKEN = "xoxb-test";
33
+ (Sentry.captureException as Mock<typeof Sentry.captureException>).mockClear();
34
+ });
35
+
36
+ afterEach(() => {
37
+ mockAxiosPost.mockRestore();
38
+ mockAxiosGet.mockRestore();
39
+ Reflect.deleteProperty(process.env, "SLACK_BOT_TOKEN");
40
+ });
41
+
42
+ it("creates a private channel, invites members, and posts the first message", async () => {
43
+ mockAxiosPost.mockImplementation(async (url: string, body: {name?: string; text?: string}) => {
44
+ if (String(url).endsWith("conversations.create")) {
45
+ return {
46
+ data: {channel: {id: "C012345678", is_private: true, name: body.name}, ok: true},
47
+ status: 200,
48
+ };
49
+ }
50
+ if (String(url).endsWith("conversations.invite")) {
51
+ return {data: {ok: true}, status: 200};
52
+ }
53
+ return {data: {channel: "C012345678", ok: true, ts: "1503435956.000247"}, status: 200};
54
+ });
55
+
56
+ const created = await createSlackPrivateChannel({
57
+ initialMessage: "Case opened",
58
+ mentionUserIds: ["U012ABCDEF"],
59
+ name: "Case-123",
60
+ userIds: ["U012ABCDEF", "not-a-slack-id"],
61
+ });
62
+
63
+ expect(created).toEqual({
64
+ channelId: "C012345678",
65
+ invites: {
66
+ alreadyMemberUserIds: [],
67
+ failures: [{error: "invalid_user_id", userId: "not-a-slack-id"}],
68
+ invitedUserIds: ["U012ABCDEF"],
69
+ },
70
+ messageTs: "1503435956.000247",
71
+ name: "case-123",
72
+ });
73
+ const createBody = mockAxiosPost.mock.calls[0]?.[1] as {is_private?: boolean; name?: string};
74
+ expect(createBody).toEqual({is_private: true, name: "case-123"});
75
+ const messageBody = mockAxiosPost.mock.calls[2]?.[1] as {text?: string};
76
+ expect(messageBody.text).toBe("<@U012ABCDEF> Case opened");
77
+ });
78
+
79
+ it("throws 409 when the channel name is taken", async () => {
80
+ mockAxiosPost.mockResolvedValue({data: {error: "name_taken", ok: false}, status: 200});
81
+
82
+ try {
83
+ await createSlackPrivateChannel({name: "case-123"});
84
+ throw new Error("Expected createSlackPrivateChannel to throw");
85
+ } catch (error) {
86
+ expect(isAPIError(error)).toBe(true);
87
+ expect((error as APIError).status).toBe(409);
88
+ expect((error as APIError).title).toBe("Slack channel name is already taken");
89
+ }
90
+ });
91
+
92
+ it("keeps the new channel id when the initial message fails", async () => {
93
+ mockAxiosPost.mockImplementation(async (url: string) => {
94
+ if (String(url).endsWith("conversations.create")) {
95
+ return {data: {channel: {id: "C012345678", name: "case-123"}, ok: true}, status: 200};
96
+ }
97
+ return {data: {error: "not_in_channel", ok: false}, status: 200};
98
+ });
99
+
100
+ try {
101
+ await createSlackPrivateChannel({initialMessage: "hello", name: "case-123"});
102
+ throw new Error("Expected createSlackPrivateChannel to throw");
103
+ } catch (error) {
104
+ expect(isAPIError(error)).toBe(true);
105
+ expect((error as APIError).title).toBe("Slack initial message failed");
106
+ expect((error as APIError).meta?.channelId).toBe("C012345678");
107
+ }
108
+ });
109
+
110
+ it("reports members who are already in the channel", async () => {
111
+ mockAxiosPost.mockResolvedValue({
112
+ data: {error: "already_in_channel", ok: false},
113
+ status: 200,
114
+ });
115
+
116
+ const result = await inviteSlackUsersToChannel({
117
+ channelId: "c012345678",
118
+ userIds: ["<@U012ABCDEF>", "U012ABCDEF"],
119
+ });
120
+
121
+ expect(result.alreadyMemberUserIds).toEqual(["U012ABCDEF"]);
122
+ expect(result.invitedUserIds).toEqual([]);
123
+ const body = mockAxiosPost.mock.calls[0]?.[1] as {channel?: string; users?: string};
124
+ expect(body).toEqual({channel: "C012345678", force: true, users: "U012ABCDEF"});
125
+ });
126
+
127
+ it("returns per-user invite failures without failing the whole call", async () => {
128
+ mockAxiosPost.mockResolvedValue({
129
+ data: {
130
+ error: "user_not_found",
131
+ errors: [{error: "user_not_found", user: "U012ABCDEF"}],
132
+ ok: false,
133
+ },
134
+ status: 200,
135
+ });
136
+
137
+ const result = await inviteSlackUsersToChannel({
138
+ channelId: "C012345678",
139
+ userIds: ["U012ABCDEF", "W0ENTERPR1"],
140
+ });
141
+
142
+ expect(result.failures).toEqual([{error: "user_not_found", userId: "U012ABCDEF"}]);
143
+ expect(result.invitedUserIds).toEqual([]);
144
+ });
145
+
146
+ it("throws when the bot is not in an existing private channel", async () => {
147
+ mockAxiosPost.mockResolvedValue({data: {error: "not_in_channel", ok: false}, status: 200});
148
+
149
+ try {
150
+ await inviteSlackUsersToChannel({channelId: "C012345678", userIds: ["U012ABCDEF"]});
151
+ throw new Error("Expected inviteSlackUsersToChannel to throw");
152
+ } catch (error) {
153
+ expect(isAPIError(error)).toBe(true);
154
+ expect((error as APIError).detail).toContain("not_in_channel");
155
+ }
156
+ });
157
+
158
+ it("posts blocks and mention tokens to a channel", async () => {
159
+ mockAxiosPost.mockResolvedValue({
160
+ data: {channel: "C012345678", ok: true, ts: "1.2"},
161
+ status: 200,
162
+ });
163
+
164
+ const posted = await postSlackMessage({
165
+ blocks: [{type: "section"}],
166
+ channelId: "C012345678",
167
+ mentionUserIds: ["U012ABCDEF"],
168
+ text: "Update",
169
+ });
170
+
171
+ expect(posted).toEqual({channelId: "C012345678", messageTs: "1.2"});
172
+ expect(mockAxiosPost.mock.calls[0]?.[1]).toEqual({
173
+ blocks: [{type: "section"}],
174
+ channel: "C012345678",
175
+ text: "<@U012ABCDEF> Update",
176
+ });
177
+ });
178
+
179
+ it("retries a rate-limited post and then succeeds", async () => {
180
+ const rateLimited = Object.assign(new Error("429"), {
181
+ isAxiosError: true,
182
+ response: {headers: {"retry-after": "0"}, status: 429},
183
+ });
184
+ mockAxiosPost
185
+ .mockRejectedValueOnce(rateLimited)
186
+ .mockResolvedValueOnce({data: {ok: true, ts: "9.9"}, status: 200});
187
+
188
+ const posted = await postSlackMessage({channelId: "C012345678", text: "again"});
189
+ expect(posted.messageTs).toBe("9.9");
190
+ expect(mockAxiosPost.mock.calls.length).toBe(2);
191
+ });
192
+
193
+ it("finds a channel on a later page", async () => {
194
+ mockAxiosGet
195
+ .mockResolvedValueOnce({
196
+ data: {
197
+ channels: [{id: "C000000001", name: "other"}],
198
+ ok: true,
199
+ response_metadata: {next_cursor: "page-2"},
200
+ },
201
+ status: 200,
202
+ })
203
+ .mockResolvedValueOnce({
204
+ data: {
205
+ channels: [{id: "C012345678", is_private: true, name_normalized: "case-123"}],
206
+ ok: true,
207
+ response_metadata: {next_cursor: ""},
208
+ },
209
+ status: 200,
210
+ });
211
+
212
+ const found = await findSlackChannelByName({name: "case-123"});
213
+ expect(found).toEqual({channelId: "C012345678", isPrivate: true, name: "case-123"});
214
+ const firstParams = mockAxiosGet.mock.calls[0]?.[1] as {params?: {types?: string}};
215
+ expect(firstParams.params?.types).toBe("public_channel,private_channel");
216
+ });
217
+
218
+ it("returns undefined when no visible channel has that name", async () => {
219
+ mockAxiosGet.mockResolvedValue({
220
+ data: {channels: [], ok: true, response_metadata: {next_cursor: ""}},
221
+ status: 200,
222
+ });
223
+
224
+ expect(await findSlackChannelByName({name: "missing"})).toBeUndefined();
225
+ });
226
+
227
+ it("throws when the bot token is missing", async () => {
228
+ Reflect.deleteProperty(process.env, "SLACK_BOT_TOKEN");
229
+
230
+ try {
231
+ await postSlackMessage({channelId: "C012345678", text: "hi"});
232
+ throw new Error("Expected postSlackMessage to throw");
233
+ } catch (error) {
234
+ expect(isAPIError(error)).toBe(true);
235
+ expect((error as APIError).title).toBe("SLACK_BOT_TOKEN is not set");
236
+ }
237
+ expect(mockAxiosPost.mock.calls.length).toBe(0);
238
+ });
239
+
240
+ it("returns the channel without posting when there is no initial message", async () => {
241
+ mockAxiosPost.mockResolvedValue({
242
+ data: {channel: {id: "C012345678", name: "case-123"}, ok: true},
243
+ status: 200,
244
+ });
245
+
246
+ const created = await createSlackPrivateChannel({name: "case-123"});
247
+ expect(created.messageTs).toBeUndefined();
248
+ expect(mockAxiosPost.mock.calls.length).toBe(1);
249
+ });
250
+
251
+ it("rejects invites that contain no Slack member ids", async () => {
252
+ await expect(
253
+ createSlackPrivateChannel({name: "case-123", userIds: ["jane@example.com"]})
254
+ ).rejects.toBeInstanceOf(APIError);
255
+ await expect(
256
+ inviteSlackUsersToChannel({channelId: "C012345678", userIds: ["jane"]})
257
+ ).rejects.toBeInstanceOf(APIError);
258
+ await expect(postSlackMessage({channelId: "not-a-channel", text: "hi"})).rejects.toBeInstanceOf(
259
+ APIError
260
+ );
261
+ await expect(postSlackMessage({channelId: "C012345678", text: " "})).rejects.toBeInstanceOf(
262
+ APIError
263
+ );
264
+ expect(mockAxiosPost.mock.calls.length).toBe(0);
265
+ });
266
+
267
+ it("keeps the channel id when inviting into the new channel fails", async () => {
268
+ mockAxiosPost.mockImplementation(async (url: string) => {
269
+ if (String(url).endsWith("conversations.create")) {
270
+ return {data: {channel: {id: "C012345678", name: "case-123"}, ok: true}, status: 200};
271
+ }
272
+ return {data: {error: "not_in_channel", ok: false}, status: 200};
273
+ });
274
+
275
+ try {
276
+ await createSlackPrivateChannel({name: "case-123", userIds: ["U012ABCDEF"]});
277
+ throw new Error("Expected createSlackPrivateChannel to throw");
278
+ } catch (error) {
279
+ expect((error as APIError).meta?.channelId).toBe("C012345678");
280
+ expect((error as APIError).detail).toContain("not_in_channel");
281
+ }
282
+ });
283
+
284
+ it("throws when Slack omits the new channel id or the message timestamp", async () => {
285
+ mockAxiosPost.mockResolvedValueOnce({data: {channel: {}, ok: true}, status: 200});
286
+ await expect(createSlackPrivateChannel({name: "case-123"})).rejects.toMatchObject({
287
+ title: "Slack API request failed",
288
+ });
289
+
290
+ mockAxiosPost.mockResolvedValueOnce({data: {ok: true}, status: 200});
291
+ await expect(postSlackMessage({channelId: "C012345678", text: "hi"})).rejects.toMatchObject({
292
+ code: "slack-message-missing",
293
+ });
294
+ });
295
+
296
+ it("counts partial invite results and skips blank error entries", async () => {
297
+ mockAxiosPost.mockResolvedValue({
298
+ data: {
299
+ errors: [
300
+ {error: "already_in_channel", user: "U012ABCDEF"},
301
+ {user: " "},
302
+ {user: "W0ENTERPR1"},
303
+ ],
304
+ ok: true,
305
+ },
306
+ status: 200,
307
+ });
308
+
309
+ const result = await inviteSlackUsersToChannel({
310
+ channelId: "C012345678",
311
+ userIds: ["U012ABCDEF", "W0ENTERPR1", "U33333333", "jane"],
312
+ });
313
+
314
+ expect(result.alreadyMemberUserIds).toEqual(["U012ABCDEF"]);
315
+ expect(result.failures).toEqual([
316
+ {error: "invalid_user_id", userId: "jane"},
317
+ {error: "unknown_error", userId: "W0ENTERPR1"},
318
+ ]);
319
+ expect(result.invitedUserIds).toEqual(["U33333333"]);
320
+ });
321
+
322
+ it("retries an HTTP 200 rate limit and a transport failure exhausts attempts", async () => {
323
+ mockAxiosPost
324
+ .mockResolvedValueOnce({
325
+ data: {error: "ratelimited", ok: false},
326
+ headers: {get: (name: string) => (name === "retry-after" ? "0.001" : undefined)},
327
+ status: 200,
328
+ })
329
+ .mockResolvedValueOnce({data: {ok: true, ts: "4.4"}, status: 200});
330
+
331
+ const posted = await postSlackMessage({
332
+ channelId: "C012345678",
333
+ mentionUserIds: ["not-an-id"],
334
+ text: "later",
335
+ });
336
+ expect(posted.messageTs).toBe("4.4");
337
+
338
+ mockAxiosPost.mockReset();
339
+ mockAxiosPost.mockRejectedValue(new Error("network down"));
340
+ await expect(postSlackMessage({channelId: "C012345678", text: "later"})).rejects.toMatchObject({
341
+ code: "slack-transport-failed",
342
+ });
343
+ expect(
344
+ (Sentry.captureException as Mock<typeof Sentry.captureException>).mock.calls.length
345
+ ).toBeGreaterThan(0);
346
+ });
347
+
348
+ it("stops paging when Slack never ends the channel list", async () => {
349
+ mockAxiosGet.mockResolvedValue({
350
+ data: {channels: [{name: "other"}], ok: true, response_metadata: {next_cursor: "next"}},
351
+ status: 200,
352
+ });
353
+
354
+ expect(await findSlackChannelByName({name: "case-123"})).toBeUndefined();
355
+ expect(mockAxiosGet.mock.calls.length).toBe(25);
356
+ });
357
+ });