@xenon-device-management/xenon 2.16.0 → 2.17.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.
Files changed (114) hide show
  1. package/README.md +2 -2
  2. package/lib/package.json +1 -1
  3. package/lib/public/assets/{AnnotationOverlay-2W4JvEyZ.js → AnnotationOverlay-CjmMCS0S.js} +1 -1
  4. package/lib/public/assets/{ApiKeyGate-GmckX_7r.js → ApiKeyGate-B4Ob0v3C.js} +1 -1
  5. package/lib/public/assets/{DeviceMosaicView-DqODzkyo.js → DeviceMosaicView-DTVOB_NO.js} +1 -1
  6. package/lib/public/assets/{EmptyState-7hETKEWb.js → EmptyState-DcEG-oAi.js} +1 -1
  7. package/lib/public/assets/{FieldGroup-GOgssFEP.js → FieldGroup-CtnCDshE.js} +1 -1
  8. package/lib/public/assets/{FilterMenu-Yvf6RGMd.js → FilterMenu-BK0dE9cc.js} +1 -1
  9. package/lib/public/assets/{Menu-KrPnfdsf.js → Menu-eKsmLpKS.js} +1 -1
  10. package/lib/public/assets/{Modal-C6WjZFeI.js → Modal-DPwop3Lz.js} +1 -1
  11. package/lib/public/assets/{RecordingPage-CSRIhZEh.js → RecordingPage-CfgSkZkB.js} +1 -1
  12. package/lib/public/assets/{RecordingsPage-CB8ST3nE.js → RecordingsPage-Bzl9pTUY.js} +1 -1
  13. package/lib/public/assets/{SegmentedControl-C9o90KId.js → SegmentedControl-B_TZTrPm.js} +1 -1
  14. package/lib/public/assets/{SettingCard-CPm3w9l2.js → SettingCard-DlmvZJPM.js} +1 -1
  15. package/lib/public/assets/{Table-DwIgERRt.js → Table-BigPWKXi.js} +1 -1
  16. package/lib/public/assets/{activity-DrLbHifn.js → activity-CvuZdQYu.js} +1 -1
  17. package/lib/public/assets/{ai-settings-DU_Ls06P.js → ai-settings-lI2UJ2n7.js} +1 -1
  18. package/lib/public/assets/{api-keys-CWYdEzJ_.js → api-keys-CPgf9XJM.js} +1 -1
  19. package/lib/public/assets/{apps-BqNVdln7.js → apps-DIzOvtUp.js} +1 -1
  20. package/lib/public/assets/{arrow-left-BtB0_Jg_.js → arrow-left-DiP5ywBT.js} +1 -1
  21. package/lib/public/assets/{arrow-right-C8NhdtyN.js → arrow-right-DtW_8hm5.js} +1 -1
  22. package/lib/public/assets/{arrow-up-right-gMg0ffvv.js → arrow-up-right-C89FbNU0.js} +1 -1
  23. package/lib/public/assets/{auth-shell-CiYZ3N4M.js → auth-shell-B7sUDb--.js} +2 -2
  24. package/lib/public/assets/{builds-page-EaaqDmLN.js → builds-page-BBhvrMfA.js} +1 -1
  25. package/lib/public/assets/{button-DDau4Axv.js → button-DugsdUw1.js} +1 -1
  26. package/lib/public/assets/{calendar-DQ83B1ed.js → calendar-grKd08ZH.js} +1 -1
  27. package/lib/public/assets/{check-K1ovTQam.js → check-ORjyNfnX.js} +1 -1
  28. package/lib/public/assets/{chevron-right-Biq00pMt.js → chevron-right-Ei2FxUXq.js} +1 -1
  29. package/lib/public/assets/{circle-check-CBv88cH7.js → circle-check-Day0HjW4.js} +1 -1
  30. package/lib/public/assets/{circle-x-Bmltailn.js → circle-x-CHxSRLHp.js} +1 -1
  31. package/lib/public/assets/{clock-BPrld-3h.js → clock-BDHewWTx.js} +1 -1
  32. package/lib/public/assets/{copy-t0QB14JI.js → copy-CTwT4I3D.js} +1 -1
  33. package/lib/public/assets/{device-explorer-BgGZ8AvV.js → device-explorer-DlhrKJ-g.js} +1 -1
  34. package/lib/public/assets/{download-BroHxNOh.js → download-D3bjz_vr.js} +1 -1
  35. package/lib/public/assets/{forgot-password-Bjmf49i6.js → forgot-password-BNBLi023.js} +1 -1
  36. package/lib/public/assets/{h264Stream-DeD__6wa.js → h264Stream-C51Au2i_.js} +1 -1
  37. package/lib/public/assets/{index-B0gQkEg0.js → index-Dk5J6HB1.js} +2 -2
  38. package/lib/public/assets/{index-B0JeuZbg.js → index-DncSz5LG.js} +1 -1
  39. package/lib/public/assets/{index-72oF89LJ.js → index-Z7_BY3pJ.js} +1 -1
  40. package/lib/public/assets/{input-DIc4MSC7.js → input-bTXM4l09.js} +1 -1
  41. package/lib/public/assets/{line-chart-BcWm2vW8.js → line-chart-B3YmVYyr.js} +1 -1
  42. package/lib/public/assets/{list-checks-B06IJJad.js → list-checks-BClKEj1-.js} +1 -1
  43. package/lib/public/assets/{lock-pVLvnN30.js → lock-CZsenX3D.js} +1 -1
  44. package/lib/public/assets/{login-CN77vy--.js → login-B6A6tOp9.js} +1 -1
  45. package/lib/public/assets/{maintenance-settings-CSdzQSkY.js → maintenance-settings-CmCJGy7O.js} +1 -1
  46. package/lib/public/assets/{monitor-BtrN5IkI.js → monitor-BdTNEglU.js} +1 -1
  47. package/lib/public/assets/{mouse-pointer-2-CNsQfo6w.js → mouse-pointer-2-BM8CaLtt.js} +1 -1
  48. package/lib/public/assets/{network-BSfA8ZxG.js → network-BS6vUc1x.js} +1 -1
  49. package/lib/public/assets/{overview-BfTebCK5.js → overview-Yfk_Y7g3.js} +1 -1
  50. package/lib/public/assets/{page-header-D8KUX6Qg.js → page-header-DhXCwpml.js} +1 -1
  51. package/lib/public/assets/{play-Cvc8xzic.js → play-D08gP1td.js} +1 -1
  52. package/lib/public/assets/{plus-C9Zj84UF.js → plus-BKboorfa.js} +1 -1
  53. package/lib/public/assets/{profile-page-Bi27STgs.js → profile-page-Cd9NodrA.js} +1 -1
  54. package/lib/public/assets/{reset-password-CPsOuwSu.js → reset-password-acLDyyDW.js} +1 -1
  55. package/lib/public/assets/{runbook-page-DEQ-DBOX.js → runbook-page-CWLkC1Fd.js} +1 -1
  56. package/lib/public/assets/{select-BWpnhWXj.js → select-DZoRKNti.js} +1 -1
  57. package/lib/public/assets/{selector-detail-redirect-BefSCSpe.js → selector-detail-redirect-DS4qrt84.js} +1 -1
  58. package/lib/public/assets/{selector-health-page-MSk96Zz7.js → selector-health-page-TpmN61G3.js} +1 -1
  59. package/lib/public/assets/{session-detail-page-DPyBNef_.js → session-detail-page-C0wYaXqy.js} +1 -1
  60. package/lib/public/assets/{settings-V6x-cXwy.js → settings-CxPGEY2j.js} +1 -1
  61. package/lib/public/assets/{stat-tile-Duex-GZD.js → stat-tile-DUpyYgl-.js} +1 -1
  62. package/lib/public/assets/{tablet-BBcoqBmL.js → tablet-SA02BJNQ.js} +1 -1
  63. package/lib/public/assets/{teams-ts8p5rEh.js → teams-jamD0Kxr.js} +1 -1
  64. package/lib/public/assets/{trash-2-CZ2ew6AZ.js → trash-2-DO8fv6w4.js} +1 -1
  65. package/lib/public/assets/{upload-Dv99y_le.js → upload-CaiGCStb.js} +1 -1
  66. package/lib/public/assets/{use-builds-data-DrYC8JCF.js → use-builds-data-jS-fcvVf.js} +1 -1
  67. package/lib/public/assets/{use-password-reset-mode-C7QkBNkP.js → use-password-reset-mode-BzoenegM.js} +1 -1
  68. package/lib/public/assets/{users-gJ5Y01yo.js → users-Bnw7Vs_B.js} +1 -1
  69. package/lib/public/assets/{users-D7tKMESH.js → users-DHvDrriG.js} +1 -1
  70. package/lib/public/assets/{video-off-CqZVuZGs.js → video-off-FEvy0w5U.js} +1 -1
  71. package/lib/public/assets/{webhook-settings-DI5DSW99.js → webhook-settings-CBVB5lxi.js} +1 -1
  72. package/lib/public/assets/{zap-ClcHFxfo.js → zap-BMrTJO6M.js} +1 -1
  73. package/lib/public/index.html +1 -1
  74. package/lib/schema.json +1 -1
  75. package/lib/src/app/index.js +2 -0
  76. package/lib/src/app/openapi/grid.yaml +102 -0
  77. package/lib/src/dashboard/event-manager.js +5 -8
  78. package/lib/src/device-utils.js +11 -2
  79. package/lib/src/gateway/nodeAsk.js +57 -0
  80. package/lib/src/gateway/nodeSessionDeviceLogs.js +35 -0
  81. package/lib/src/plugin.js +4 -1
  82. package/lib/src/scripts/initialize-database.js +0 -6
  83. package/lib/src/scripts/run-migrations.js +123 -880
  84. package/lib/src/services/SessionLifecycleService.js +20 -5
  85. package/lib/src/services/interceptor/CertManager.js +50 -16
  86. package/lib/src/services/logcat/NodeDeviceLogStore.js +99 -0
  87. package/lib/src/services/logcat/NodeDeviceLogsCollector.js +164 -0
  88. package/lib/src/services/logcat/SessionDeviceLogs.js +199 -44
  89. package/lib/src/services/logcat/nodeDeviceLogs.js +91 -0
  90. package/lib/src/services/metrics/nodeMetrics.js +20 -49
  91. package/lib/src/sessions/RemoteSession.js +11 -2
  92. package/lib/src/sessions/SessionManager.js +28 -1
  93. package/lib/test/helpers/fake-logcat.js +80 -0
  94. package/lib/test/helpers/hub-node-pair.js +227 -0
  95. package/lib/test/unit/dashboard-events-device-logs.spec.js +15 -0
  96. package/lib/test/unit/hub-node-iphone-readiness.spec.js +134 -0
  97. package/lib/test/unit/hub-node-session-device-logs.spec.js +194 -0
  98. package/lib/test/unit/hub-node-session-metrics.spec.js +24 -192
  99. package/lib/test/unit/hub-remote-session-heartbeat.spec.js +8 -1
  100. package/lib/test/unit/interceptor/CertManager.spec.js +89 -0
  101. package/lib/test/unit/node-device-log-store.spec.js +102 -0
  102. package/lib/test/unit/node-device-logs-collector.spec.js +343 -0
  103. package/lib/test/unit/node-gateway-create-appium-server.spec.js +8 -1
  104. package/lib/test/unit/node-hub-session-owner.spec.js +8 -1
  105. package/lib/test/unit/node-session-device-logs-route.spec.js +103 -0
  106. package/lib/test/unit/run-migrations-database.spec.js +57 -424
  107. package/lib/test/unit/run-migrations.test.js +74 -674
  108. package/lib/test/unit/session-device-logs-hub-node.spec.js +340 -0
  109. package/lib/test/unit/session-device-logs-lifecycle.spec.js +137 -0
  110. package/lib/test/unit/session-device-logs.spec.js +32 -94
  111. package/lib/test/unit/session-log-indexes.spec.js +15 -0
  112. package/lib/tsconfig.tsbuildinfo +1 -1
  113. package/package.json +1 -1
  114. package/schema.json +1 -1
@@ -14,38 +14,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  require("reflect-metadata");
16
16
  const chai_1 = require("chai");
17
- const express_1 = __importDefault(require("express"));
18
- const fs_1 = __importDefault(require("fs"));
19
- const http_1 = __importDefault(require("http"));
20
- const os_1 = __importDefault(require("os"));
21
- const path_1 = __importDefault(require("path"));
22
- const sinon_1 = __importDefault(require("sinon"));
23
17
  const loopbackRequest_1 = __importDefault(require("../helpers/loopbackRequest"));
24
18
  const typedi_1 = require("typedi");
25
- const plugin_1 = require("../../src/plugin");
26
- const registerCommandAuth_1 = require("../../src/app/registerCommandAuth");
27
- const defaultGateway_1 = require("../../src/gateway/defaultGateway");
28
- const hubSessionToken_1 = require("../../src/gateway/hubSessionToken");
29
- const nodeSessionStatus_1 = require("../../src/gateway/nodeSessionStatus");
30
- const nodeSessionMetrics_1 = require("../../src/gateway/nodeSessionMetrics");
31
19
  const SessionMetricsService_1 = require("../../src/services/metrics/SessionMetricsService");
32
20
  const NodeMetricsStore_1 = require("../../src/services/metrics/NodeMetricsStore");
33
21
  const NodeMetricsCollector_1 = require("../../src/services/metrics/NodeMetricsCollector");
34
22
  const nodeMetrics_1 = require("../../src/services/metrics/nodeMetrics");
35
- const JwtKeyService_1 = require("../../src/services/token/JwtKeyService");
36
- const PluginContext_1 = require("../../src/PluginContext");
23
+ const SessionDeviceLogs_1 = require("../../src/services/logcat/SessionDeviceLogs");
37
24
  const IPluginArgs_1 = require("../../src/interfaces/IPluginArgs");
38
- const device_managers_1 = require("../../src/device-managers");
39
- const device_store_1 = require("../../src/data-service/device-store");
40
- const prisma_store_1 = require("../../src/data-service/prisma-store");
41
- const SessionManager_1 = require("../../src/sessions/SessionManager");
42
- const RemoteSession_1 = require("../../src/sessions/RemoteSession");
43
- const appiumUmbrella_1 = require("../../src/sessions/appiumUmbrella");
44
- const config_1 = require("../../src/config");
45
- const container_registration_1 = require("../helpers/container-registration");
46
25
  const scratch_database_1 = require("../helpers/scratch-database");
47
26
  const selector_health_fixture_1 = require("../helpers/selector-health-fixture");
48
- const appium_umbrella_1 = require("../helpers/appium-umbrella");
27
+ const hub_node_pair_1 = require("../helpers/hub-node-pair");
49
28
  /**
50
29
  * A hub collects CPU and memory for a session on a node's phone from the
51
30
  * node: against a node in Appium 3's own server() (Appium's umbrella with
@@ -55,7 +34,6 @@ const appium_umbrella_1 = require("../helpers/appium-umbrella");
55
34
  * test drives; everything between it and the hub's writes is the real thing.
56
35
  */
57
36
  const quiet = { info: () => undefined, warn: () => undefined, error: () => undefined };
58
- const NODE_ID = 'node-1';
59
37
  /** The node's sampler service, its phone sampler replaced by one the test drives. */
60
38
  class NodeSideMetrics extends SessionMetricsService_1.SessionMetricsService {
61
39
  constructor() {
@@ -139,169 +117,27 @@ const at = (t) => ({
139
117
  describe('a hub collects a node session’s CPU and memory', function () {
140
118
  this.timeout(60000);
141
119
  const scratch = (0, scratch_database_1.useScratchDatabase)();
142
- const servers = [];
143
- let dirs;
144
- let hubKeys;
145
- let appiumLogs;
146
- let restore;
147
- let saved;
148
- let authDisabledBefore;
149
- let commandAuthBefore;
150
- let umbrella;
151
- let hubUrl;
152
- let nodeOrigin;
120
+ const pair = (0, hub_node_pair_1.useHubAndNode)(scratch, [
121
+ SessionMetricsService_1.SessionMetricsService,
122
+ NodeMetricsStore_1.NodeMetricsStore,
123
+ nodeMetrics_1.NodeMetricsSupport,
124
+ SessionDeviceLogs_1.SessionDeviceLogs,
125
+ ]);
153
126
  let nodeMetrics;
154
- before(() => __awaiter(this, void 0, void 0, function* () {
155
- appiumLogs = (0, appium_umbrella_1.quietAppiumLogs)();
156
- dirs = [fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'xenon-heartbeat-keys-'))];
157
- hubKeys = new JwtKeyService_1.JwtKeyService();
158
- yield hubKeys.init(dirs[0]);
159
- }));
160
- after(() => {
161
- appiumLogs.restore();
162
- for (const dir of dirs)
163
- fs_1.default.rmSync(dir, { recursive: true, force: true });
164
- });
165
- beforeEach(() => __awaiter(this, void 0, void 0, function* () {
166
- restore = (0, container_registration_1.saveRegistrations)(JwtKeyService_1.JwtKeyService, hubSessionToken_1.HubSessionTokenIssuer, device_managers_1.XenonManager, appiumUmbrella_1.AppiumUmbrella, nodeSessionStatus_1.NodeSessionProbeSupport, SessionMetricsService_1.SessionMetricsService, NodeMetricsStore_1.NodeMetricsStore, nodeMetrics_1.NodeMetricsSupport);
127
+ beforeEach(() => {
167
128
  nodeMetrics = new NodeSideMetrics();
168
129
  typedi_1.Container.set(SessionMetricsService_1.SessionMetricsService, nodeMetrics);
169
130
  typedi_1.Container.set(NodeMetricsStore_1.NodeMetricsStore, new NodeMetricsStore_1.NodeMetricsStore());
170
131
  typedi_1.Container.set(nodeMetrics_1.NodeMetricsSupport, new nodeMetrics_1.NodeMetricsSupport());
171
- // One process plays both sides: the hub's keys sign, the node checks them.
172
- typedi_1.Container.set(JwtKeyService_1.JwtKeyService, hubKeys);
173
- typedi_1.Container.set(hubSessionToken_1.HubSessionTokenIssuer, new hubSessionToken_1.HubSessionTokenIssuer());
174
- typedi_1.Container.set(appiumUmbrella_1.AppiumUmbrella, new appiumUmbrella_1.AppiumUmbrella());
175
- typedi_1.Container.set(nodeSessionStatus_1.NodeSessionProbeSupport, new nodeSessionStatus_1.NodeSessionProbeSupport());
176
- typedi_1.Container.set(device_managers_1.XenonManager, {
177
- getMaxSessionCount: () => undefined,
178
- deviceInstances: () => __awaiter(this, void 0, void 0, function* () { return []; }),
179
- });
180
- const context = typedi_1.Container.get(PluginContext_1.PluginContext);
181
- saved = {
182
- store: device_store_1.DeviceStoreFactory._deviceStore,
183
- pending: device_store_1.DeviceStoreFactory._pendingSessionStore,
184
- context: Object.assign({}, context),
185
- };
186
- device_store_1.DeviceStoreFactory._deviceStore = new prisma_store_1.PrismaDeviceStore();
187
- device_store_1.DeviceStoreFactory._pendingSessionStore = new prisma_store_1.PrismaPendingSessionStore();
188
- authDisabledBefore = config_1.config.authDisabled;
189
- config_1.config.authDisabled = false;
190
- // Per-command auth on: the node then takes the hub's token and nothing else.
191
- commandAuthBefore = process.env.XENON_REQUIRE_COMMAND_AUTH;
192
- process.env.XENON_REQUIRE_COMMAND_AUTH = '1';
193
- yield scratch.db.pendingSession.deleteMany({});
194
- yield scratch.db.device.deleteMany({});
195
- }));
196
- afterEach(() => __awaiter(this, void 0, void 0, function* () {
197
- for (const s of SessionManager_1.SESSION_MANAGER.getAllSessions())
198
- SessionManager_1.SESSION_MANAGER.removeSession(s.getId());
199
- device_store_1.DeviceStoreFactory._deviceStore = saved.store;
200
- device_store_1.DeviceStoreFactory._pendingSessionStore = saved.pending;
201
- Object.assign(typedi_1.Container.get(PluginContext_1.PluginContext), saved.context);
202
- config_1.config.authDisabled = authDisabledBefore;
203
- if (commandAuthBefore === undefined)
204
- delete process.env.XENON_REQUIRE_COMMAND_AUTH;
205
- else
206
- process.env.XENON_REQUIRE_COMMAND_AUTH = commandAuthBefore;
207
- sinon_1.default.restore();
208
- restore();
209
- for (const s of servers.splice(0)) {
210
- s.closeAllConnections();
211
- yield new Promise((resolve) => http_1.default.Server.prototype.close.call(s, () => resolve()));
212
- }
213
- }));
214
- const port = (s) => s.address().port;
215
- /** A hub (its public keys) and a node. */
216
- function boot() {
217
- return __awaiter(this, void 0, void 0, function* () {
218
- const baseDriver = (0, appium_umbrella_1.appiumBaseDriver)();
219
- const hubServer = yield baseDriver.server({
220
- routeConfiguringFunction: baseDriver.routeConfiguringFunction((0, appium_umbrella_1.umbrellaWith)([])),
221
- port: 0,
222
- hostname: '127.0.0.1',
223
- basePath: '/wd/hub',
224
- cliArgs: { basePath: '/wd/hub' },
225
- serverUpdaters: [
226
- (app) => {
227
- app.get('/xenon/api/auth/jwks.json', (_req, res) => res.json(hubKeys.jwks()));
228
- },
229
- ],
230
- });
231
- servers.push(hubServer);
232
- hubUrl = `http://127.0.0.1:${port(hubServer)}`;
233
- const pluginArgs = Object.assign(Object.assign({}, IPluginArgs_1.DefaultPluginArgs), { hub: hubUrl, bindHostOrIp: '127.0.0.1', enableDashboard: false, deviceAvailabilityTimeoutMs: 1000, deviceAvailabilityQueryIntervalMs: 100 });
234
- umbrella = (0, appium_umbrella_1.umbrellaWith)([[plugin_1.XenonPlugin, 'xenon']]);
235
- const nodeServer = yield baseDriver.server({
236
- routeConfiguringFunction: baseDriver.routeConfiguringFunction(umbrella),
237
- port: 0,
238
- hostname: '127.0.0.1',
239
- basePath: '/node',
240
- cliArgs: { basePath: '/node' },
241
- serverUpdaters: [
242
- (app) => {
243
- (0, registerCommandAuth_1.registerSessionGateway)(app, { basePath: '/node' }, (0, registerCommandAuth_1.commandAuthDeps)({ enabled: () => true, authDisabled: () => false, logger: quiet }), (0, defaultGateway_1.nodeGatewayOptions)(hubUrl));
244
- // What ServerManager mounts under /xenon/api on a node.
245
- const api = express_1.default.Router();
246
- (0, nodeSessionStatus_1.registerNodeSessionStatus)(api, pluginArgs);
247
- (0, nodeSessionMetrics_1.registerNodeSessionMetrics)(api, pluginArgs);
248
- app.use('/xenon/api', api);
249
- },
250
- ],
251
- });
252
- servers.push(nodeServer);
253
- nodeOrigin = `http://127.0.0.1:${port(nodeServer)}`;
254
- typedi_1.Container.get(PluginContext_1.PluginContext).setContext(pluginArgs, port(nodeServer), NODE_ID, '/node');
255
- yield scratch.db.device.create({
256
- data: {
257
- udid: 'phone-1',
258
- host: nodeOrigin,
259
- nodeId: NODE_ID,
260
- platform: 'android',
261
- name: 'phone-1',
262
- sdk: '14',
263
- busy: false,
264
- userBlocked: false,
265
- offline: false,
266
- },
267
- });
268
- });
269
- }
270
- /** A session on the node, created as the hub creates it. */
271
- function nodeSession() {
272
- return __awaiter(this, void 0, void 0, function* () {
273
- const token = yield typedi_1.Container.get(hubSessionToken_1.HubSessionTokenIssuer).createTokenFor({
274
- userId: 'alice',
275
- udid: 'phone-1',
276
- host: nodeOrigin,
277
- });
278
- const res = yield (0, loopbackRequest_1.default)(nodeOrigin)
279
- .post('/node/session')
280
- .set(hubSessionToken_1.HUB_TOKEN_HEADER, token)
281
- .send({
282
- capabilities: {
283
- alwaysMatch: {
284
- platformName: 'Android',
285
- 'appium:automationName': appium_umbrella_1.FAKE_AUTOMATION,
286
- 'appium:newCommandTimeout': 0,
287
- 'appium:udid': 'phone-1',
288
- 'xe:options': { recordVideo: false },
289
- },
290
- firstMatch: [{}],
291
- },
292
- });
293
- (0, chai_1.expect)(res.status, JSON.stringify(res.body)).to.equal(200);
294
- return res.body.value.sessionId;
132
+ // The node records the session's device log too; not here.
133
+ typedi_1.Container.set(SessionDeviceLogs_1.SessionDeviceLogs, {
134
+ start: () => __awaiter(this, void 0, void 0, function* () { return undefined; }),
135
+ stop: () => __awaiter(this, void 0, void 0, function* () { return undefined; }),
295
136
  });
296
- }
297
- /** The hub's object for that session. */
298
- const hubSide = (sessionId) => new RemoteSession_1.RemoteSession({
299
- sessionId,
300
- device: { udid: 'phone-1', host: nodeOrigin, nodeId: NODE_ID, platform: 'android' },
301
- sessionResponse: {},
302
- xenonOption: {},
303
- baseUrl: `${nodeOrigin}/node`,
304
137
  });
138
+ const boot = () => pair.boot();
139
+ const nodeSession = () => pair.nodeSession();
140
+ const hubSide = (sessionId) => pair.hubSide(sessionId);
305
141
  it("the hub collects a node session's figures as it runs, and the last ones when it ends", () => __awaiter(this, void 0, void 0, function* () {
306
142
  yield boot();
307
143
  const sessionId = yield nodeSession();
@@ -312,8 +148,8 @@ describe('a hub collects a node session’s CPU and memory', function () {
312
148
  const hub = new HubSideMetrics();
313
149
  const device = {
314
150
  udid: 'phone-1',
315
- host: nodeOrigin,
316
- nodeId: NODE_ID,
151
+ host: pair.nodeOrigin,
152
+ nodeId: hub_node_pair_1.NODE_ID,
317
153
  platform: 'android',
318
154
  realDevice: true,
319
155
  };
@@ -323,11 +159,7 @@ describe('a hub collects a node session’s CPU and memory', function () {
323
159
  yield until(() => hub.written.length === 0 &&
324
160
  typedi_1.Container.get(NodeMetricsStore_1.NodeMetricsStore).read(sessionId, null).samples.length === 0);
325
161
  nodeMetrics.hooks[0].onSample(at(3000));
326
- const token = yield typedi_1.Container.get(hubSessionToken_1.HubSessionTokenIssuer).tokenFor(sessionId);
327
- const del = yield (0, loopbackRequest_1.default)(nodeOrigin)
328
- .delete(`/node/session/${sessionId}`)
329
- .set(hubSessionToken_1.HUB_TOKEN_HEADER, token);
330
- (0, chai_1.expect)(del.status, JSON.stringify(del.body)).to.equal(200);
162
+ yield pair.deleteOnNode(sessionId);
331
163
  (0, chai_1.expect)(nodeMetrics.stopped).to.equal(1);
332
164
  (0, chai_1.expect)(typedi_1.Container.get(NodeMetricsStore_1.NodeMetricsStore).read(sessionId, 2000).state).to.equal('ended');
333
165
  yield hub.stop(sessionId);
@@ -347,7 +179,7 @@ describe('a hub collects a node session’s CPU and memory', function () {
347
179
  device_version: '14',
348
180
  desired_capabilities: '{}',
349
181
  session_capabilities: '{}',
350
- node_id: NODE_ID,
182
+ node_id: hub_node_pair_1.NODE_ID,
351
183
  has_live_video: false,
352
184
  status: 'running',
353
185
  },
@@ -355,8 +187,8 @@ describe('a hub collects a node session’s CPU and memory', function () {
355
187
  const hub = new HubStoringMetrics();
356
188
  const device = {
357
189
  udid: 'phone-1',
358
- host: nodeOrigin,
359
- nodeId: NODE_ID,
190
+ host: pair.nodeOrigin,
191
+ nodeId: hub_node_pair_1.NODE_ID,
360
192
  platform: 'android',
361
193
  realDevice: true,
362
194
  };
@@ -386,8 +218,8 @@ describe('a hub collects a node session’s CPU and memory', function () {
386
218
  const hub = new HubSideMetrics();
387
219
  const device = {
388
220
  udid: 'phone-1',
389
- host: nodeOrigin,
390
- nodeId: NODE_ID,
221
+ host: pair.nodeOrigin,
222
+ nodeId: hub_node_pair_1.NODE_ID,
391
223
  platform: 'android',
392
224
  realDevice: true,
393
225
  };
@@ -38,6 +38,7 @@ const RemoteSession_1 = require("../../src/sessions/RemoteSession");
38
38
  const appiumUmbrella_1 = require("../../src/sessions/appiumUmbrella");
39
39
  const XenonSession_1 = require("../../src/sessions/XenonSession");
40
40
  const config_1 = require("../../src/config");
41
+ const SessionDeviceLogs_1 = require("../../src/services/logcat/SessionDeviceLogs");
41
42
  const container_registration_1 = require("../helpers/container-registration");
42
43
  const scratch_database_1 = require("../helpers/scratch-database");
43
44
  const appium_umbrella_1 = require("../helpers/appium-umbrella");
@@ -80,12 +81,18 @@ describe('the hub’s heartbeat on a node’s session', function () {
80
81
  fs_1.default.rmSync(dir, { recursive: true, force: true });
81
82
  });
82
83
  beforeEach(() => __awaiter(this, void 0, void 0, function* () {
83
- restore = (0, container_registration_1.saveRegistrations)(JwtKeyService_1.JwtKeyService, hubSessionToken_1.HubSessionTokenIssuer, device_managers_1.XenonManager, appiumUmbrella_1.AppiumUmbrella, nodeSessionStatus_1.NodeSessionProbeSupport);
84
+ restore = (0, container_registration_1.saveRegistrations)(JwtKeyService_1.JwtKeyService, hubSessionToken_1.HubSessionTokenIssuer, device_managers_1.XenonManager, appiumUmbrella_1.AppiumUmbrella, nodeSessionStatus_1.NodeSessionProbeSupport, SessionDeviceLogs_1.SessionDeviceLogs);
84
85
  // One process plays both sides: the hub's keys sign, the node checks them.
85
86
  typedi_1.Container.set(JwtKeyService_1.JwtKeyService, hubKeys);
86
87
  typedi_1.Container.set(hubSessionToken_1.HubSessionTokenIssuer, new hubSessionToken_1.HubSessionTokenIssuer());
87
88
  typedi_1.Container.set(appiumUmbrella_1.AppiumUmbrella, new appiumUmbrella_1.AppiumUmbrella());
88
89
  typedi_1.Container.set(nodeSessionStatus_1.NodeSessionProbeSupport, new nodeSessionStatus_1.NodeSessionProbeSupport());
90
+ // A node records the device log of each session its hub creates; its
91
+ // phone here is a row, so nothing may reach this machine's adb.
92
+ typedi_1.Container.set(SessionDeviceLogs_1.SessionDeviceLogs, {
93
+ start: () => __awaiter(this, void 0, void 0, function* () { return undefined; }),
94
+ stop: () => __awaiter(this, void 0, void 0, function* () { return undefined; }),
95
+ });
89
96
  typedi_1.Container.set(device_managers_1.XenonManager, {
90
97
  getMaxSessionCount: () => undefined,
91
98
  deviceInstances: () => __awaiter(this, void 0, void 0, function* () { return []; }),
@@ -46,6 +46,9 @@ const chai_1 = require("chai");
46
46
  const fs = __importStar(require("fs"));
47
47
  const path = __importStar(require("path"));
48
48
  const os = __importStar(require("os"));
49
+ const child_process_1 = require("child_process");
50
+ const crypto_1 = require("crypto");
51
+ const sinon = __importStar(require("sinon"));
49
52
  const node_forge_1 = require("node-forge");
50
53
  const CertManager_1 = require("../../../src/services/interceptor/CertManager");
51
54
  describe('CertManager', () => {
@@ -98,4 +101,90 @@ describe('CertManager', () => {
98
101
  (0, chai_1.expect)(fname).to.match(/^[0-9a-f]{8}\.0$/);
99
102
  (0, chai_1.expect)(typeof ca.subjectHash).to.equal('string');
100
103
  }));
104
+ describe('serial number', () => {
105
+ // The serial was Date.now() in hex padded to 16 digits: always 00 00 01 ...,
106
+ // an INTEGER with illegal leading zeros. OpenSSL 3 (Node's included), Go
107
+ // and BoringSSL refuse such a certificate outright.
108
+ it('is a CA OpenSSL can load', () => __awaiter(void 0, void 0, void 0, function* () {
109
+ const ca = yield new CertManager_1.CertManager(dir).ensure();
110
+ (0, chai_1.expect)(() => new crypto_1.X509Certificate(fs.readFileSync(ca.certPath))).to.not.throw();
111
+ }));
112
+ it('is positive, minimally encoded and at least 64 random bits', () => __awaiter(void 0, void 0, void 0, function* () {
113
+ const ca = yield new CertManager_1.CertManager(dir).ensure();
114
+ const serial = new crypto_1.X509Certificate(fs.readFileSync(ca.certPath)).serialNumber;
115
+ const first = parseInt(serial.slice(0, 2), 16);
116
+ (0, chai_1.expect)(first, 'no leading zero byte').to.be.greaterThan(0);
117
+ (0, chai_1.expect)(first, 'not negative').to.be.lessThan(0x80);
118
+ (0, chai_1.expect)(serial.length / 2)
119
+ .to.be.at.least(8)
120
+ .and.at.most(20);
121
+ }));
122
+ it('differs between two CAs generated in the same millisecond', () => __awaiter(void 0, void 0, void 0, function* () {
123
+ const other = fs.mkdtempSync(path.join(os.tmpdir(), 'xenon-cert-'));
124
+ const clock = sinon.useFakeTimers({ now: 1760000000000, toFake: ['Date'] });
125
+ try {
126
+ const a = yield new CertManager_1.CertManager(dir).ensure();
127
+ const b = yield new CertManager_1.CertManager(other).ensure();
128
+ (0, chai_1.expect)(new crypto_1.X509Certificate(fs.readFileSync(a.certPath)).serialNumber).to.not.equal(new crypto_1.X509Certificate(fs.readFileSync(b.certPath)).serialNumber);
129
+ }
130
+ finally {
131
+ clock.restore();
132
+ fs.rmSync(other, { recursive: true, force: true });
133
+ }
134
+ }));
135
+ it('replaces a CA an earlier version wrote with the bad serial', () => __awaiter(void 0, void 0, void 0, function* () {
136
+ writeCa(dir, '000001a10d75af19');
137
+ const ca = yield new CertManager_1.CertManager(dir).ensure();
138
+ (0, chai_1.expect)(() => new crypto_1.X509Certificate(fs.readFileSync(ca.certPath))).to.not.throw();
139
+ }));
140
+ it('keeps a CA OpenSSL can load', () => __awaiter(void 0, void 0, void 0, function* () {
141
+ writeCa(dir, '1a10d75af19a2b3c');
142
+ const before = fs.readFileSync(path.join(dir, 'certs', 'ca.pem'), 'utf8');
143
+ yield new CertManager_1.CertManager(dir).ensure();
144
+ (0, chai_1.expect)(fs.readFileSync(path.join(dir, 'certs', 'ca.pem'), 'utf8')).to.equal(before);
145
+ }));
146
+ });
147
+ describe('Android file name', () => {
148
+ // Android looks a system CA up by <subject_hash_old>.0. The name was
149
+ // openssl's, else a SHA-1 of the PEM, which names no certificate: with the
150
+ // bad serial openssl couldn't load the CA, so the fallback always ran.
151
+ it("is OpenSSL's subject_hash_old, with no openssl binary on the PATH", function () {
152
+ return __awaiter(this, void 0, void 0, function* () {
153
+ try {
154
+ (0, child_process_1.execFileSync)('openssl', ['version'], { stdio: 'ignore' });
155
+ }
156
+ catch (_a) {
157
+ this.skip();
158
+ }
159
+ const ca = yield new CertManager_1.CertManager(dir).ensure();
160
+ const expected = (0, child_process_1.execFileSync)('openssl', ['x509', '-inform', 'PEM', '-subject_hash_old', '-noout', '-in', ca.certPath], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
161
+ (0, chai_1.expect)(ca.subjectHash).to.equal(expected);
162
+ const pathBefore = process.env.PATH;
163
+ process.env.PATH = '';
164
+ try {
165
+ (0, chai_1.expect)(new CertManager_1.CertManager(dir).androidCertFilename()).to.equal(`${expected}.0`);
166
+ }
167
+ finally {
168
+ process.env.PATH = pathBefore;
169
+ }
170
+ });
171
+ });
172
+ });
101
173
  });
174
+ function writeCa(dir, serialHex) {
175
+ fs.mkdirSync(path.join(dir, 'certs'), { recursive: true });
176
+ fs.mkdirSync(path.join(dir, 'keys'), { recursive: true });
177
+ const keys = node_forge_1.pki.rsa.generateKeyPair(1024);
178
+ const cert = node_forge_1.pki.createCertificate();
179
+ cert.publicKey = keys.publicKey;
180
+ cert.serialNumber = serialHex;
181
+ cert.validity.notBefore = new Date(Date.now() - 60000);
182
+ cert.validity.notAfter = new Date(Date.now() + 365 * 24 * 3600000);
183
+ const attrs = [{ name: 'commonName', value: 'Xenon MITM Root CA' }];
184
+ cert.setSubject(attrs);
185
+ cert.setIssuer(attrs);
186
+ cert.setExtensions([{ name: 'basicConstraints', cA: true, critical: true }]);
187
+ cert.sign(keys.privateKey, node_forge_1.md.sha256.create());
188
+ fs.writeFileSync(path.join(dir, 'certs', 'ca.pem'), node_forge_1.pki.certificateToPem(cert), 'utf8');
189
+ fs.writeFileSync(path.join(dir, 'keys', 'ca.private.key'), node_forge_1.pki.privateKeyToPem(keys.privateKey));
190
+ }
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ require("reflect-metadata");
7
+ const chai_1 = require("chai");
8
+ const sinon_1 = __importDefault(require("sinon"));
9
+ const NodeDeviceLogStore_1 = require("../../src/services/logcat/NodeDeviceLogStore");
10
+ const nodeDeviceLogs_1 = require("../../src/services/logcat/nodeDeviceLogs");
11
+ const row = (n) => ({ message: `line ${n}`, timestamp: new Date(1000 + n) });
12
+ const rows = (from, to) => Array.from({ length: to - from + 1 }, (_, i) => row(from + i));
13
+ describe('NodeDeviceLogStore: a node holds a session’s device log lines for its hub', () => {
14
+ let now;
15
+ let store;
16
+ beforeEach(() => {
17
+ now = 1000000;
18
+ store = new NodeDeviceLogStore_1.NodeDeviceLogStore();
19
+ store.now = () => now;
20
+ });
21
+ it('numbers each line, and answers every one without `after`', () => {
22
+ store.begin('s1');
23
+ store.add('s1', [row(1), row(2)]);
24
+ store.add('s1', [row(3)]);
25
+ (0, chai_1.expect)(store.read('s1', null)).to.deep.equal({
26
+ state: 'recording',
27
+ more: false,
28
+ lines: [
29
+ { seq: 1, message: 'line 1', timestamp: 1001 },
30
+ { seq: 2, message: 'line 2', timestamp: 1002 },
31
+ { seq: 3, message: 'line 3', timestamp: 1003 },
32
+ ],
33
+ });
34
+ });
35
+ it('drops what the hub has: the lines at or before `after`', () => {
36
+ store.begin('s1');
37
+ store.add('s1', rows(1, 3));
38
+ (0, chai_1.expect)(store.read('s1', 2).lines.map((l) => l.seq)).to.deep.equal([3]);
39
+ // Gone for good, even to an ask that names none.
40
+ (0, chai_1.expect)(store.read('s1', null).lines.map((l) => l.seq)).to.deep.equal([3]);
41
+ store.add('s1', [row(4)]);
42
+ (0, chai_1.expect)(store.read('s1', 3).lines.map((l) => l.seq)).to.deep.equal([4]);
43
+ });
44
+ it(`answers at most ${nodeDeviceLogs_1.NODE_DEVICE_LOG_PAGE} lines at a time, and says there are more`, () => {
45
+ store.begin('s1');
46
+ store.add('s1', rows(1, nodeDeviceLogs_1.NODE_DEVICE_LOG_PAGE + 5));
47
+ const first = store.read('s1', null);
48
+ (0, chai_1.expect)(first.lines).to.have.length(nodeDeviceLogs_1.NODE_DEVICE_LOG_PAGE);
49
+ (0, chai_1.expect)(first.more).to.equal(true);
50
+ const second = store.read('s1', nodeDeviceLogs_1.NODE_DEVICE_LOG_PAGE);
51
+ (0, chai_1.expect)(second.lines.map((l) => l.seq)).to.deep.equal([1, 2, 3, 4, 5].map((n) => nodeDeviceLogs_1.NODE_DEVICE_LOG_PAGE + n));
52
+ (0, chai_1.expect)(second.more).to.equal(false);
53
+ });
54
+ it('says a session ended, and keeps it 10 minutes for the hub’s last ask', () => {
55
+ store.begin('s1');
56
+ store.add('s1', rows(1, 2));
57
+ store.end('s1');
58
+ (0, chai_1.expect)(store.read('s1', null).state).to.equal('ended');
59
+ now += nodeDeviceLogs_1.NODE_DEVICE_LOGS_KEEP_AFTER_END_MS - 1;
60
+ (0, chai_1.expect)(store.read('s1', 1).lines.map((l) => l.seq)).to.deep.equal([2]);
61
+ now += 1;
62
+ (0, chai_1.expect)(store.read('s1', null)).to.deep.equal({ state: 'off', lines: [], more: false });
63
+ });
64
+ it('forgets an ended session 10 minutes on, though nothing else happens', () => {
65
+ const clock = sinon_1.default.useFakeTimers({ now });
66
+ try {
67
+ const timed = new NodeDeviceLogStore_1.NodeDeviceLogStore();
68
+ timed.begin('s1');
69
+ timed.add('s1', rows(1, 3));
70
+ timed.end('s1');
71
+ clock.tick(nodeDeviceLogs_1.NODE_DEVICE_LOGS_KEEP_AFTER_END_MS);
72
+ (0, chai_1.expect)(timed.entries.has('s1')).to.equal(false);
73
+ }
74
+ finally {
75
+ clock.restore();
76
+ }
77
+ });
78
+ it('forgets an ended session nobody asks about, at the next session', () => {
79
+ store.begin('s1');
80
+ store.end('s1');
81
+ now += nodeDeviceLogs_1.NODE_DEVICE_LOGS_KEEP_AFTER_END_MS;
82
+ store.begin('s2');
83
+ (0, chai_1.expect)(store.entries.has('s1')).to.equal(false);
84
+ });
85
+ it('says off for a session it holds nothing for, and keeps nothing for it', () => {
86
+ store.add('nobody', rows(1, 2));
87
+ (0, chai_1.expect)(store.read('nobody', null)).to.deep.equal({ state: 'off', lines: [], more: false });
88
+ });
89
+ it('knows whether a hub has asked about a session', () => {
90
+ store.begin('s1');
91
+ (0, chai_1.expect)(store.claimed('s1')).to.equal(false);
92
+ store.read('s1', null);
93
+ (0, chai_1.expect)(store.claimed('s1')).to.equal(true);
94
+ (0, chai_1.expect)(store.claimed('unknown')).to.equal(false);
95
+ });
96
+ it('forgets a session it was told to', () => {
97
+ store.begin('s1');
98
+ store.add('s1', rows(1, 2));
99
+ store.forget('s1');
100
+ (0, chai_1.expect)(store.read('s1', null).state).to.equal('off');
101
+ });
102
+ });