@oneuptime/common 12.0.20 → 12.0.22

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.
Files changed (119) hide show
  1. package/Models/AnalyticsModels/ChangeEvent.ts +331 -0
  2. package/Models/AnalyticsModels/Index.ts +2 -0
  3. package/Models/DatabaseModels/Index.ts +2 -0
  4. package/Models/DatabaseModels/UserTwoFactorBackupCode.ts +262 -0
  5. package/Server/API/UserTwoFactorBackupCodeAPI.ts +258 -0
  6. package/Server/EnvironmentConfig.ts +1 -8
  7. package/Server/Infrastructure/Postgres/SchemaMigrations/1789000000000-AddUserSlackAndMicrosoftTeams.ts +42 -0
  8. package/Server/Infrastructure/Postgres/SchemaMigrations/1789100000000-AddUserTwoFactorBackupCode.ts +63 -0
  9. package/Server/Infrastructure/Postgres/SchemaMigrations/Index.ts +2 -2
  10. package/Server/Services/ChangeEventService.ts +11 -0
  11. package/Server/Services/EnterpriseLicenseService.ts +3 -3
  12. package/Server/Services/Index.ts +4 -0
  13. package/Server/Services/UserService.ts +42 -0
  14. package/Server/Services/UserTwoFactorBackupCodeService.ts +355 -0
  15. package/Server/Utils/Attribution.ts +11 -11
  16. package/Server/Utils/Marketing/MarketingEventWebhook.ts +4 -5
  17. package/Server/Utils/Telemetry/ChangeEventRow.ts +228 -0
  18. package/Server/Utils/TwoFactorBackupCode.ts +266 -0
  19. package/Server/Views/Partials/AnalyticsConsent.ejs +3 -95
  20. package/Tests/App/Dashboard/DashboardChartWidgetZoom.test.tsx +64 -0
  21. package/Tests/App/Dashboard/EventOverlayHook.test.tsx +249 -0
  22. package/Tests/App/Dashboard/InvestigationArtifacts.test.tsx +315 -0
  23. package/Tests/App/Dashboard/InvestigationDrawer.test.tsx +258 -0
  24. package/Tests/App/Dashboard/MetricChartsCompare.test.tsx +171 -0
  25. package/Tests/App/Dashboard/MetricViewCompare.test.tsx +233 -0
  26. package/Tests/Server/API/UserAuthenticationAPI.test.ts +16 -3
  27. package/Tests/Server/API/UserTwoFactorAuthAdminAPI.test.ts +18 -2
  28. package/Tests/Server/API/UserTwoFactorBackupCodeAPI.test.ts +1390 -0
  29. package/Tests/Server/Infrastructure/Postgres/AddUserSlackAndMicrosoftTeamsMigration.test.ts +236 -0
  30. package/Tests/Server/Services/UserAuthenticationService.test.ts +23 -1
  31. package/Tests/Server/Services/UserTwoFactorAuthAdmin.test.ts +21 -0
  32. package/Tests/Server/Services/UserTwoFactorBackupCodeAdminSurface.test.ts +919 -0
  33. package/Tests/Server/Services/UserTwoFactorBackupCodeService.test.ts +862 -0
  34. package/Tests/Server/Utils/AI/SRE/Insights/Detectors/ExceptionIdentity.test.ts +224 -0
  35. package/Tests/Server/Utils/Attribution.test.ts +4 -5
  36. package/Tests/Server/Utils/Marketing/MarketingEventUtil.test.ts +2 -2
  37. package/Tests/Server/Utils/Monitor/MonitorCriteriaExpectationBuilder.test.ts +300 -0
  38. package/Tests/Server/Utils/TwoFactorBackupCode.test.ts +475 -0
  39. package/Tests/UI/Components/Charts/ChartGhostSeries.test.tsx +103 -0
  40. package/Tests/UI/Components/Charts/TooltipEntries.test.ts +44 -8
  41. package/Tests/Utils/Telemetry/CrossSignalScope.test.ts +13 -2
  42. package/Types/AnalyticsDatabase/AnalyticsTableName.ts +7 -0
  43. package/Types/Email/EmailTemplateType.ts +2 -0
  44. package/Types/Marketing/Attribution.ts +9 -15
  45. package/Types/Marketing/MarketingEvent.ts +10 -46
  46. package/Types/UserAuthenticationStatus.ts +16 -0
  47. package/UI/Components/Charts/Area/AreaChart.tsx +15 -0
  48. package/UI/Components/Charts/ChartGroup/ChartGroup.tsx +16 -1
  49. package/UI/Components/Charts/ChartLibrary/AreaChart/AreaChart.tsx +189 -93
  50. package/UI/Components/Charts/ChartLibrary/BarChart/BarChart.tsx +6 -1
  51. package/UI/Components/Charts/ChartLibrary/LineChart/LineChart.tsx +213 -114
  52. package/UI/Components/Charts/ChartLibrary/Utils/TooltipEntries.ts +42 -27
  53. package/UI/Components/Charts/Line/LineChart.tsx +15 -0
  54. package/Utils/Metrics/MetricExplorerUrl.ts +119 -5
  55. package/Utils/Telemetry/CrossSignalScope.ts +19 -10
  56. package/build/dist/Models/AnalyticsModels/ChangeEvent.js +298 -0
  57. package/build/dist/Models/AnalyticsModels/ChangeEvent.js.map +1 -0
  58. package/build/dist/Models/AnalyticsModels/Index.js +2 -0
  59. package/build/dist/Models/AnalyticsModels/Index.js.map +1 -1
  60. package/build/dist/Models/DatabaseModels/Index.js +2 -0
  61. package/build/dist/Models/DatabaseModels/Index.js.map +1 -1
  62. package/build/dist/Models/DatabaseModels/UserTwoFactorBackupCode.js +277 -0
  63. package/build/dist/Models/DatabaseModels/UserTwoFactorBackupCode.js.map +1 -0
  64. package/build/dist/Server/API/UserTwoFactorBackupCodeAPI.js +201 -0
  65. package/build/dist/Server/API/UserTwoFactorBackupCodeAPI.js.map +1 -0
  66. package/build/dist/Server/EnvironmentConfig.js +1 -7
  67. package/build/dist/Server/EnvironmentConfig.js.map +1 -1
  68. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789000000000-AddUserSlackAndMicrosoftTeams.js +39 -0
  69. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789000000000-AddUserSlackAndMicrosoftTeams.js.map +1 -1
  70. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789100000000-AddUserTwoFactorBackupCode.js +46 -0
  71. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789100000000-AddUserTwoFactorBackupCode.js.map +1 -0
  72. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js +2 -2
  73. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js.map +1 -1
  74. package/build/dist/Server/Services/ChangeEventService.js +9 -0
  75. package/build/dist/Server/Services/ChangeEventService.js.map +1 -0
  76. package/build/dist/Server/Services/EnterpriseLicenseService.js +3 -3
  77. package/build/dist/Server/Services/Index.js +4 -0
  78. package/build/dist/Server/Services/Index.js.map +1 -1
  79. package/build/dist/Server/Services/UserService.js +39 -0
  80. package/build/dist/Server/Services/UserService.js.map +1 -1
  81. package/build/dist/Server/Services/UserTwoFactorBackupCodeService.js +327 -0
  82. package/build/dist/Server/Services/UserTwoFactorBackupCodeService.js.map +1 -0
  83. package/build/dist/Server/Utils/Attribution.js +6 -6
  84. package/build/dist/Server/Utils/Marketing/MarketingEventWebhook.js +4 -5
  85. package/build/dist/Server/Utils/Marketing/MarketingEventWebhook.js.map +1 -1
  86. package/build/dist/Server/Utils/Telemetry/ChangeEventRow.js +150 -0
  87. package/build/dist/Server/Utils/Telemetry/ChangeEventRow.js.map +1 -0
  88. package/build/dist/Server/Utils/TwoFactorBackupCode.js +269 -0
  89. package/build/dist/Server/Utils/TwoFactorBackupCode.js.map +1 -0
  90. package/build/dist/Types/AnalyticsDatabase/AnalyticsTableName.js +7 -0
  91. package/build/dist/Types/AnalyticsDatabase/AnalyticsTableName.js.map +1 -1
  92. package/build/dist/Types/Email/EmailTemplateType.js +2 -0
  93. package/build/dist/Types/Email/EmailTemplateType.js.map +1 -1
  94. package/build/dist/Types/Marketing/Attribution.js +9 -15
  95. package/build/dist/Types/Marketing/Attribution.js.map +1 -1
  96. package/build/dist/Types/Marketing/MarketingEvent.js +2 -33
  97. package/build/dist/Types/Marketing/MarketingEvent.js.map +1 -1
  98. package/build/dist/UI/Components/Charts/Area/AreaChart.js +1 -1
  99. package/build/dist/UI/Components/Charts/Area/AreaChart.js.map +1 -1
  100. package/build/dist/UI/Components/Charts/ChartGroup/ChartGroup.js +9 -1
  101. package/build/dist/UI/Components/Charts/ChartGroup/ChartGroup.js.map +1 -1
  102. package/build/dist/UI/Components/Charts/ChartLibrary/AreaChart/AreaChart.js +92 -38
  103. package/build/dist/UI/Components/Charts/ChartLibrary/AreaChart/AreaChart.js.map +1 -1
  104. package/build/dist/UI/Components/Charts/ChartLibrary/BarChart/BarChart.js +8 -8
  105. package/build/dist/UI/Components/Charts/ChartLibrary/BarChart/BarChart.js.map +1 -1
  106. package/build/dist/UI/Components/Charts/ChartLibrary/LineChart/LineChart.js +95 -37
  107. package/build/dist/UI/Components/Charts/ChartLibrary/LineChart/LineChart.js.map +1 -1
  108. package/build/dist/UI/Components/Charts/ChartLibrary/Utils/TooltipEntries.js +39 -24
  109. package/build/dist/UI/Components/Charts/ChartLibrary/Utils/TooltipEntries.js.map +1 -1
  110. package/build/dist/UI/Components/Charts/Line/LineChart.js +1 -1
  111. package/build/dist/UI/Components/Charts/Line/LineChart.js.map +1 -1
  112. package/build/dist/Utils/Metrics/MetricExplorerUrl.js +81 -0
  113. package/build/dist/Utils/Metrics/MetricExplorerUrl.js.map +1 -1
  114. package/build/dist/Utils/Telemetry/CrossSignalScope.js +14 -8
  115. package/build/dist/Utils/Telemetry/CrossSignalScope.js.map +1 -1
  116. package/package.json +1 -1
  117. package/Server/Infrastructure/Postgres/SchemaMigrations/1788900000000-RedactStoredMonitorIngestSecrets.ts +0 -117
  118. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1788900000000-RedactStoredMonitorIngestSecrets.js +0 -106
  119. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1788900000000-RedactStoredMonitorIngestSecrets.js.map +0 -1
@@ -0,0 +1,475 @@
1
+ import TwoFactorBackupCode, {
2
+ BackupCodeAlphabet,
3
+ BackupCodeLength,
4
+ BackupCodeSetSize,
5
+ } from "../../../Server/Utils/TwoFactorBackupCode";
6
+ import { EncryptionSecret } from "../../../Server/EnvironmentConfig";
7
+ import ObjectID from "../../../Types/ObjectID";
8
+ import crypto from "crypto";
9
+ import { describe, expect, it } from "@jest/globals";
10
+
11
+ /*
12
+ * ---------------------------------------------------------------------------
13
+ * The code generation and hashing behind two factor backup codes.
14
+ *
15
+ * WHAT THIS FILE IS GUARDING
16
+ *
17
+ * A backup code is the last door into an account whose second factor is gone,
18
+ * so it fails in two directions and both are unacceptable:
19
+ *
20
+ * - too weak, and a caller who has the password guesses their way past two
21
+ * factor auth. The whole security argument for this feature rests on the
22
+ * code space being enormous, so the alphabet, the length and the uniformity
23
+ * of the draw are pinned here rather than left to a comment;
24
+ * - too strict, and a user who typed exactly the right code off a piece of
25
+ * paper is told it is wrong. Those users are, by definition, already locked
26
+ * out and already panicking, and every transcription rule the alphabet was
27
+ * designed around (I/1, L/1, O/0, the display hyphen, a lowercase phone
28
+ * keyboard) is a way to produce that failure if normalization drifts.
29
+ *
30
+ * NOTHING IS MOCKED. The point of these tests is the real crypto: real
31
+ * randomness from crypto.randomInt, real HMAC keyed by the real
32
+ * EnvironmentConfig secret. The expected digests are recomputed here from
33
+ * Node's crypto directly rather than by calling the function under test, so a
34
+ * change to the construction has to be a deliberate, visible one.
35
+ *
36
+ * The single-use SEMANTICS are not here -- they live in Postgres, and are
37
+ * covered by Common/Tests/Server/Services/UserTwoFactorBackupCodeService.test.ts.
38
+ * ---------------------------------------------------------------------------
39
+ */
40
+
41
+ const USER_ID: ObjectID = new ObjectID("11111111-1111-4111-8111-111111111111");
42
+ const OTHER_USER_ID: ObjectID = new ObjectID(
43
+ "22222222-2222-4222-8222-222222222222",
44
+ );
45
+
46
+ /*
47
+ * The digest, recomputed from the RFC primitives rather than from the module
48
+ * under test. If the construction in TwoFactorBackupCode.hashCode is changed,
49
+ * this stops matching -- which is the point: the digest of every stored code
50
+ * depends on it, so a silent change is a silent invalidation of every backup
51
+ * code every user is holding.
52
+ */
53
+ type ExpectedHashFunction = (data: {
54
+ code: string;
55
+ userId: ObjectID;
56
+ }) => string;
57
+
58
+ const expectedHash: ExpectedHashFunction = (data: {
59
+ code: string;
60
+ userId: ObjectID;
61
+ }): string => {
62
+ const parts: Array<string> = ["v1", data.userId.toString(), data.code];
63
+
64
+ const message: string = parts
65
+ .map((part: string) => {
66
+ return `${part.length}:${part}`;
67
+ })
68
+ .join("");
69
+
70
+ return crypto
71
+ .createHmac("sha256", EncryptionSecret.toString())
72
+ .update(message)
73
+ .digest("hex");
74
+ };
75
+
76
+ describe("TwoFactorBackupCode.generateCode -- the code space", () => {
77
+ it("draws only from the declared alphabet", () => {
78
+ const violations: Array<string> = [];
79
+
80
+ for (let attempt: number = 0; attempt < 200; attempt++) {
81
+ const code: string = TwoFactorBackupCode.generateCode();
82
+
83
+ for (const character of code) {
84
+ if (!BackupCodeAlphabet.includes(character)) {
85
+ violations.push(`${code} contains ${character}`);
86
+ }
87
+ }
88
+ }
89
+
90
+ expect(violations).toEqual([]);
91
+ });
92
+
93
+ it("is exactly BackupCodeLength characters long every time", () => {
94
+ const lengths: Set<number> = new Set<number>();
95
+
96
+ for (let attempt: number = 0; attempt < 200; attempt++) {
97
+ lengths.add(TwoFactorBackupCode.generateCode().length);
98
+ }
99
+
100
+ expect(Array.from(lengths)).toEqual([BackupCodeLength]);
101
+ });
102
+
103
+ /*
104
+ * The alphabet is not decoration. Every symbol it excludes is one a person
105
+ * transcribes wrongly off a printed list -- and `normalizeCode` MAPS those
106
+ * symbols onto their lookalikes, so a generator that emitted an `O` would
107
+ * produce a code that normalizes to a DIFFERENT code and can never be
108
+ * redeemed. The exclusion and the mapping have to stay in step.
109
+ */
110
+ it.each(["I", "L", "O", "U"])(
111
+ "never emits the ambiguous character %p",
112
+ (character: string) => {
113
+ expect(BackupCodeAlphabet).not.toContain(character);
114
+ },
115
+ );
116
+
117
+ it("has a 32 symbol alphabet, so ten characters is 2^50", () => {
118
+ expect(BackupCodeAlphabet.length).toBe(32);
119
+ expect(BackupCodeLength).toBe(10);
120
+
121
+ /*
122
+ * Stated as an assertion rather than a comment because the security case
123
+ * for this whole feature is this number. At 2^50 a caller holding the
124
+ * password guesses one of ten live codes with probability ~1e-14 per
125
+ * attempt; shortening the code or shrinking the alphabet would quietly
126
+ * move that into range of the rate limiter's budget.
127
+ */
128
+ expect(Math.pow(BackupCodeAlphabet.length, BackupCodeLength)).toBe(
129
+ Math.pow(2, 50),
130
+ );
131
+ });
132
+
133
+ /*
134
+ * A uniformity smoke test, not a statistical proof. It exists to catch the
135
+ * one realistic implementation slip -- a modulo reduction over a range that
136
+ * is not a multiple of the alphabet size, which biases the first few symbols
137
+ * and shrinks the effective key space. With 32000 draws every symbol should
138
+ * land ~1000 times; a biased implementation misses this by a mile.
139
+ */
140
+ it("draws every symbol, roughly uniformly", () => {
141
+ const counts: Map<string, number> = new Map<string, number>();
142
+
143
+ for (const character of BackupCodeAlphabet) {
144
+ counts.set(character, 0);
145
+ }
146
+
147
+ const drawCount: number = 3200;
148
+
149
+ for (let attempt: number = 0; attempt < drawCount; attempt++) {
150
+ for (const character of TwoFactorBackupCode.generateCode()) {
151
+ counts.set(character, (counts.get(character) || 0) + 1);
152
+ }
153
+ }
154
+
155
+ const totalDraws: number = drawCount * BackupCodeLength;
156
+ const expectedPerSymbol: number = totalDraws / BackupCodeAlphabet.length;
157
+
158
+ const violations: Array<string> = [];
159
+
160
+ for (const [character, count] of counts) {
161
+ if (count < expectedPerSymbol * 0.6 || count > expectedPerSymbol * 1.4) {
162
+ violations.push(
163
+ `${character}: ${count} (expected ~${expectedPerSymbol})`,
164
+ );
165
+ }
166
+ }
167
+
168
+ expect(violations).toEqual([]);
169
+ });
170
+
171
+ it("does not repeat itself", () => {
172
+ const codes: Set<string> = new Set<string>();
173
+
174
+ for (let attempt: number = 0; attempt < 500; attempt++) {
175
+ codes.add(TwoFactorBackupCode.generateCode());
176
+ }
177
+
178
+ expect(codes.size).toBe(500);
179
+ });
180
+ });
181
+
182
+ describe("TwoFactorBackupCode.generateCodeSet", () => {
183
+ it("issues BackupCodeSetSize codes by default", () => {
184
+ expect(TwoFactorBackupCode.generateCodeSet()).toHaveLength(
185
+ BackupCodeSetSize,
186
+ );
187
+ });
188
+
189
+ it("honours an explicit count", () => {
190
+ expect(TwoFactorBackupCode.generateCodeSet(3)).toHaveLength(3);
191
+ });
192
+
193
+ /*
194
+ * Duplicates inside one set would not weaken the code space -- they would
195
+ * break SINGLE USE. Two rows sharing a digest means consuming one leaves an
196
+ * identical, still-unspent second row behind, so a code advertised as
197
+ * one-time would work twice.
198
+ */
199
+ it("never issues the same code twice in one set", () => {
200
+ for (let attempt: number = 0; attempt < 50; attempt++) {
201
+ const codes: Array<string> = TwoFactorBackupCode.generateCodeSet();
202
+
203
+ expect(new Set(codes).size).toBe(codes.length);
204
+ }
205
+ });
206
+ });
207
+
208
+ describe("TwoFactorBackupCode.formatForDisplay", () => {
209
+ it("splits a ten character code into two groups of five", () => {
210
+ expect(TwoFactorBackupCode.formatForDisplay("ABCDE12345")).toBe(
211
+ "ABCDE-12345",
212
+ );
213
+ });
214
+
215
+ /*
216
+ * The hyphen is cosmetic and must survive the round trip, or every code we
217
+ * show the user is a code they cannot type back in.
218
+ */
219
+ it("produces something normalizeCode maps back to the original", () => {
220
+ const violations: Array<string> = [];
221
+
222
+ for (let attempt: number = 0; attempt < 200; attempt++) {
223
+ const code: string = TwoFactorBackupCode.generateCode();
224
+ const displayed: string = TwoFactorBackupCode.formatForDisplay(code);
225
+
226
+ if (TwoFactorBackupCode.normalizeCode(displayed) !== code) {
227
+ violations.push(`${code} -> ${displayed}`);
228
+ }
229
+ }
230
+
231
+ expect(violations).toEqual([]);
232
+ });
233
+ });
234
+
235
+ describe("TwoFactorBackupCode.normalizeCode -- what a locked-out user types", () => {
236
+ it("accepts the code exactly as displayed", () => {
237
+ expect(TwoFactorBackupCode.normalizeCode("ABCDE-12345")).toBe("ABCDE12345");
238
+ });
239
+
240
+ it.each([
241
+ ["lowercase from a phone keyboard", "abcde-12345", "ABCDE12345"],
242
+ ["no hyphen at all", "ABCDE12345", "ABCDE12345"],
243
+ ["a space where the hyphen was", "ABCDE 12345", "ABCDE12345"],
244
+ ["leading and trailing whitespace", " ABCDE-12345 ", "ABCDE12345"],
245
+ ["a clipboard that inserted newlines", "ABCDE\n12345", "ABCDE12345"],
246
+ ["mixed case and stray punctuation", "aB.cD/e-1 2345", "ABCDE12345"],
247
+ ])("handles %s", (_label: string, raw: string, expected: string) => {
248
+ expect(TwoFactorBackupCode.normalizeCode(raw)).toBe(expected);
249
+ });
250
+
251
+ /*
252
+ * Crockford's transcription rules. These are the ONLY reason the alphabet
253
+ * drops these letters -- if the mapping went away, the exclusion would just
254
+ * be an arbitrary restriction and a user reading `0` as `O` off a printout
255
+ * would be told their code is invalid.
256
+ */
257
+ it.each([
258
+ ["O", "0"],
259
+ ["o", "0"],
260
+ ["I", "1"],
261
+ ["i", "1"],
262
+ ["L", "1"],
263
+ ["l", "1"],
264
+ ])("maps the lookalike %p to %p", (typed: string, canonical: string) => {
265
+ expect(TwoFactorBackupCode.normalizeCode(typed)).toBe(canonical);
266
+ });
267
+
268
+ /*
269
+ * `U` is excluded from the alphabet with no lookalike to map onto, so it is
270
+ * dropped rather than translated. Pinned so that nobody "helpfully" maps it
271
+ * to V later and changes what a submitted code means.
272
+ */
273
+ it("drops U rather than mapping it", () => {
274
+ expect(TwoFactorBackupCode.normalizeCode("UUU")).toBe("");
275
+ });
276
+
277
+ /*
278
+ * The code arrives straight off a JSON body, so it is only a string because
279
+ * the caller chose to make it one. Anything else must fail verification
280
+ * rather than throw out of the normalizer and surface as a 500 -- an
281
+ * unhandled exception on the login path is both an availability bug and a
282
+ * way to tell requests apart.
283
+ */
284
+ it.each([[undefined], [null], [12345], [{}], [[]], [true]])(
285
+ "returns empty for the non-string input %p",
286
+ (raw: unknown) => {
287
+ expect(TwoFactorBackupCode.normalizeCode(raw as string)).toBe("");
288
+ },
289
+ );
290
+
291
+ it("returns empty for a string with nothing usable in it", () => {
292
+ expect(TwoFactorBackupCode.normalizeCode(" --- ")).toBe("");
293
+ });
294
+ });
295
+
296
+ describe("TwoFactorBackupCode.hashCode", () => {
297
+ it("matches an independently computed HMAC", () => {
298
+ const code: string = "ABCDE12345";
299
+
300
+ expect(TwoFactorBackupCode.hashCode({ code: code, userId: USER_ID })).toBe(
301
+ expectedHash({ code: code, userId: USER_ID }),
302
+ );
303
+ });
304
+
305
+ it("is deterministic, which is what lets a code be looked up by digest", () => {
306
+ const code: string = TwoFactorBackupCode.generateCode();
307
+
308
+ expect(TwoFactorBackupCode.hashCode({ code: code, userId: USER_ID })).toBe(
309
+ TwoFactorBackupCode.hashCode({ code: code, userId: USER_ID }),
310
+ );
311
+ });
312
+
313
+ /*
314
+ * Domain separation. Without it, one precomputed table inverts every
315
+ * account's codes at once, and two users issued the same code would be
316
+ * visibly linked by identical rows.
317
+ */
318
+ it("gives two users different digests for the same code", () => {
319
+ const code: string = "ABCDE12345";
320
+
321
+ expect(
322
+ TwoFactorBackupCode.hashCode({ code: code, userId: USER_ID }),
323
+ ).not.toBe(
324
+ TwoFactorBackupCode.hashCode({ code: code, userId: OTHER_USER_ID }),
325
+ );
326
+ });
327
+
328
+ /*
329
+ * The digest is computed over the NORMALIZED code, not the raw submission.
330
+ * If it were not, a user who typed their code with the hyphen would hash to
331
+ * something that matches nothing -- the exact lockout the normalizer exists
332
+ * to prevent, moved one function along.
333
+ */
334
+ it.each(["ABCDE-12345", "abcde12345", " abcde-12345 ", "ABCDE 12345"])(
335
+ "hashes %p to the same digest as the canonical form",
336
+ (raw: string) => {
337
+ expect(TwoFactorBackupCode.hashCode({ code: raw, userId: USER_ID })).toBe(
338
+ TwoFactorBackupCode.hashCode({
339
+ code: "ABCDE12345",
340
+ userId: USER_ID,
341
+ }),
342
+ );
343
+ },
344
+ );
345
+
346
+ it("produces 64 hex characters, which fits the ShortText column", () => {
347
+ const digest: string = TwoFactorBackupCode.hashCode({
348
+ code: TwoFactorBackupCode.generateCode(),
349
+ userId: USER_ID,
350
+ });
351
+
352
+ expect(digest).toMatch(/^[0-9a-f]{64}$/);
353
+ expect(digest.length).toBeLessThanOrEqual(100);
354
+ });
355
+
356
+ /*
357
+ * Length prefixing. Without it, concatenation is ambiguous: a userId of
358
+ * "ab" with code "cd" and a userId of "abc" with code "d" would produce the
359
+ * same message and therefore the same digest.
360
+ */
361
+ it("cannot be confused by rearranging the boundary between user and code", () => {
362
+ const first: string = TwoFactorBackupCode.hashCode({
363
+ code: "CD",
364
+ userId: new ObjectID("ab"),
365
+ });
366
+
367
+ const second: string = TwoFactorBackupCode.hashCode({
368
+ code: "D",
369
+ userId: new ObjectID("abc"),
370
+ });
371
+
372
+ expect(first).not.toBe(second);
373
+ });
374
+
375
+ /*
376
+ * The plaintext must not be recoverable from the digest by anything short of
377
+ * brute force -- in particular, the digest must not merely BE the code, or
378
+ * contain it, which is the shape a careless "hash" refactor tends to take.
379
+ */
380
+ it("does not contain the code it was computed from", () => {
381
+ const code: string = TwoFactorBackupCode.generateCode();
382
+
383
+ const digest: string = TwoFactorBackupCode.hashCode({
384
+ code: code,
385
+ userId: USER_ID,
386
+ });
387
+
388
+ expect(digest).not.toContain(code);
389
+ expect(digest).not.toContain(code.toLowerCase());
390
+ });
391
+
392
+ it("changes completely when a single character of the code changes", () => {
393
+ const a: string = TwoFactorBackupCode.hashCode({
394
+ code: "ABCDE12345",
395
+ userId: USER_ID,
396
+ });
397
+
398
+ const b: string = TwoFactorBackupCode.hashCode({
399
+ code: "ABCDE12346",
400
+ userId: USER_ID,
401
+ });
402
+
403
+ expect(a).not.toBe(b);
404
+ });
405
+
406
+ it("hashes an empty code to something no real code can collide with", () => {
407
+ /*
408
+ * An empty submission still produces a digest here -- the refusal lives in
409
+ * the service, which never gets this far. What matters is that the digest
410
+ * of "" is not the digest of any generated code, so a caller sending an
411
+ * empty string can never match a row even if a future caller forgets the
412
+ * guard.
413
+ */
414
+ const emptyDigest: string = TwoFactorBackupCode.hashCode({
415
+ code: "",
416
+ userId: USER_ID,
417
+ });
418
+
419
+ const violations: Array<string> = [];
420
+
421
+ for (let attempt: number = 0; attempt < 100; attempt++) {
422
+ const code: string = TwoFactorBackupCode.generateCode();
423
+
424
+ if (
425
+ TwoFactorBackupCode.hashCode({ code: code, userId: USER_ID }) ===
426
+ emptyDigest
427
+ ) {
428
+ violations.push(code);
429
+ }
430
+ }
431
+
432
+ expect(violations).toEqual([]);
433
+ });
434
+ });
435
+
436
+ describe("TwoFactorBackupCode.isHashEqual", () => {
437
+ it("accepts two identical digests", () => {
438
+ const digest: string = TwoFactorBackupCode.hashCode({
439
+ code: "ABCDE12345",
440
+ userId: USER_ID,
441
+ });
442
+
443
+ expect(TwoFactorBackupCode.isHashEqual(digest, digest)).toBe(true);
444
+ });
445
+
446
+ it("rejects two different digests", () => {
447
+ expect(
448
+ TwoFactorBackupCode.isHashEqual(
449
+ TwoFactorBackupCode.hashCode({ code: "AAAAA11111", userId: USER_ID }),
450
+ TwoFactorBackupCode.hashCode({ code: "BBBBB22222", userId: USER_ID }),
451
+ ),
452
+ ).toBe(false);
453
+ });
454
+
455
+ /*
456
+ * crypto.timingSafeEqual THROWS on a length mismatch, so the length check in
457
+ * front of it is not an optimisation -- without it, a short or malformed
458
+ * value turns a failed comparison into a 500 on the login path.
459
+ */
460
+ it.each([
461
+ ["", ""],
462
+ ["abc", ""],
463
+ ["", "abc"],
464
+ ["abc", "abcd"],
465
+ ])(
466
+ "returns false rather than throwing for (%p, %p)",
467
+ (a: string, b: string) => {
468
+ expect(() => {
469
+ return TwoFactorBackupCode.isHashEqual(a, b);
470
+ }).not.toThrow();
471
+
472
+ expect(TwoFactorBackupCode.isHashEqual(a, b)).toBe(false);
473
+ },
474
+ );
475
+ });
@@ -0,0 +1,103 @@
1
+ import { AreaChart } from "../../../../UI/Components/Charts/ChartLibrary/AreaChart/AreaChart";
2
+ import { LineChart } from "../../../../UI/Components/Charts/ChartLibrary/LineChart/LineChart";
3
+ import "@testing-library/jest-dom";
4
+ import { render } from "@testing-library/react";
5
+ import React from "react";
6
+ import { describe, expect, jest, test } from "@jest/globals";
7
+
8
+ /*
9
+ * ResponsiveContainer measures its parent, which is always 0x0 in jsdom,
10
+ * so the chart renders nothing without a fixed size.
11
+ */
12
+ jest.mock("recharts", () => {
13
+ const actual: Record<string, any> = jest.requireActual("recharts") as Record<
14
+ string,
15
+ any
16
+ >;
17
+ return {
18
+ ...actual,
19
+ ResponsiveContainer: ({ children }: { children: React.ReactElement }) => {
20
+ return React.cloneElement(children, {
21
+ width: 600,
22
+ height: 300,
23
+ } as Record<string, unknown>);
24
+ },
25
+ };
26
+ });
27
+
28
+ /*
29
+ * Compare-to-previous ghost series must be visually and interactively
30
+ * second-class: dashed, and never part of the fat invisible click-target
31
+ * lines that make live series selectable.
32
+ */
33
+
34
+ type ChartRow = Record<string, any>;
35
+
36
+ const data: Array<ChartRow> = [
37
+ { time: "10:00", live: 10, "live (previous)": 8 },
38
+ { time: "10:05", live: 20, "live (previous)": 12 },
39
+ { time: "10:10", live: 15, "live (previous)": 9 },
40
+ ];
41
+
42
+ describe.each([
43
+ ["LineChart", LineChart],
44
+ ["AreaChart", AreaChart],
45
+ ] as Array<[string, typeof LineChart | typeof AreaChart]>)(
46
+ "%s ghost series",
47
+ (_name: string, Chart: typeof LineChart | typeof AreaChart) => {
48
+ test("ghost categories render dashed; live ones do not", () => {
49
+ const { container } = render(
50
+ <Chart
51
+ data={data}
52
+ index="time"
53
+ categories={["live", "live (previous)"]}
54
+ ghostCategories={["live (previous)"]}
55
+ />,
56
+ );
57
+
58
+ const dashed: Array<Element> = Array.from(
59
+ container.querySelectorAll('path[stroke-dasharray="6 4"]'),
60
+ );
61
+ expect(dashed.length).toBeGreaterThan(0);
62
+
63
+ /*
64
+ * The live series' curve must NOT be dashed — recharts names each
65
+ * series path group; assert at least one series curve without the
66
+ * ghost dash exists.
67
+ */
68
+ const allCurves: Array<Element> = Array.from(
69
+ container.querySelectorAll(".recharts-layer path"),
70
+ ).filter((el: Element) => {
71
+ return el.getAttribute("stroke-dasharray") !== "6 4";
72
+ });
73
+ expect(allCurves.length).toBeGreaterThan(0);
74
+ });
75
+
76
+ test("ghosts are excluded from the fat click-target lines", () => {
77
+ const { container } = render(
78
+ <Chart
79
+ data={data}
80
+ index="time"
81
+ categories={["live", "live (previous)"]}
82
+ ghostCategories={["live (previous)"]}
83
+ onValueChange={() => {
84
+ // Enables the click-target machinery, like the wrappers do.
85
+ }}
86
+ />,
87
+ );
88
+
89
+ /*
90
+ * LineChart renders invisible strokeWidth-12 click-targets per
91
+ * SELECTABLE series; ghosts must not get one. (AreaChart has no
92
+ * fat-line mechanism — zero is correct there.)
93
+ */
94
+ const fatLines: Array<Element> = Array.from(
95
+ container.querySelectorAll('path[stroke-width="12"]'),
96
+ );
97
+ expect(fatLines.length).toBeLessThanOrEqual(1);
98
+ for (const fatLine of fatLines) {
99
+ expect(fatLine.getAttribute("name")).not.toContain("(previous)");
100
+ }
101
+ });
102
+ },
103
+ );
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, test } from "@jest/globals";
2
2
  import {
3
3
  DEFAULT_TOOLTIP_MAX_ENTRIES,
4
+ PREVIOUS_PERIOD_SERIES_SUFFIX,
4
5
  PreparedTooltipEntries,
5
6
  SortableTooltipItem,
6
7
  prepareTooltipEntries,
@@ -53,24 +54,24 @@ describe("prepareTooltipEntries", () => {
53
54
  expect(categories(prepared)).toEqual(["cpu1", "cpu2", "cpu10"]);
54
55
  });
55
56
 
56
- test("sorts non-finite values last without dropping them", () => {
57
+ test("sorts non-finite values last and drops band tuples entirely", () => {
57
58
  const prepared: PreparedTooltipEntries<TestItem> = prepareTooltipEntries([
58
59
  item("nan-series", NaN),
59
60
  item("real-low", 1),
60
61
  item("infinite", Infinity),
61
62
  item("real-high", 7),
62
- // The anomaly band's dataKey yields a [low, high] tuple at runtime.
63
+ /*
64
+ * The anomaly band's dataKey yields a [low, high] tuple at runtime
65
+ * — a shaded region, not a series, so it must not render as a row
66
+ * nor count toward the overflow footer.
67
+ */
63
68
  item("band", [2, 9] as unknown as number),
64
69
  ]);
65
70
 
66
71
  expect(categories(prepared).slice(0, 2)).toEqual(["real-high", "real-low"]);
67
72
  // Non-finite tail keeps natural name order among itself.
68
- expect(categories(prepared).slice(2)).toEqual([
69
- "band",
70
- "infinite",
71
- "nan-series",
72
- ]);
73
- expect(prepared.totalCount).toBe(5);
73
+ expect(categories(prepared).slice(2)).toEqual(["infinite", "nan-series"]);
74
+ expect(prepared.totalCount).toBe(4);
74
75
  });
75
76
 
76
77
  test('filters out type "none" entries (hidden click-target lines, band fills)', () => {
@@ -143,6 +144,41 @@ describe("prepareTooltipEntries", () => {
143
144
  }
144
145
  });
145
146
 
147
+ test("previous-period ghosts sort after every live series, whatever their value", () => {
148
+ const prepared: PreparedTooltipEntries<TestItem> = prepareTooltipEntries([
149
+ item(`host-a${PREVIOUS_PERIOD_SERIES_SUFFIX}`, 999),
150
+ item("host-a", 10),
151
+ item("host-b", 50),
152
+ item(`host-b${PREVIOUS_PERIOD_SERIES_SUFFIX}`, 60),
153
+ ]);
154
+
155
+ expect(categories(prepared)).toEqual([
156
+ "host-b",
157
+ "host-a",
158
+ // Ghost tier keeps its own value ordering.
159
+ `host-a${PREVIOUS_PERIOD_SERIES_SUFFIX}`,
160
+ `host-b${PREVIOUS_PERIOD_SERIES_SUFFIX}`,
161
+ ]);
162
+ });
163
+
164
+ test("ghosts never displace live readings under the cap", () => {
165
+ const payload: Array<TestItem> = [];
166
+ for (let index: number = 0; index < DEFAULT_TOOLTIP_MAX_ENTRIES; index++) {
167
+ payload.push(item(`live-${index}`, index));
168
+ payload.push(item(`live-${index}${PREVIOUS_PERIOD_SERIES_SUFFIX}`, 1e6));
169
+ }
170
+
171
+ const prepared: PreparedTooltipEntries<TestItem> =
172
+ prepareTooltipEntries(payload);
173
+
174
+ expect(
175
+ prepared.entries.every((entry: TestItem) => {
176
+ return !entry.category.endsWith(PREVIOUS_PERIOD_SERIES_SUFFIX);
177
+ }),
178
+ ).toBe(true);
179
+ expect(prepared.overflowCount).toBe(DEFAULT_TOOLTIP_MAX_ENTRIES);
180
+ });
181
+
146
182
  test("does not mutate the input payload", () => {
147
183
  const payload: Array<TestItem> = [item("low", 1), item("high", 2)];
148
184
  prepareTooltipEntries(payload);
@@ -597,9 +597,20 @@ describe("toMetricsExplorerQueryParams", () => {
597
597
  });
598
598
 
599
599
  test("reports the signal-specific fields the metric grammar cannot express", () => {
600
+ const result: CrossSignalQueryParams = toMetricsExplorerQueryParams(
601
+ fullScope(),
602
+ "container.cpu.time",
603
+ );
604
+
605
+ /*
606
+ * serviceIds now CARRY: they ride the explorer's one-shot
607
+ * `services` param (resolved to resource.service.name filters on
608
+ * load) instead of being reported dropped.
609
+ */
610
+ expect(result.dropped).toEqual(["traceIds", "spanIds", "severityTexts"]);
600
611
  expect(
601
- toMetricsExplorerQueryParams(fullScope(), "container.cpu.time").dropped,
602
- ).toEqual(["serviceIds", "traceIds", "spanIds", "severityTexts"]);
612
+ JSON.parse(result.params["services"] as string).length,
613
+ ).toBeGreaterThan(0);
603
614
  });
604
615
  });
605
616
 
@@ -7,6 +7,13 @@ enum AnalyticsTableName {
7
7
  * attributes with a keys sidecar for arbitrary-field filtering.
8
8
  */
9
9
  SecurityEvent = "SecurityEventItemV1",
10
+ /*
11
+ * Deploy/config-change markers posted by CI/CD, rendered as dashed
12
+ * vertical lines on metric charts. Peer of LogItemV3 in layout (tenant
13
+ * projectId, per-row retentionDate TTL, attributes Map + keys sidecar)
14
+ * but tiny in volume.
15
+ */
16
+ ChangeEvent = "ChangeEventV1",
10
17
  Metric = "MetricItemV3",
11
18
  ExceptionInstance = "ExceptionItemV3",
12
19
  Span = "SpanItemV3",