network-renewal.test.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import test from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import { mkdtemp, readFile, rm } from 'node:fs/promises';
  4. import { tmpdir } from 'node:os';
  5. import { join, resolve, sep } from 'node:path';
  6. import { captureRefreshGrant, createNetworkRenewal, sessionExpiry, mergeSessionCredentials, refreshGrantsFromMsalCache, hasMatchingRefreshGrant } from '../src/network-renewal.js';
  7. import { createProtectedJson } from '../src/protected-json.js';
  8. const instant = 1800000000000, tenant = '11111111-1111-1111-1111-111111111111', user = '22222222-2222-2222-2222-222222222222', client = '33333333-3333-3333-3333-333333333333';
  9. const token = (changes = {}) => `fixture.${Buffer.from(JSON.stringify({ tid: tenant, oid: user, appid: client, aud: 'fixture-resource', scp: 'read history', exp: (instant + 120000) / 1000, ...changes })).toString('base64url')}.private-signature`;
  10. const session = (access = token()) => ({ log: { entries: [{ request: { url: 'https://teams.cloud.microsoft/api/chatsvc/v1/users/ME/conversations/test/messages', headers: [{ name: 'Authorization', value: `Bearer ${access}` }] }, response: { private: 'preserve-payload' } }] } });
  11. const authCapture = (access = token()) => ({ url: `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/token`, method: 'POST', headers: [{ name: 'Origin', value: 'https://teams.cloud.microsoft' }],
  12. body: new URLSearchParams({ client_id: client, scope: 'fixture-resource/read offline_access', redirect_uri: 'https://teams.cloud.microsoft/', grant_type: 'authorization_code', code: 'one-use-private-code', code_verifier: 'private-verifier' }).toString(),
  13. response: { token_type: 'Bearer', access_token: access, refresh_token: 'private-refresh', id_token: 'never-persist-id-token' }, now: instant });
  14. function memoryVault() { let value; return { read: async () => structuredClone(value), write: async next => { value = structuredClone(next); }, value: () => value }; }
  15. const response = (payload, status = 200, headers = {}) => new Response(JSON.stringify(payload), { status, headers });
  16. const freshResponse = (changes = {}) => response({ token_type: 'Bearer', access_token: token({ exp: (instant + 3600000) / 1000, ...changes }), refresh_token: 'rotated-private-refresh' });
  17. async function fixture(options = {}) {
  18. const vault = options.vault || memoryVault(), requests = []; let clock = instant;
  19. const renewal = createNetworkRenewal({ dataDir: 'unused', vault, now: () => clock, fetch: async (...args) => { requests.push(args); return options.fetch ? options.fetch(...args) : freshResponse(); } });
  20. await renewal.install([captureRefreshGrant(authCapture())], session(), options.profile);
  21. return { renewal, vault, requests, advance: milliseconds => { clock += milliseconds; } };
  22. }
  23. test('expired or nearly expired MSAL access tokens cannot declare browser recovery complete', () => {
  24. const har = session();
  25. for (const expiry of [instant - 60000, instant, instant + 30000]) {
  26. const grant = captureRefreshGrant({ ...authCapture(token({ exp: expiry / 1000 })), now: 0 });
  27. assert.equal(hasMatchingRefreshGrant(har, [grant], instant), false);
  28. }
  29. const fresh = captureRefreshGrant(authCapture(token({ exp: (instant + 3600000) / 1000 })));
  30. assert.equal(hasMatchingRefreshGrant(har, [fresh], instant), true);
  31. assert.equal(hasMatchingRefreshGrant(session(token({ oid: '44444444-4444-4444-4444-444444444444' })), [fresh], instant), false);
  32. assert.equal(hasMatchingRefreshGrant(session(token({ scp: 'read history extra' })), [fresh], instant), false);
  33. });
  34. test('capture accepts only observed public-client grants on allowed Microsoft endpoints and never retains code or verifier', () => {
  35. const grant = captureRefreshGrant(authCapture()); assert.ok(grant);
  36. assert.doesNotMatch(JSON.stringify(grant), /private-code|private-verifier|never-persist|authorization_code/);
  37. for (const mutate of [c => c.url = 'https://evil.example/token', c => c.url += '?redirect=private', c => c.headers[0].value = 'https://evil.example',
  38. c => c.body += '&client_secret=private', c => c.body += '&client_id=other', c => c.response.access_token = token({ oid: 'unknown' }),
  39. c => c.response.access_token = token({ appid: tenant }), c => c.response.access_token = token({ tid: user }),
  40. c => c.body = c.body.replace(encodeURIComponent('https://teams.cloud.microsoft/'), encodeURIComponent('https://evil.example/'))]) {
  41. const c = authCapture(); mutate(c); assert.equal(captureRefreshGrant(c), null);
  42. }
  43. });
  44. test('observed broker query and redirect parameters are retained while unknown token URL parameters stay blocked', () => {
  45. const captured = authCapture();
  46. captured.url += `?client_id=${client}&brk_client_id=${user}&brk_redirect_uri=https%3A%2F%2Fteams.cloud.microsoft&client-request-id=${tenant}`;
  47. const form = new URLSearchParams(captured.body); form.set('redirect_uri', 'brk-multihub://outlook.office.com'); form.set('brk_client_id', user); form.set('brk_redirect_uri', 'https://teams.cloud.microsoft'); captured.body = form.toString();
  48. const grant = captureRefreshGrant(captured); assert.ok(grant); assert.equal(grant.params.brk_client_id, user);
  49. assert.equal(captureRefreshGrant({ ...captured, url: captured.url + '&redirect_to=https://evil.example' }), null);
  50. });
  51. test('MSAL cache establishes same-client same-account renewal even without a token POST for the captured resource', () => {
  52. const har = session(token({ aud: 'https://ic3.teams.office.com' }));
  53. const proof = { credentialType: 'AccessToken', homeAccountId: 'own-home', clientId: client, environment: 'login.microsoftonline.com', realm: tenant,
  54. secret: token({ aud: 'https://other-resource.example', exp: (instant + 3600000) / 1000 }), target: 'https://other-resource.example/read' };
  55. const refresh = { credentialType: 'RefreshToken', homeAccountId: 'own-home', clientId: client, environment: 'login.microsoftonline.com', secret: 'private-own-refresh' };
  56. const result = refreshGrantsFromMsalCache([proof, refresh], [], har, instant);
  57. assert.equal(result.length, 1); assert.equal(result[0].params.scope, 'https://ic3.teams.office.com/.default'); assert.equal(result[0].refreshToken, refresh.secret);
  58. for (const changes of [{ clientId: user }, { homeAccountId: 'foreign-home' }, { environment: 'evil.example' }]) assert.equal(refreshGrantsFromMsalCache([proof, { ...refresh, ...changes }], [], har, instant).length, 0);
  59. assert.equal(refreshGrantsFromMsalCache([{ ...proof, secret: token({ oid: tenant }) }, refresh], [], har, instant).length, 0);
  60. assert.equal(refreshGrantsFromMsalCache([proof, refresh], [], session(token({ aud: 'https://unobserved.example' })), instant).length, 0);
  61. });
  62. test('Teams root-slash aliases match and expanded MSAL cache scopes cannot send an invalid dynamic/.default mix', async () => {
  63. const access = token({ aud: 'https://outlook.office.com/', exp: (instant + 3600000) / 1000 });
  64. const cache = [{ credentialType: 'AccessToken', homeAccountId: 'own-home', clientId: client, environment: 'login.microsoftonline.com', realm: tenant,
  65. secret: access, target: 'https://outlook.office.com//read https://outlook.office.com//.default' },
  66. { credentialType: 'RefreshToken', homeAccountId: 'own-home', clientId: client, environment: 'login.microsoftonline.com', secret: 'private-refresh' }];
  67. const har = session(token({ aud: 'https://outlook.office.com' })), grants = refreshGrantsFromMsalCache(cache, [], har, instant);
  68. assert.equal(grants.length, 1); assert.equal(grants[0].params.scope, 'https://outlook.office.com/.default');
  69. const vault = memoryVault(); let scope;
  70. const renewal = createNetworkRenewal({ dataDir: 'unused', vault, now: () => instant, fetch: async (_, options) => {
  71. scope = new URLSearchParams(options.body).get('scope'); return response({ token_type: 'Bearer', access_token: access, refresh_token: 'rotated' });
  72. } });
  73. await renewal.install(grants, har); const result = await renewal.renew({ har, force: true });
  74. assert.equal(result.changed, true); assert.equal(result.status.state, 'renewed'); assert.equal(scope, 'https://outlook.office.com/.default');
  75. });
  76. test('fresh browser cookies never cross origins or account boundaries', () => {
  77. const old = session(); old.log.entries[0].request.headers.push({ name: 'Cookie', value: 'old' });
  78. const fresh = session(token({ exp: (instant + 3600000) / 1000 })); fresh.log.entries[0].request.headers.push({ name: 'Cookie', value: 'new' });
  79. assert.equal(mergeSessionCredentials(old, fresh, [], instant).log.entries[0].request.headers[1].value, 'new');
  80. fresh.log.entries[0].request.url = 'https://outlook.office.com/api/events';
  81. assert.equal(mergeSessionCredentials(old, fresh, [], instant).log.entries[0].request.headers[1].value, 'old');
  82. });
  83. test('renewal rotates a resource credential once, updates all matching headers and preserves payload and other resources', async () => {
  84. const f = await fixture(), har = session(); har.log.entries.push(...session(token({ aud: 'calendar-resource', exp: (instant + 7200000) / 1000 })).log.entries);
  85. const [a, b] = await Promise.all([f.renewal.renew({ har }), f.renewal.renew({ har })]);
  86. assert.equal(f.requests.length, 1); assert.equal(a, b); assert.equal(a.changed, true);
  87. const [url, options] = f.requests[0]; assert.equal(url, authCapture().url); assert.equal(options.redirect, 'error');
  88. assert.equal(new URLSearchParams(options.body).get('grant_type'), 'refresh_token'); assert.equal(new URLSearchParams(options.body).get('refresh_token'), 'private-refresh');
  89. assert.equal(options.headers.Origin, 'https://teams.cloud.microsoft');
  90. assert.equal(a.har.log.entries[0].response.private, 'preserve-payload'); assert.deepEqual(a.har.log.entries[1], har.log.entries[1]);
  91. assert.equal(har.log.entries[0].request.headers[0].value, `Bearer ${token()}`);
  92. assert.equal(f.vault.value().grants[0].refreshToken, 'rotated-private-refresh');
  93. assert.equal(a.status.state, 'renewed'); assert.equal(sessionExpiry(a.har), new Date(instant + 3600000).toISOString());
  94. assert.doesNotMatch(JSON.stringify(a.status), /private|11111111|22222222|33333333|fixture-resource/);
  95. });
  96. test('valid tokens make no refresh request; restart loads rotated cache without using a browser', async () => {
  97. const f = await fixture(); const valid = session(token({ exp: (instant + 7200000) / 1000 }));
  98. assert.equal((await f.renewal.renew({ har: valid })).changed, false); assert.equal(f.requests.length, 0);
  99. const renewed = await f.renewal.renew({ har: session() });
  100. let calls = 0; const restarted = createNetworkRenewal({ dataDir: 'unused', vault: f.vault, now: () => instant, fetch: async () => { calls++; throw new Error(); } });
  101. const result = await restarted.renew({ har: session() });
  102. assert.equal(result.changed, true); assert.deepEqual(result.har, renewed.har); assert.equal(calls, 0);
  103. });
  104. test('separate instances cannot install or use each other account refresh tokens', async () => {
  105. const first = await fixture(), secondVault = memoryVault(); let called = false;
  106. const second = createNetworkRenewal({ dataDir: 'second', vault: secondVault, now: () => instant, fetch: async () => { called = true; throw new Error(); } });
  107. const other = session(token({ oid: tenant }));
  108. await second.install([captureRefreshGrant(authCapture())], other);
  109. assert.equal(secondVault.value().grants.length, 0);
  110. assert.equal((await second.renew({ har: other })).changed, false); assert.equal(called, false);
  111. assert.equal((await first.renewal.renew({ har: session() })).changed, true);
  112. });
  113. test('wrong tenant, audience, account, client or reduced scopes cannot replace existing credentials', async () => {
  114. for (const changes of [{ tid: user }, { oid: tenant }, { appid: user }, { aud: 'another-resource' }, { scp: 'read' }, { exp: instant / 1000 }]) {
  115. const f = await fixture({ fetch: () => freshResponse(changes) });
  116. const result = await f.renewal.renew({ har: session() });
  117. assert.equal(result.changed, false); assert.equal(result.status.state, 'retrying');
  118. assert.equal(f.vault.value().grants[0].refreshToken, 'private-refresh');
  119. }
  120. });
  121. test('429 respects Retry-After and transient outages back off without asking for MFA', async () => {
  122. const f = await fixture({ fetch: () => response({ error: 'temporarily_unavailable', error_description: 'never-output-private-details' }, 429, { 'Retry-After': '600' }) });
  123. const result = await f.renewal.renew({ har: session() }); assert.equal(result.status.state, 'retrying'); assert.equal(result.status.interactionRequired, false);
  124. assert.equal(result.status.nextAttemptAt, new Date(instant + 600000).toISOString());
  125. f.advance(599000); await f.renewal.renew({ har: session(), force: true }); assert.equal(f.requests.length, 1);
  126. f.advance(1001); await f.renewal.renew({ har: session() }); assert.equal(f.requests.length, 2);
  127. assert.doesNotMatch(JSON.stringify(result.status), /never-output|private/);
  128. });
  129. test('invalid_grant requests saved browser session recovery before interaction and stops retrying after interaction is required', async () => {
  130. const f = await fixture({ profile: { id: 'login-44444444-4444-4444-4444-444444444444', browser: 'msedge' }, fetch: () => response({ error: 'invalid_grant', error_description: 'MFA-private' }, 400) });
  131. const result = await f.renewal.renew({ har: session() }); assert.equal(result.status.browserRequired, true); assert.equal(result.status.interactionRequired, false);
  132. f.renewal.recoveryFailed({ interactive: true }); await f.renewal.renew({ har: session(), force: true }); assert.equal(f.requests.length, 1);
  133. assert.equal(f.renewal.status().state, 'interaction_required');
  134. await f.renewal.install([captureRefreshGrant(authCapture())], session()); assert.equal(f.renewal.status().interactionRequired, false);
  135. });
  136. test('cancellation cannot publish new credentials or classify an abort as MFA', async () => {
  137. const controller = new AbortController(); const f = await fixture({ fetch: async () => { controller.abort(); return freshResponse(); } });
  138. const result = await f.renewal.renew({ har: session(), signal: controller.signal });
  139. assert.equal(result.changed, false); assert.equal(result.status.interactionRequired, false);
  140. });
  141. test('recovered browser tokens only replace same-account same-resource tokens with sufficient scopes', () => {
  142. const har = session(), candidate = session(token({ exp: (instant + 3600000) / 1000 }));
  143. assert.notDeepEqual(mergeSessionCredentials(har, candidate, [], instant), har);
  144. for (const changes of [{ oid: tenant }, { aud: 'wrong-resource' }, { scp: 'read' }]) assert.deepEqual(mergeSessionCredentials(har, session(token({ exp: (instant + 3600000) / 1000, ...changes })), [], instant), har);
  145. });
  146. test('encrypted vault survives reconstruction and does not store raw tokens on Windows', async () => {
  147. const directory = await mkdtemp(join(tmpdir(), 'teams-renewal-vault-')), path = join(directory, 'network-renewal.json');
  148. try { const value = { refreshToken: 'private-long-lived-token', profile: 'private-profile' };
  149. await createProtectedJson(path).write(value);
  150. assert.deepEqual(await createProtectedJson(path).read(), value);
  151. if (process.platform === 'win32') assert.doesNotMatch(await readFile(path, 'utf8'), /private-long-lived-token|private-profile/);
  152. } finally { assert.ok(resolve(directory).startsWith(resolve(tmpdir()) + sep)); await rm(directory, { recursive: true, force: true }); }
  153. });