use std::sync::{Arc, Mutex};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use renox::Config;
use renox::http::Http;
use renox::prelude::*;
use serde::Deserialize;
use crate::provider::{Refused, TIMEOUT};
use crate::{BoxFuture, Credentials, Profile, Provider, Token};
pub const CONSUMER_TENANT: &str = "9188040d-6c67-4c5b-b112-36a304b66dad";
pub const ANY_WORK_ACCOUNT: &str = "organizations";
const LOGIN: &str = "https://login.microsoftonline.com";
#[derive(Debug, Clone)]
pub struct Microsoft {
credentials: Credentials,
tenant: Option<String>,
active: String,
authorize: String,
token: String,
client_id: Option<String>,
resolved: Arc<Mutex<Option<(String, String)>>>,
}
impl Microsoft {
pub fn from_config() -> Self {
Self::with(Credentials::from_config("MICROSOFT"))
}
pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
Self::with(Credentials::new(client_id, client_secret))
}
fn with(credentials: Credentials) -> Self {
let mut microsoft = Self {
client_id: credentials.resolve(&Config::default()).map(|(id, _)| id),
credentials,
tenant: None,
active: String::new(),
authorize: String::new(),
token: String::new(),
resolved: Arc::default(),
};
microsoft.activate(ANY_WORK_ACCOUNT);
microsoft
}
pub fn tenant(mut self, tenant: impl Into<String>) -> Self {
let tenant: String = tenant.into();
self.activate(tenant.trim());
self.tenant = Some(tenant.trim().to_owned());
self
}
fn activate(&mut self, tenant: &str) {
self.active = tenant.to_owned();
self.authorize = format!("{LOGIN}/{tenant}/oauth2/v2.0/authorize");
self.token = format!("{LOGIN}/{tenant}/oauth2/v2.0/token");
}
fn tenant_id(&self) -> Option<&str> {
is_guid(&self.active).then_some(self.active.as_str())
}
fn any_work_account(&self) -> bool {
["organizations", "common"]
.iter()
.any(|any| self.active.eq_ignore_ascii_case(any))
}
async fn resolve_tenant(&self, http: &Http) -> Result<String> {
let cached = self.resolved.lock().ok().and_then(|cached| cached.clone());
if let Some((tenant, id)) = cached
&& tenant == self.active
{
return Ok(id);
}
#[derive(Deserialize)]
struct Discovery {
issuer: String,
}
let url = format!(
"{LOGIN}/{}/v2.0/.well-known/openid-configuration",
self.active
);
let discovery: Discovery = http
.get(&url)
.header("accept", "application/json")
.timeout(TIMEOUT)
.send()
.await?
.error_for_status()?
.json()?;
let id = tid_of_issuer(&discovery.issuer)
.filter(|id| is_guid(id))
.ok_or_else(|| renox::anyhow::anyhow!("{url}: no tenant id in the issuer"))?
.to_owned();
if let Ok(mut cached) = self.resolved.lock() {
*cached = Some((self.active.clone(), id.clone()));
}
Ok(id)
}
}
fn tid_of_issuer(issuer: &str) -> Option<&str> {
issuer.trim_end_matches('/').rsplit('/').nth(1)
}
fn is_guid(text: &str) -> bool {
text.len() == 36
&& text.char_indices().all(|(i, c)| match i {
8 | 13 | 18 | 23 => c == '-',
_ => c.is_ascii_hexdigit(),
})
}
#[derive(Deserialize)]
struct Claims {
iss: Option<String>,
aud: Option<String>,
exp: Option<i64>,
tid: Option<String>,
oid: Option<String>,
sub: Option<String>,
email: Option<String>,
preferred_username: Option<String>,
name: Option<String>,
}
fn claims(id_token: &str) -> Result<Claims> {
let payload = id_token
.split('.')
.nth(1)
.ok_or_else(|| renox::anyhow::anyhow!("the ID token isn't a JWT"))?;
let bytes = URL_SAFE_NO_PAD
.decode(payload.trim_end_matches('='))
.map_err(|_| renox::anyhow::anyhow!("the ID token's payload isn't base64url"))?;
Ok(renox::serde_json::from_slice(&bytes)?)
}
impl Provider for Microsoft {
fn name(&self) -> &str {
"microsoft"
}
fn label(&self) -> &str {
"Microsoft"
}
fn credentials(&self) -> &Credentials {
&self.credentials
}
fn authorize_endpoint(&self) -> &str {
&self.authorize
}
fn token_endpoint(&self) -> &str {
&self.token
}
fn scopes(&self) -> &[&str] {
&["openid", "email", "profile"]
}
fn authorize_params(&self) -> Vec<(&str, &str)> {
vec![("prompt", "select_account")]
}
fn with_config(&self, config: &Config) -> Option<Arc<dyn Provider>> {
let mut resolved = self.clone();
let tenant = self
.tenant
.clone()
.or_else(|| config.var("MICROSOFT_TENANT"))
.unwrap_or_else(|| ANY_WORK_ACCOUNT.to_owned());
resolved.activate(tenant.trim());
resolved.client_id = self.credentials.resolve(config).map(|(id, _)| id);
Some(Arc::new(resolved))
}
fn profile<'a>(&'a self, http: &'a Http, token: &'a Token) -> BoxFuture<'a, Result<Profile>> {
Box::pin(async move {
let id_token = token
.id_token
.as_deref()
.ok_or_else(|| renox::anyhow::anyhow!("Microsoft sent no ID token"))?;
let claims = claims(id_token)?;
let tid = claims
.tid
.as_deref()
.ok_or_else(|| renox::anyhow::anyhow!("the ID token has no tid"))?;
let ours = self
.client_id
.as_deref()
.ok_or_else(|| renox::anyhow::anyhow!("no client id to check the audience"))?;
if claims.aud.as_deref() != Some(ours) {
return Err(renox::anyhow::anyhow!("the ID token isn't for this app").into());
}
if claims
.exp
.is_none_or(|exp| exp <= renox::db::now().timestamp())
{
return Err(renox::anyhow::anyhow!("the ID token expired").into());
}
if claims.iss.as_deref() != Some(&format!("{LOGIN}/{tid}/v2.0")) {
return Err(renox::anyhow::anyhow!("the ID token's issuer doesn't match").into());
}
if tid.eq_ignore_ascii_case(CONSUMER_TENANT) {
return Err(Refused::new(
"personal_account",
"Personal Microsoft accounts can't sign in here. Use your work or school account.",
)
.into());
}
let verified = if self.any_work_account() {
false
} else {
let wanted = match self.tenant_id() {
Some(id) => id.to_owned(),
None => self.resolve_tenant(http).await?,
};
if !tid.eq_ignore_ascii_case(&wanted) {
return Err(Refused::new(
"tenant",
"That Microsoft account belongs to another organisation.",
)
.into());
}
true
};
let oid = claims
.oid
.as_deref()
.or(claims.sub.as_deref())
.filter(|id| !id.is_empty())
.ok_or_else(|| renox::anyhow::anyhow!("the ID token has no oid"))?;
let id = if self.any_work_account() {
format!("{tid}.{oid}")
} else {
oid.to_owned()
};
let mut profile = Profile::new(id);
let email = claims
.email
.or_else(|| claims.preferred_username.filter(|name| name.contains('@')));
if let Some(email) = email {
profile = profile.email(email, verified);
}
Ok(profile.name(claims.name))
})
}
}