BlueGit

ict rusty-teams

feat(session): tenant sessions for orgs the account is a guest in

The token lookup kept only tokens of the account's home tenant, so a
guest org could not be reached at all. Session::in_tenant asks the page
for tokens of one tenant and redeems the account's refresh token at that
tenant's token endpoint, the way Teams reaches a guest org. Each tenant
session holds its own token cache, so home and guest run side by side.

Checked live with one account that is a member in one tenant and a guest
in another: joinedTeams and chatsvc conversations answer per tenant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Michael Wallner · pushed by metis

Authored 2026-11-15 · 2 weeks ago

Hash
3707776fc670a880d96e7ae54a60fb07f2fafa20
Parent
0e3132f8
3 files changed +54 −10
crates/session/assets/fetch.js +6 −4
@@ -1,4 +1,4 @@
1 (async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh, nestedApp}) => {
1 (async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh, nestedApp, tenant}) => {
2 2 const fresh = (expires) => expires > Date.now() + marginMs;
3 3 const normalize = (value) => value.toLowerCase().replace(/\/\/+(?=[^/]*$)/, '/');
4 4 const covers = (value, name) => value === name || value === name + '.all';
@@ -54,6 +54,8 @@
54 54 if (sealed.length) await unseal();
55 55 const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;
56 56 const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];
57 // Without a tenant the account's home tenant; a guest tenant is reached with the same account's refresh token.
58 const inTenant = (entry) => tenant ? entry.realm === tenant : (!entry.realm || entry.realm === homeTenant(entry));
57 59 const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {});
58 60 const acquire = async (resource, scope) => {
59 61 const base = resource.replace(/\/+$/, '');
@@ -62,12 +64,12 @@
62 64 const underResource = (name) => normalize(name).startsWith(base.toLowerCase() + '/');
63 65 const grants = (scopes) => scopes.some(s => (scope === '.default' ? underResource(s) : covers(normalize(s), wanted))
64 66 || (base === 'https://graph.microsoft.com' && covers(s.toLowerCase(), short)));
65 const cacheKey = nestedApp ? base + '|' + nestedApp.clientId : base;
67 const cacheKey = [base, nestedApp ? nestedApp.clientId : '', tenant || ''].join('|');
66 68 let token = null, expiresOn = 0;
67 69 for (const entry of forceRefresh ? [] : entries) {
68 70 if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue;
69 71 if (nestedApp && entry.clientId !== nestedApp.clientId) continue;
70 if (!ownAccount(entry) || (entry.realm && entry.realm !== homeTenant(entry))) continue;
72 if (!ownAccount(entry) || !inTenant(entry)) continue;
71 73 const expires = Number(entry.expiresOn) * 1000;
72 74 if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue;
73 75 token = entry.secret; expiresOn = expires;
@@ -94,7 +96,7 @@
94 96 form.set('brk_redirect_uri', nestedApp.brokerRedirectUri);
95 97 }
96 98 try {
97 const response = await fetch(`https://login.microsoftonline.com/${homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`,
99 const response = await fetch(`https://login.microsoftonline.com/${tenant || homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`,
98 100 {method: 'POST', body: form});
99 101 const answer = await response.json();
100 102 if (!response.ok) { refreshError = answer.error || `HTTP ${response.status}`; continue; }
@@ -1,4 +1,4 @@
1(async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh, nestedApp}) => {
1(async ({requests, resource, scope, marginMs, concurrency, maxBytes, forceRefresh, nestedApp, tenant}) => {
2 const fresh = (expires) => expires > Date.now() + marginMs;
2 const fresh = (expires) => expires > Date.now() + marginMs;
3 const normalize = (value) => value.toLowerCase().replace(/\/\/+(?=[^/]*$)/, '/');
3 const normalize = (value) => value.toLowerCase().replace(/\/\/+(?=[^/]*$)/, '/');
4 const covers = (value, name) => value === name || value === name + '.all';
4 const covers = (value, name) => value === name || value === name + '.all';
@@ -54,6 +54,8 @@
54 if (sealed.length) await unseal();
54 if (sealed.length) await unseal();
55 const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;
55 const ownAccount = (entry) => !activeHome || entry.homeAccountId === activeHome;
56 const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];
56 const homeTenant = (entry) => (entry.homeAccountId || '').split('.')[1];
57 // Without a tenant the account's home tenant; a guest tenant is reached with the same account's refresh token.
58 const inTenant = (entry) => tenant ? entry.realm === tenant : (!entry.realm || entry.realm === homeTenant(entry));
57 const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {});
59 const cache = (window.__rustyTeamsTokens = window.__rustyTeamsTokens || {});
58 const acquire = async (resource, scope) => {
60 const acquire = async (resource, scope) => {
59 const base = resource.replace(/\/+$/, '');
61 const base = resource.replace(/\/+$/, '');
@@ -62,12 +64,12 @@
62 const underResource = (name) => normalize(name).startsWith(base.toLowerCase() + '/');
64 const underResource = (name) => normalize(name).startsWith(base.toLowerCase() + '/');
63 const grants = (scopes) => scopes.some(s => (scope === '.default' ? underResource(s) : covers(normalize(s), wanted))
65 const grants = (scopes) => scopes.some(s => (scope === '.default' ? underResource(s) : covers(normalize(s), wanted))
64 || (base === 'https://graph.microsoft.com' && covers(s.toLowerCase(), short)));
66 || (base === 'https://graph.microsoft.com' && covers(s.toLowerCase(), short)));
65 const cacheKey = nestedApp ? base + '|' + nestedApp.clientId : base;
67 const cacheKey = [base, nestedApp ? nestedApp.clientId : '', tenant || ''].join('|');
66 let token = null, expiresOn = 0;
68 let token = null, expiresOn = 0;
67 for (const entry of forceRefresh ? [] : entries) {
69 for (const entry of forceRefresh ? [] : entries) {
68 if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue;
70 if (entry.credentialType !== 'AccessToken' || (entry.tokenType && entry.tokenType !== 'Bearer')) continue;
69 if (nestedApp && entry.clientId !== nestedApp.clientId) continue;
71 if (nestedApp && entry.clientId !== nestedApp.clientId) continue;
70 if (!ownAccount(entry) || (entry.realm && entry.realm !== homeTenant(entry))) continue;
72 if (!ownAccount(entry) || !inTenant(entry)) continue;
71 const expires = Number(entry.expiresOn) * 1000;
73 const expires = Number(entry.expiresOn) * 1000;
72 if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue;
74 if (!grants((entry.target || '').split(' ')) || !fresh(expires) || expires <= expiresOn) continue;
73 token = entry.secret; expiresOn = expires;
75 token = entry.secret; expiresOn = expires;
@@ -94,7 +96,7 @@
94 form.set('brk_redirect_uri', nestedApp.brokerRedirectUri);
96 form.set('brk_redirect_uri', nestedApp.brokerRedirectUri);
95 }
97 }
96 try {
98 try {
97 const response = await fetch(`https://login.microsoftonline.com/${homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`,
99 const response = await fetch(`https://login.microsoftonline.com/${tenant || homeTenant(refreshToken) || 'organizations'}/oauth2/v2.0/token`,
98 {method: 'POST', body: form});
100 {method: 'POST', body: form});
99 const answer = await response.json();
101 const answer = await response.json();
100 if (!response.ok) { refreshError = answer.error || `HTTP ${response.status}`; continue; }
102 if (!response.ok) { refreshError = answer.error || `HTTP ${response.status}`; continue; }
crates/session/src/page_script.rs +1 −0
@@ -55,6 +55,7 @@ impl Session {
55 55 "concurrency": 1,
56 56 "maxBytes": 1,
57 57 "forceRefresh": force_refresh,
58 "tenant": self.tenant(),
58 59 });
59 60 let script = format!(
60 61 "{head}{TOKEN_MARKER}\nconst args = {args};\n{body}\n}})",
@@ -55,6 +55,7 @@ impl Session {
55 "concurrency": 1,
55 "concurrency": 1,
56 "maxBytes": 1,
56 "maxBytes": 1,
57 "forceRefresh": force_refresh,
57 "forceRefresh": force_refresh,
58 "tenant": self.tenant(),
58 });
59 });
59 let script = format!(
60 let script = format!(
60 "{head}{TOKEN_MARKER}\nconst args = {args};\n{body}\n}})",
61 "{head}{TOKEN_MARKER}\nconst args = {args};\n{body}\n}})",
crates/session/src/session.rs +47 −6
@@ -74,6 +74,7 @@ pub struct Session {
74 74 tabs: Arc<HashMap<App, Mutex<Option<TabControl>>>>,
75 75 force_refresh: Arc<AtomicBool>,
76 76 native: Option<Arc<NativeHttp>>,
77 tenant: Option<Arc<str>>,
77 78 }
78 79
79 80 impl Session {
@@ -90,13 +91,9 @@ impl Session {
90 91 config: SessionConfig,
91 92 ) -> Result<Self> {
92 93 transport.check().await?;
93 let native = config
94 .native_http
95 .then(|| NativeHttp::new(config.evaluate_timeout, MAX_DOWNLOAD_BYTES))
96 .flatten()
97 .map(Arc::new);
98 94 Ok(Session {
99 native,
95 native: native_http(&config),
96 tenant: None,
100 97 transport,
101 98 config,
102 99 tabs: Arc::new(
@@ -109,6 +106,22 @@ impl Session {
109 106 })
110 107 }
111 108
109 /// The same browser session with tokens for `tenant_id`, e.g. a tenant the account is a guest in.
110 /// Tokens are held apart from the home tenant's, so both can run side by side.
111 pub fn in_tenant(&self, tenant_id: &str) -> Session {
112 Session {
113 native: native_http(&self.config),
114 force_refresh: Arc::new(AtomicBool::new(false)),
115 tenant: Some(tenant_id.to_ascii_lowercase().into()),
116 ..self.clone()
117 }
118 }
119
120 /// The tenant set with [`Session::in_tenant`]; `None` is the account's home tenant.
121 pub fn tenant(&self) -> Option<&str> {
122 self.tenant.as_deref()
123 }
124
112 125 pub async fn request(
113 126 &self,
114 127 method: Method,
@@ -314,6 +327,7 @@ impl Session {
314 327 "concurrency": DEFAULT_CONCURRENCY,
315 328 "maxBytes": MAX_DOWNLOAD_BYTES,
316 329 "forceRefresh": self.force_refresh.load(Ordering::SeqCst),
330 "tenant": self.tenant(),
317 331 })
318 332 .to_string()
319 333 }
@@ -364,6 +378,14 @@ impl Drop for TabHold {
364 378 }
365 379 }
366 380
381 fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {
382 config
383 .native_http
384 .then(|| NativeHttp::new(config.evaluate_timeout, MAX_DOWNLOAD_BYTES))
385 .flatten()
386 .map(Arc::new)
387 }
388
367 389 pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
368 390 header
369 391 .and_then(|value| value.trim().parse::<f64>().ok())
@@ -420,6 +442,25 @@ mod tests {
420 442 );
421 443 }
422 444
445 #[tokio::test]
446 async fn a_tenant_session_asks_the_page_for_that_tenant_only() {
447 let home =
448 Session::with_transport(Arc::new(HoldRecorder::default()), SessionConfig::default())
449 .await
450 .unwrap();
451 let guest = home.in_tenant("AAAA-Guest");
452 let request = Request::get("https://graph.microsoft.com/v1.0/me");
453 let tenant_of = |session: &Session| {
454 let payload: Value =
455 serde_json::from_str(&session.payload(&[&request], &Scope::graph("User.Read")))
456 .unwrap();
457 payload["tenant"].clone()
458 };
459 assert_eq!(tenant_of(&home), Value::Null);
460 assert_eq!(tenant_of(&guest), json!("aaaa-guest"));
461 assert_eq!(home.tenant(), None);
462 }
463
423 464 #[test]
424 465 fn retry_after_seconds_parse() {
425 466 let default = Duration::from_secs(2);
@@ -74,6 +74,7 @@ pub struct Session {
74 tabs: Arc<HashMap<App, Mutex<Option<TabControl>>>>,
74 tabs: Arc<HashMap<App, Mutex<Option<TabControl>>>>,
75 force_refresh: Arc<AtomicBool>,
75 force_refresh: Arc<AtomicBool>,
76 native: Option<Arc<NativeHttp>>,
76 native: Option<Arc<NativeHttp>>,
77 tenant: Option<Arc<str>>,
77}
78}
78
79
79impl Session {
80impl Session {
@@ -90,13 +91,9 @@ impl Session {
90 config: SessionConfig,
91 config: SessionConfig,
91 ) -> Result<Self> {
92 ) -> Result<Self> {
92 transport.check().await?;
93 transport.check().await?;
93 let native = config
94 .native_http
95 .then(|| NativeHttp::new(config.evaluate_timeout, MAX_DOWNLOAD_BYTES))
96 .flatten()
97 .map(Arc::new);
98 Ok(Session {
94 Ok(Session {
99 native,
95 native: native_http(&config),
96 tenant: None,
100 transport,
97 transport,
101 config,
98 config,
102 tabs: Arc::new(
99 tabs: Arc::new(
@@ -109,6 +106,22 @@ impl Session {
109 })
106 })
110 }
107 }
111
108
109 /// The same browser session with tokens for `tenant_id`, e.g. a tenant the account is a guest in.
110 /// Tokens are held apart from the home tenant's, so both can run side by side.
111 pub fn in_tenant(&self, tenant_id: &str) -> Session {
112 Session {
113 native: native_http(&self.config),
114 force_refresh: Arc::new(AtomicBool::new(false)),
115 tenant: Some(tenant_id.to_ascii_lowercase().into()),
116 ..self.clone()
117 }
118 }
119
120 /// The tenant set with [`Session::in_tenant`]; `None` is the account's home tenant.
121 pub fn tenant(&self) -> Option<&str> {
122 self.tenant.as_deref()
123 }
124
112 pub async fn request(
125 pub async fn request(
113 &self,
126 &self,
114 method: Method,
127 method: Method,
@@ -314,6 +327,7 @@ impl Session {
314 "concurrency": DEFAULT_CONCURRENCY,
327 "concurrency": DEFAULT_CONCURRENCY,
315 "maxBytes": MAX_DOWNLOAD_BYTES,
328 "maxBytes": MAX_DOWNLOAD_BYTES,
316 "forceRefresh": self.force_refresh.load(Ordering::SeqCst),
329 "forceRefresh": self.force_refresh.load(Ordering::SeqCst),
330 "tenant": self.tenant(),
317 })
331 })
318 .to_string()
332 .to_string()
319 }
333 }
@@ -364,6 +378,14 @@ impl Drop for TabHold {
364 }
378 }
365}
379}
366
380
381fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {
382 config
383 .native_http
384 .then(|| NativeHttp::new(config.evaluate_timeout, MAX_DOWNLOAD_BYTES))
385 .flatten()
386 .map(Arc::new)
387}
388
367pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
389pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
368 header
390 header
369 .and_then(|value| value.trim().parse::<f64>().ok())
391 .and_then(|value| value.trim().parse::<f64>().ok())
@@ -420,6 +442,25 @@ mod tests {
420 );
442 );
421 }
443 }
422
444
445 #[tokio::test]
446 async fn a_tenant_session_asks_the_page_for_that_tenant_only() {
447 let home =
448 Session::with_transport(Arc::new(HoldRecorder::default()), SessionConfig::default())
449 .await
450 .unwrap();
451 let guest = home.in_tenant("AAAA-Guest");
452 let request = Request::get("https://graph.microsoft.com/v1.0/me");
453 let tenant_of = |session: &Session| {
454 let payload: Value =
455 serde_json::from_str(&session.payload(&[&request], &Scope::graph("User.Read")))
456 .unwrap();
457 payload["tenant"].clone()
458 };
459 assert_eq!(tenant_of(&home), Value::Null);
460 assert_eq!(tenant_of(&guest), json!("aaaa-guest"));
461 assert_eq!(home.tenant(), None);
462 }
463
423 #[test]
464 #[test]
424 fn retry_after_seconds_parse() {
465 fn retry_after_seconds_parse() {
425 let default = Duration::from_secs(2);
466 let default = Duration::from_secs(2);