Draft: SSO login (OAuth 2.0 + OpenID Connect) #1012

Open
avdb13 wants to merge 11 commits from oidc into next
19 changed files with 809 additions and 350 deletions
Showing only changes of commit 8fd6a88f43 - Show all commits

View file

@ -56,7 +56,6 @@ http = "0.2.9"
# Used to find data directory for default db path
directories = "4.0.1"
macaroon = { git = "https://github.com/macaroon-rs/macaroon.git", branch = "main" }
openid = "0.9"
# Used for ruma wrapper
serde_json = { version = "1.0.96", features = ["raw_value"] }
# Used for appservice registration files
@ -122,6 +121,9 @@ async-trait = "0.1.68"
sd-notify = { version = "0.4.1", optional = true }
url = { version = "2.5.0", features = ["serde"] }
openidconnect = { version = "3.5.0", features = ["jwk-alg", "accept-string-booleans"] }
askama = { version = "0.12.1", features = ["with-axum"] }
askama_axum = { version = "0.4.0", features = ["urlencode", "config"] }
[target.'cfg(unix)'.dependencies]
nix = { version = "0.26.2", features = ["resource"] }

2
askama.toml Normal file
View file

@ -0,0 +1,2 @@
[general]
dirs = ["public/templates"]

View file

@ -58,11 +58,15 @@ address = "127.0.0.1" # This makes sure Conduit can only be reached using the re
macaroon_key = "this is the key"
[[oidc_provider]]
id = "keycloak"
name = "keycloak"
client.id = "conduit"
client.secret = "00000000-0000-0000-0000-000000000000"
discover_url = "https://keycloak.domain.com/auth/realms/example"
scopes = ["openid", "read_user"]
backchannel_logout = true
[[global.oidc]]
idp_id = "gitlab"
idp_name = "Gitlab"
idp_icon = "mxc://matrix.org/00000000000000000000000000000000"
issuer = "https://gitlab.com"
scopes = ["openid", "profile"]
[global.oidc.client]
id = "0000000000000000000000000000000000000000000000000000000000000000"
secret = "0000000000000000000000000000000000000000000000000000000000000000"
auth_method = "post"

6
public/conduit.svg Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="windows-1252"?>
<!-- Generator: Adobe Illustrator 18.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path fill="#FFB636" d="M459.866,218.346l-186.7,0.701c-4.619,0.017-7.618-4.861-5.517-8.975L370.845,8.024 c3.103-6.075-4.493-11.949-9.592-7.417L39.948,286.141c-4.221,3.751-1.602,10.732,4.045,10.78l170.444,1.457 c4.443,0.038,7.391,4.619,5.583,8.679L133.317,501.73c-2.688,6.035,4.709,11.501,9.689,7.16l320.937-279.725 C468.25,225.412,465.58,218.325,459.866,218.346z"/>
</svg>

After

Width:  |  Height:  |  Size: 821 B

152
public/templates/base.html Normal file
View file

@ -0,0 +1,152 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}{% endblock %}</title>
<!-- <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"> -->
<style type="text/css">
{{"
body, input, select, textarea {
font-family: \"Inter\", \"Helvetica\", \"Arial\", sans-serif;
font-size: 14px;
color: #17191C;
}
header, footer {
max-width: 480px;
width: 100%;
margin: 24px auto;
text-align: center;
}
@media screen and (min-width: 800px) {
header {
margin-top: 90px;
}
}
header {
min-height: 60px;
}
header p {
color: #737D8C;
line-height: 24px;
}
h1 {
font-size: 24px;
}
a {
color: #418DED;
}
.error_page h1 {
color: #FE2928;
}
h2 {
font-size: 14px;
}
h2 img {
vertical-align: middle;
margin-right: 8px;
width: 24px;
height: 24px;
}
label {
cursor: pointer;
}
main {
max-width: 360px;
width: 100%;
margin: 24px auto;
}
.primary-button {
border: none;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
text-decoration: none;
padding: 12px;
color: white;
background-color: #418DED;
font-weight: bold;
display: block;
border-radius: 12px;
width: 100%;
box-sizing: border-box;
margin: 16px 0;
cursor: pointer;
text-align: center;
}
.profile {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 24px;
padding: 13px;
border: 1px solid #E9ECF1;
border-radius: 4px;
}
.profile.with-avatar {
margin-top: 42px; /* (36px / 2) + 24px*/
}
.profile .avatar {
width: 36px;
height: 36px;
border-radius: 100%;
display: block;
margin-top: -32px;
margin-bottom: 8px;
}
.profile .display-name {
font-weight: bold;
margin-bottom: 4px;
font-size: 15px;
line-height: 18px;
}
.profile .user-id {
color: #737D8C;
font-size: 12px;
line-height: 12px;
}
footer {
margin-top: 80px;
}
footer svg {
display: block;
width: 46px;
margin: 0px auto 12px auto;
}
footer p {
color: #737D8C;
}
"}}
{% block style %}{% endblock %}
</style>
</head>
<body>
<header class="mx_Header">
<img src="https://matrix.org/img/matrix-120x51.png" width="120" height="51" alt="[matrix]"/>
</header>
{% block body %}{% endblock %}
</body>
</html>

View file

@ -0,0 +1,19 @@
<footer>
<svg role="img" aria-label="[Matrix logo]" viewBox="0 0 200 85" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="parent" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="child" transform="translate(-122.000000, -6.000000)" fill="#000000" fill-rule="nonzero">
<g id="matrix-logo" transform="translate(122.000000, 6.000000)">
<polygon id="left-bracket" points="2.24708861 1.93811009 2.24708861 82.7268844 8.10278481 82.7268844 8.10278481 84.6652459 0 84.6652459 0 0 8.10278481 0 8.10278481 1.93811009"></polygon>
<path d="M24.8073418,27.5493174 L24.8073418,31.6376991 L24.924557,31.6376991 C26.0227848,30.0814294 27.3455696,28.8730642 28.8951899,28.0163743 C30.4437975,27.1611927 32.2189873,26.7318422 34.218481,26.7318422 C36.1394937,26.7318422 37.8946835,27.102622 39.4825316,27.8416679 C41.0708861,28.5819706 42.276962,29.8856073 43.1005063,31.7548404 C44.0017722,30.431345 45.2270886,29.2629486 46.7767089,28.2506569 C48.3253165,27.2388679 50.158481,26.7318422 52.2764557,26.7318422 C53.8843038,26.7318422 55.3736709,26.9269101 56.7473418,27.3162917 C58.1189873,27.7056734 59.295443,28.3285835 60.2759494,29.185022 C61.255443,30.0422147 62.02,31.1615927 62.5701266,32.5426532 C63.1187342,33.9262275 63.3936709,35.5898349 63.3936709,37.5372459 L63.3936709,57.7443688 L55.0410127,57.7441174 L55.0410127,40.6319376 C55.0410127,39.6201486 55.0020253,38.6661761 54.9232911,37.7700202 C54.8440506,36.8751211 54.6293671,36.0968606 54.2764557,35.4339817 C53.9232911,34.772611 53.403038,34.2464807 52.7177215,33.8568477 C52.0313924,33.4689743 51.0997468,33.2731523 49.9235443,33.2731523 C48.7473418,33.2731523 47.7962025,33.4983853 47.0706329,33.944578 C46.344557,34.393033 45.7764557,34.9774826 45.3650633,35.6969211 C44.9534177,36.4181193 44.6787342,37.2353431 44.5417722,38.150855 C44.4037975,39.0653615 44.3356962,39.9904257 44.3356962,40.9247908 L44.3356962,57.7443688 L35.9835443,57.7443688 L35.9835443,40.8079009 C35.9835443,39.9124991 35.963038,39.0263982 35.9253165,38.150855 C35.8853165,37.2743064 35.7192405,36.4666349 35.424557,35.7263321 C35.1303797,34.9872862 34.64,34.393033 33.9539241,33.944578 C33.2675949,33.4983853 32.2579747,33.2731523 30.9248101,33.2731523 C30.5321519,33.2731523 30.0126582,33.3608826 29.3663291,33.5365945 C28.7192405,33.7118037 28.0913924,34.0433688 27.4840506,34.5292789 C26.875443,35.0164459 26.3564557,35.7172826 25.9250633,36.6315376 C25.4934177,37.5470495 25.2779747,38.7436 25.2779747,40.2229486 L25.2779747,57.7441174 L16.9260759,57.7443688 L16.9260759,27.5493174 L24.8073418,27.5493174 Z" id="m"></path>
<path d="M68.7455696,31.9886202 C69.6075949,30.7033339 70.7060759,29.672189 72.0397468,28.8926716 C73.3724051,28.1141596 74.8716456,27.5596239 76.5387342,27.2283101 C78.2050633,26.8977505 79.8817722,26.7315908 81.5678481,26.7315908 C83.0974684,26.7315908 84.6458228,26.8391798 86.2144304,27.0525982 C87.7827848,27.2675248 89.2144304,27.6865688 90.5086076,28.3087248 C91.8025316,28.9313835 92.8610127,29.7983798 93.6848101,30.9074514 C94.5083544,32.0170257 94.92,33.4870734 94.92,35.3173431 L94.92,51.026844 C94.92,52.3913138 94.998481,53.6941963 95.1556962,54.9400165 C95.3113924,56.1865908 95.5863291,57.120956 95.9787342,57.7436147 L87.5091139,57.7436147 C87.3518987,57.276055 87.2240506,56.7996972 87.1265823,56.3125303 C87.0278481,55.8266202 86.9592405,55.3301523 86.9207595,54.8236294 C85.5873418,56.1865908 84.0182278,57.1405633 82.2156962,57.6857982 C80.4113924,58.2295248 78.5683544,58.503022 76.6860759,58.503022 C75.2346835,58.503022 73.8817722,58.3275615 72.6270886,57.9776459 C71.3718987,57.6269761 70.2744304,57.082244 69.3334177,56.3411872 C68.3921519,55.602644 67.656962,54.6680275 67.1275949,53.5390972 C66.5982278,52.410167 66.3331646,51.065556 66.3331646,49.5087835 C66.3331646,47.7961578 66.6367089,46.384178 67.2455696,45.2756092 C67.8529114,44.1652807 68.6367089,43.2799339 69.5987342,42.6173064 C70.5589873,41.9556844 71.6567089,41.4592165 72.8924051,41.1284055 C74.1273418,40.7978459 75.3721519,40.5356606 76.6270886,40.3398385 C77.8820253,40.1457761 79.116962,39.9896716 80.3329114,39.873033 C81.5483544,39.7558917 82.6270886,39.5804312 83.5681013,39.3469028 C84.5093671,39.1133743 85.2536709,38.7732624 85.8032911,38.3250587 C86.3513924,37.8773578 86.6063291,37.2252881 86.5678481,36.3680954 C86.5678481,35.4731963 86.4210127,34.7620532 86.1268354,34.2366771 C85.8329114,33.7113009 85.4405063,33.3018092 84.9506329,33.0099615 C84.4602532,32.7181138 83.8916456,32.5232972 83.2450633,32.4255119 C82.5977215,32.3294862 81.9010127,32.2797138 81.156962,32.2797138 C79.5098734,32.2797138 78.2159494,32.6303835 77.2746835,33.3312202 C76.3339241,34.0320569 75.7837975,35.2007046 75.6275949,36.8354037 L67.275443,36.8354037 C67.3924051,34.8892495 67.8817722,33.2726495 68.7455696,31.9886202 Z M85.2440506,43.6984752 C84.7149367,43.873433 84.1460759,44.0189798 83.5387342,44.1361211 C82.9306329,44.253011 82.2936709,44.350545 81.6270886,44.4279688 C80.96,44.5066495 80.2934177,44.6034294 79.6273418,44.7203193 C78.9994937,44.8362037 78.3820253,44.9933138 77.7749367,45.1871248 C77.1663291,45.3829468 76.636962,45.6451321 76.1865823,45.9759431 C75.7349367,46.3070055 75.3724051,46.7263009 75.0979747,47.2313156 C74.8232911,47.7375872 74.6863291,48.380356 74.6863291,49.1588679 C74.6863291,49.8979138 74.8232911,50.5218294 75.0979747,51.026844 C75.3724051,51.5338697 75.7455696,51.9328037 76.2159494,52.2246514 C76.6863291,52.5164991 77.2349367,52.7213706 77.8632911,52.8375064 C78.4898734,52.9546477 79.136962,53.012967 79.8037975,53.012967 C81.4506329,53.012967 82.724557,52.740978 83.6273418,52.1952404 C84.5288608,51.6507596 85.1949367,50.9981872 85.6270886,50.2382771 C86.0579747,49.4793725 86.323038,48.7119211 86.4212658,47.9321523 C86.518481,47.1536404 86.5681013,46.5304789 86.5681013,46.063422 L86.5681013,42.9677248 C86.2146835,43.2799339 85.7736709,43.5230147 85.2440506,43.6984752 Z" id="a"></path>
<path d="M116.917975,27.5493174 L116.917975,33.0976917 L110.801266,33.0976917 L110.801266,48.0492936 C110.801266,49.4502128 111.036203,50.3850807 111.507089,50.8518862 C111.976962,51.3191945 112.918734,51.5527229 114.33038,51.5527229 C114.801013,51.5527229 115.251392,51.5336183 115.683038,51.4944037 C116.114177,51.4561945 116.526076,51.3968697 116.917975,51.3194459 L116.917975,57.7438661 C116.212152,57.860756 115.427595,57.9381798 114.565316,57.9778972 C113.702785,58.0153523 112.859747,58.0357138 112.036203,58.0357138 C110.742278,58.0357138 109.516456,57.9477321 108.36,57.7722716 C107.202785,57.5975651 106.183544,57.2577046 105.301519,56.7509303 C104.418987,56.2454128 103.722785,55.5242147 103.213418,54.5898495 C102.703038,53.6562385 102.448608,52.4292716 102.448608,50.9099541 L102.448608,33.0976917 L97.3903797,33.0976917 L97.3903797,27.5493174 L102.448608,27.5493174 L102.448608,18.4967596 L110.801013,18.4967596 L110.801013,27.5493174 L116.917975,27.5493174 Z" id="t"></path>
<path d="M128.857975,27.5493174 L128.857975,33.1565138 L128.975696,33.1565138 C129.367089,32.2213945 129.896203,31.3559064 130.563544,30.557033 C131.23038,29.7596679 131.99443,29.0776844 132.857215,28.5130936 C133.719241,27.9495083 134.641266,27.5113596 135.622532,27.1988991 C136.601772,26.8879468 137.622025,26.7315908 138.681013,26.7315908 C139.229873,26.7315908 139.836962,26.8296275 140.504304,27.0239413 L140.504304,34.7336477 C140.111646,34.6552183 139.641013,34.586844 139.092658,34.5290275 C138.543291,34.4704569 138.014177,34.4410459 137.504304,34.4410459 C135.974937,34.4410459 134.681013,34.6949358 133.622785,35.2004532 C132.564051,35.7067248 131.711392,36.397255 131.064051,37.2735523 C130.417215,38.1501009 129.955443,39.1714422 129.681266,40.3398385 C129.407089,41.5074807 129.269873,42.7736624 129.269873,44.1361211 L129.269873,57.7438661 L120.917722,57.7438661 L120.917722,27.5493174 L128.857975,27.5493174 Z" id="r"></path>
<path d="M144.033165,22.8767376 L144.033165,16.0435798 L152.386076,16.0435798 L152.386076,22.8767376 L144.033165,22.8767376 Z M152.386076,27.5493174 L152.386076,57.7438661 L144.033165,57.7438661 L144.033165,27.5493174 L152.386076,27.5493174 Z" id="i"></path>
<polygon id="x" points="156.738228 27.5493174 166.266582 27.5493174 171.619494 35.4337303 176.913418 27.5493174 186.147848 27.5493174 176.148861 41.6831927 187.383544 57.7441174 177.85443 57.7441174 171.501772 48.2245028 165.148861 57.7441174 155.797468 57.7441174 166.737468 41.8589046"></polygon>
<polygon id="right-bracket" points="197.580759 82.7268844 197.580759 1.93811009 191.725063 1.93811009 191.725063 0 199.828354 0 199.828354 84.6652459 191.725063 84.6652459 191.725063 82.7268844"></polygon>
</g>
</g>
</g>
</svg>
<p>An open network for secure, decentralized communication.<br>© 2023 The Matrix.org Foundation C.I.C.</p>
</footer>

View file

@ -0,0 +1,58 @@
{% extends "base.html" %}
{% block title %}Choose identity provider{% endblock %}
{% block style %}
.providers {
list-style: none;
padding: 0;
}
.providers li {
margin: 12px;
}
.providers a {
display: block;
border-radius: 4px;
border: 1px solid #17191C;
padding: 8px;
text-align: center;
text-decoration: none;
color: #17191C;
display: flex;
align-items: center;
font-weight: bold;
}
.providers a img {
width: 24px;
height: 24px;
}
.providers a span {
flex: 1;
}
{% endblock %}
{% block body %}
<header>
<h1>Log in to {{ server_name }} </h1>
<p>Choose an identity provider to log in</p>
</header>
<main>
<ul class="providers">
{% for idp in metadata %}
<li>
<a href="pick_idp?idp={{ idp.id }}&redirectUrl={{ redirect_url|urlencode_strict }}">
{% match crate::utils::mxc_to_http_or_none(idp.icon.as_deref(), "32", "32") %}
{% when Some with (mxc) %}
<img src="{{ mxc }}"/>
{% when None %}
{% endmatch %}
<span>{{ idp.name.as_deref().unwrap_or(idp.id) }}</span>
</a>
</li>
{% endfor %}
</ul>
</main>
{% include "sso_footer.html" %}
{% endblock %}

View file

@ -0,0 +1,27 @@
{% extends "_base.html" %}
{% block title %}Authentication{% endblock %}
{% block header %}
<style type="text/css">
#registrationForm input {
display: block;
margin: auto;
}
</style>
{% endblock %}
{% block body %}
<form id="registrationForm" method="post" action="{{ myurl }}">
<div>
{% if error is defined %}
<p class="error"><strong>Error: {{ error }}</strong></p>
{% endif %}
<p>
Please click the button below if you agree to the
<a href="{{ terms_url }}">privacy policy of this homeserver.</a>
</p>
<input type="hidden" name="session" value="{{ session }}" />
<input type="submit" value="Agree" />
</div>
</form>
{% endblock %}

View file

@ -11,6 +11,7 @@ mod keys;
mod media;
mod membership;
mod message;
mod oidc;
mod presence;
mod profile;
mod push;
@ -22,7 +23,6 @@ mod room;
mod search;
mod session;
mod space;
mod sso;
mod state;
mod sync;
mod tag;
@ -47,6 +47,7 @@ pub use keys::*;
pub use media::*;
pub use membership::*;
pub use message::*;
pub use oidc::*;
pub use presence::*;
pub use profile::*;
pub use push::*;
@ -58,7 +59,6 @@ pub use room::*;
pub use search::*;
pub use session::*;
pub use space::*;
pub use sso::*;
pub use state::*;
pub use sync::*;
pub use tag::*;

View file

@ -0,0 +1,114 @@
use crate::{
config::Metadata, service::oidc::COOKIE_STATE_EXPIRATION_SECS, services, Error, Result, Ruma,
};
use askama::Template;
use axum::response::IntoResponse;
use axum_extra::extract::cookie::{Cookie, SameSite};
use bytes::BufMut;
use http::{header::COOKIE, HeaderValue, StatusCode};
use ruma::api::{
client::{error::ErrorKind, session},
error::IntoHttpError,
OutgoingResponse,
};
// const SEED_LEN: usize = 32;
/// # `GET /_matrix/client/v3/login/sso/redirect`
///
/// Redirect user to SSO interface.
///
pub async fn get_sso_redirect(
body: Ruma<session::sso_login::v3::Request>,
) -> axum::response::Response {
let server_name = services().globals.server_name().to_string();
let metadata = services().oidc.get_metadata();
let redirect_url = body.redirect_url.clone();
let t = SsoTemplate {
server_name,
metadata,
redirect_url,
};
match t.render() {
Ok(body) => {
let headers = [(
http::header::CONTENT_TYPE,
http::HeaderValue::from_static(SsoTemplate::MIME_TYPE),
)];
(headers, body).into_response()
}
Err(_) => (StatusCode::INTERNAL_SERVER_ERROR, "woops").into_response(),
}
}
pub struct SsoResponse {
pub inner: session::sso_login_with_provider::v3::Response,
pub cookie: String,
}
impl OutgoingResponse for SsoResponse {
fn try_into_http_response<T: Default + BufMut>(
self,
) -> Result<http::Response<T>, IntoHttpError> {
self.inner.try_into_http_response().map(|mut ok| {
*ok.status_mut() = StatusCode::FOUND;
match HeaderValue::from_str(self.cookie.as_str()) {
Ok(value) => {
ok.headers_mut().insert(COOKIE, value);
Ok(ok)
}
Err(e) => Err(IntoHttpError::Header(e)),
}
})?
}
}
/// # `GET /_matrix/client/v3/login/sso/redirect/{idpId}`
///
/// Redirect user to SSO interface.
pub async fn get_sso_redirect_with_idp_id(
body: Ruma<session::sso_login_with_provider::v3::Request>,
// State(uiaa_session): State<Option<()>>,
) -> Result<SsoResponse> {
// if services().oidc.get_all().len() == 1 {
// }
let Ok(provider) = services().oidc.get_provider(&body.idp_id).await else {
return Err(Error::BadRequest(
ErrorKind::NotFound,
"Unknown identity provider",
));
};
let (location, cookie) = provider.handle_redirect(&body.redirect_url).await;
let inner = session::sso_login_with_provider::v3::Response {
location: location.to_string(),
};
let cookie = Cookie::build("openid-state", cookie)
.path("/_conduit/client/oidc")
.secure(false) //FIXME
// .secure(true)
.http_only(true)
.same_site(SameSite::None)
.max_age(time::Duration::seconds(COOKIE_STATE_EXPIRATION_SECS))
.finish()
.to_string();
Ok(SsoResponse { inner, cookie })
// Ok((axum::http::StatusCode::FOUND, [(LOCATION, &body.redirect_url)]).into_response())
}
pub async fn get_sso_return() {}
#[derive(Template)]
#[template(path = "sso_login_idp_picker.html", escape = "none")]
struct SsoTemplate {
pub server_name: String,
pub metadata: Vec<Metadata>,
pub redirect_url: String,
}

View file

@ -1,8 +1,6 @@
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
use crate::{services, utils, Error, Result, Ruma};
use base64::alphabet;
use base64::engine;
use base64::engine::general_purpose;
use base64::{alphabet, engine, engine::general_purpose};
// use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use macaroon::Verifier;
@ -81,10 +79,20 @@ fn test_verifier_callback() {
pub async fn get_login_types_route(
_body: Ruma<get_login_types::v3::Request>,
) -> Result<get_login_types::v3::Response> {
let identity_providers = services()
.oidc
.get_metadata()
.clone()
.into_iter()
.map(Into::into)
.collect();
Ok(get_login_types::v3::Response::new(vec![
get_login_types::v3::LoginType::Password(Default::default()),
get_login_types::v3::LoginType::ApplicationService(Default::default()),
get_login_types::v3::LoginType::Sso(get_login_types::v3::SsoLoginType::default()),
get_login_types::v3::LoginType::Sso(get_login_types::v3::SsoLoginType {
identity_providers,
}),
]))
}
@ -184,13 +192,13 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
let mut verifier = Verifier::default();
verifier.satisfy_general(verifier_callback);
let openid_client = &services().globals.openid_client;
let (key, _client) = openid_client.as_ref().unwrap();
// let openid_client = &services().globals.openid_client;
// let (key, _client) = openid_client.as_ref().unwrap();
match verifier.verify(&macaroon, &key, Default::default()) {
Ok(()) => println!("Macaroon verified!"),
Err(error) => println!("Error validating macaroon: {:?}", error),
}
// match verifier.verify(&macaroon, &key, Default::default()) {
// Ok(()) => println!("Macaroon verified!"),
// Err(error) => println!("Error validating macaroon: {:?}", error),
// }
let user_id =
UserId::parse_with_server_name(user_id, services().globals.server_name())

View file

@ -1,254 +0,0 @@
use axum::extract::Query;
use axum::response::IntoResponse;
use axum_extra::extract::cookie::{Cookie, SameSite};
use axum_extra::extract::CookieJar;
use macaroon::Macaroon;
use openid::{Token, Userinfo, Provider};
use rand::{thread_rng, Rng};
use reqwest::Url;
use ring::digest;
use ruma::api::client::error::ErrorKind;
use serde::{Deserialize, Serialize};
use crate::{services, Result, Error};
const COOKIE_STATE_EXPIRATION_SECS: i64 = 10 * 60;
const MAC_VALID_SECS: i64 = 10;
const PROOF_KEY_LEN: usize = 32;
const NONCE_LEN: usize = 32;
#[derive(Deserialize, Serialize)]
struct State {
after_auth: String,
proof_key: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SsoRedirectParams {
pub redirect_url: String,
}
/// # `GET /_matrix/client/v3/login/sso/redirect`
///
/// Redirect user to SSO interface.
///
pub async fn get_sso_redirect(
Query(params): Query<SsoRedirectParams>,
// State(uia_session): State<Option<()>>,
cookies: CookieJar,
) -> Result<impl IntoResponse> {
let SsoRedirectParams { redirect_url } = params;
let client = services().globals.oidc.as_ref().unwrap();
let key = services().globals.macaroon.as_ref()
.ok_or(Error::BadConfig(&"Missing macaroon key in config file."))?;
use base64::{
alphabet,
engine::{self, general_purpose},
Engine as _,
};
const CUSTOM_ENGINE: engine::GeneralPurpose =
engine::GeneralPurpose::new(&alphabet::URL_SAFE, general_purpose::NO_PAD);
// https://datatracker.ietf.org/doc/html/rfc7636#section-4.1
let mut arr = [0u8; PROOF_KEY_LEN];
thread_rng().fill(&mut arr[..]);
let proof_key = CUSTOM_ENGINE.encode(arr);
thread_rng().fill(&mut arr[..]);
let nonce = CUSTOM_ENGINE.encode(arr);
let state = State {
after_auth: redirect_url.to_string(),
proof_key,
};
let state = serde_json::to_string(&state).unwrap();
let key = macaroon::MacaroonKey::generate(key.as_ref());
let mut macaroon = macaroon::Macaroon::create(None, &key, "key".into()).unwrap();
let issuer = client.provider.auth_uri();
let expires = chrono::Utc::now() + chrono::TimeDelta::seconds(COOKIE_STATE_EXPIRATION_SECS);
macaroon.add_first_party_caveat(format!("state = {state}").into());
macaroon.add_first_party_caveat(format!("provider = ???", ).into());
macaroon.add_first_party_caveat(format!("state = {state}").into());
macaroon.add_first_party_caveat(format!("nonce = {nonce}").into());
macaroon.add_first_party_caveat(format!("redirect_url = {redirect_url}").into());
let cookie1 = Cookie::build("openid-state", state_b64)
.path("/sso_return")
.secure(false) //FIXME
// .secure(true)
.http_only(true)
.same_site(SameSite::None)
.max_age(time::Duration::seconds(COOKIE_STATE_EXPIRATION_SECS))
.finish();
let updated_jar = cookies.add(cookie1);
let cookie2 = Cookie::build("openid-state-no-samesite", state_b64)
.path("/sso_return")
.http_only(true)
.max_age(time::Duration::seconds(COOKIE_STATE_EXPIRATION_SECS))
.finish();
let updated_jar = cookies.add(cookie1).add(cookie2);
let auth_url = client.auth_url(&openid::Options {
scope: Some("email".into()),
state: Some(state_b64_sha256_b64.to_string()),
..Default::default()
});
let redirect = axum::response::Redirect::to(auth_url.as_ref());
Ok((updated_jar, redirect))
}
async fn request_token(
oidc_client: &openid::DiscoveredClient,
code: &str,
) -> Result<(Token, Userinfo), Error> {
let mut token: Token = oidc_client.request_token(code).await
.map_err(|_| Error::BadRequest(ErrorKind::Unknown, "OICD token request failed."))?
.into();
let Some(ref mut id_token) = token.id_token else {
return Err(Error::BadServerResponse("OICD token did not contain id_token"))?;
};
oidc_client.decode_token(id_token)
.map_err(|_| Error::BadRequest(ErrorKind::Unknown, "Couldn't decode token."))?;
oidc_client.validate_token(id_token, None, None)
.map_err(|_| Error::BadRequest(ErrorKind::Unknown, "Couldn't validate token."))?;
let userinfo = oidc_client.request_userinfo(&token).await
.map_err(|_| Error::BadServerResponse("Requesting userinfo failed."))?;
Ok((token, userinfo))
}
// #[derive(Debug)]
// struct User {
// id: String,
// login: Option<String>()
// first_name: Option<String>,
// last_name: Option<String>,
// email: Option<String>,
// image_url: Option<String>,
// activated: bool,
// lang_key: Option<String>,
// authorities: Vec<String>,
// }
// #[derive(Debug, Responder)]
// pub enum ExampleResponse<'a> {
// Redirect(Redirect),
// Unauthorized(rocket::response::status::Unauthorized<&'a str>),
// }
#[derive(Debug, Deserialize)]
pub struct Params {
// pub session_state: String,
pub state: String,
pub code: String,
}
pub async fn get_sso_return(
Query(params): Query<Params>,
cookies: CookieJar,
) -> Result<impl IntoResponse> {
let Params { code, state, .. } = params;
use base64::{
alphabet,
engine::{self, general_purpose},
Engine as _,
};
const CUSTOM_ENGINE: engine::GeneralPurpose =
engine::GeneralPurpose::new(&alphabet::URL_SAFE, general_purpose::NO_PAD);
let state = CUSTOM_ENGINE.decode(state).unwrap();
// TODO: test with expired/deleted cookie
let cookie_state = cookies.get("openid-state").unwrap();
let cookie_state_b64_sha256 =
digest::digest(&digest::SHA256, &cookie_state.value().as_bytes());
if state != cookie_state_b64_sha256.as_ref() {
// return ExampleResponse::Unauthorized(rocket::response::status::Unauthorized(Some(
// "invalid state",
// )));
panic!("invalid state");
}
let decoded_state = CUSTOM_ENGINE.decode(cookie_state.value()).unwrap();
let decoded_state: State = serde_json::from_slice(&decoded_state).unwrap();
let openid_client = &services().globals.openid_client;
let (key, client) = openid_client.as_ref().unwrap();
let username;
match request_token(client, &code).await {
Ok(Some((_token, userinfo))) => {
/*
let id = uuid::Uuid::new_v4().to_string();
let login = userinfo.preferred_username.clone();
let email = userinfo.email.clone();
h
let new_user = User {
id: userinfo.sub.clone().unwrap_or_default(),
login,
last_name: userinfo.family_name.clone(),
first_name: userinfo.name.clone(),
email,
activated: userinfo.email_verified,
image_url: userinfo.picture.clone().map(|x| x.to_string()),
lang_key: Some("en".to_string()),
authorities: vec!["ROLE_USER".to_string()], //FIXME: read from token
};
*/
// user = new_user.login.unwrap();
username = userinfo.preferred_username.unwrap();
}
Ok(None) => {
// return ExampleResponse::Unauthorized(rocket::response::status::Unauthorized(Some(
// "no id_token found",
// )));
panic!("no id_token found");
}
Err(err) => {
eprintln!("login error in call: {:?}", err);
// return ExampleResponse::Unauthorized(rocket::response::status::Unauthorized(Some(
// "login error in call",
// )));
panic!("login error in call");
}
}
// Create our macaroon
let mut macaroon = match Macaroon::create(Some("location".into()), &key, username.into()) {
Ok(macaroon) => macaroon,
Err(error) => panic!("Error creating macaroon: {:?}", error),
};
let something = format!("time < {}", chrono::Utc::now().timestamp() + MAC_VALID_SECS).into();
macaroon.add_first_party_caveat(something);
let serialized = macaroon.serialize(macaroon::Format::V2).unwrap();
let encoded = CUSTOM_ENGINE.encode(serialized);
let redirect_url =
Url::parse_with_params(&decoded_state.after_auth, &[("loginToken", encoded)]).unwrap();
let redirect = axum::response::Redirect::to(&redirect_url.to_string());
Ok(redirect)
}

View file

@ -11,6 +11,8 @@ use tracing::warn;
mod proxy;
mod oidc;
pub use oidc::*;
use self::{oidc::OidcConfig, proxy::ProxyConfig};
#[derive(Clone, Debug, Deserialize)]

View file

@ -1,60 +1,79 @@
use ruma::{serde::AsRefStr, OwnedMxcUri};
use openidconnect::JsonWebKeyId;
use ruma::{
api::client::session::get_login_types::v3::{IdentityProvider, IdentityProviderBrand},
OwnedMxcUri,
};
use serde::Deserialize;
pub type OidcConfig = Vec<ProviderConfig>;
#[derive(Clone, Debug, Deserialize)]
pub struct ProviderConfig {
pub struct Metadata {
// Must be unique, used to distinguish OPs
#[serde(rename = "idp_id")]
pub id: String,
pub name: Option<String>,
pub icon: Option<OwnedMxcUri>,
// Base URL of the OpenID Provider
#[serde(rename = "idp_name")]
pub name: Option<String>,
#[serde(rename = "idp_icon")]
pub icon: Option<OwnedMxcUri>,
}
impl Into<IdentityProvider> for Metadata {
fn into(self) -> IdentityProvider {
let brand = match IdentityProviderBrand::from(self.id.clone()) {
IdentityProviderBrand::_Custom(_) => None,
brand => Some(brand),
};
IdentityProvider {
id: self.id.clone(),
name: self.name.unwrap_or(self.id),
icon: self.icon,
brand,
}
}
}
#[derive(Clone, Debug, Deserialize)]
pub struct ProviderConfig {
// Information retrieved while creating the OpenID Application
pub client: ClientConfig,
// Information for displaying the OpenID Provider
#[serde(flatten)]
pub metadata: Metadata,
// Foo
// #[serde(deserialize_with = "crate::utils::deserialize_from_str")]
pub issuer: url::Url,
// Always contains at least "openid"
// Always contains "openid" by default
// "profile", "email" and "name" are useful to suggest an MXID
pub scopes: Vec<String>,
// PKCE provides dynamic client secrets
// Should be enabled when `ClientAuthMethod` is `None`
pub pkce: Option<bool>,
// Allow existent accounts to login with OIDC
pub allow_existing_users: bool,
// Invalidate user sessions when the OP session expires
pub backchannel_logout: bool,
// Should be enabled when the authorization response does not contain userinfo
pub userinfo_override: bool,
// Should be enabled when the authorization response does not contain a unique subject claim
subject_claim: Option<String>,
pub subject_claim: Option<String>,
pub client: ClientConfig,
pub metadata: MetadataConfig,
}
// Allow existent accounts to login with OIDC
#[serde(default)]
pub allow_existing_users: bool,
#[derive(Clone, Debug, Deserialize)]
pub enum MetadataConfig {
// Should be used for OPs supporting the OIDC Discovery endpoint
Discoverable,
Manual {
authorization: Option<url::Url>,
token: Option<url::Url>,
userinfo: Option<url::Url>,
jwk: Option<url::Url>,
},
}
// Invalidate user sessions when the OP session expires
#[serde(default)]
pub backchannel_logout: bool,
#[derive(Clone, Debug, Deserialize, AsRefStr)]
pub enum ClientAuthMethod {
None,
// Provide the client combo in the Authorization header
Basic,
// Provide the client combo as in the POST request body
Post,
// Provide a JWT signed with client secret
SharedJwt,
// Provide a JWT signed with our own keypair (OP needs to know the public key)
PrivateJwt,
// Should be enabled when the authorization response does not contain userinfo
#[serde(default)]
pub userinfo_override: bool,
#[serde(default)]
pub discovery: DiscoveryConfig,
}
#[derive(Clone, Debug, Deserialize)]
@ -63,4 +82,51 @@ pub struct ClientConfig {
// Mandatory for the following `ClientAuthMethod`s:
// [`Basic`,`Post`,`SharedJwt`]
pub secret: Option<String>,
pub auth_method: AuthMethod,
}
#[derive(Clone, Debug, Deserialize)]
pub struct Endpoints {
pub auth: url::Url,
pub token: Option<url::Url>,
pub userinfo: Option<url::Url>,
pub jwk: Option<url::Url>,
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DiscoveryConfig {
// Should be used for OPs supporting the OIDC Discovery endpoint
#[default]
Automatic,
Manual(Endpoints),
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthMethod {
None,
// Provide the client combo in the Authorization header
Basic,
// Provide the client combo as in the POST request body
Post,
// Provide a JWT signed with client secret
SharedJwt,
// Provide a JWT signed with a private key (OP needs to know the public key)
PrivateJwt,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Algorithm {
Rsa,
EdDsa,
}
#[derive(Clone, Debug, Deserialize)]
pub struct PrivateSigningKey {
pub kind: Algorithm,
pub path: String,
pub kid: Option<JsonWebKeyId>,
}

View file

@ -179,6 +179,7 @@ async fn run_server() -> io::Result<()> {
header::CONTENT_TYPE,
header::ACCEPT,
header::AUTHORIZATION,
header::LOCATION,
])
.max_age(Duration::from_secs(86400)),
)
@ -400,11 +401,12 @@ fn routes() -> Router {
"/_matrix/key/v2/server/:key_id",
get(server_server::get_server_keys_deprecated_route),
)
.route(
"/_matrix/client/v3/login/sso/redirect",
get(client_server::get_sso_redirect),
)
.route("/sso_return", get(client_server::get_sso_return))
// .route(
// "/_matrix/client/v3/login/sso/redirect",
// get(client_server::get_sso_redirect),
// )
.ruma_route(client_server::get_sso_redirect_with_idp_id)
// .route("/sso_return", get(client_server::get_sso_return))
.ruma_route(server_server::get_public_rooms_route)
.ruma_route(server_server::get_public_rooms_filtered_route)
.ruma_route(server_server::send_transaction_message_route)

View file

@ -75,8 +75,6 @@ pub struct Service {
pub rotate: RotationHandler,
pub shutdown: AtomicBool,
pub oidc: HashMap<String, openid::DiscoveredClient>,
pub macaroon: Option<macaroon::MacaroonKey>,
}
@ -190,34 +188,6 @@ impl Service {
.as_ref()
.map(|s| macaroon::MacaroonKey::generate(s.as_bytes()));
let oidc = {
let discover_all = config.oidc.iter().map(|provider| {
openid::DiscoveredClient::discover_with_client(
default_client.clone(),
provider.client.id.clone(),
provider.client.secret.clone(),
Some(provider.redirect_url.to_string()),
provider.issuer.clone(),
).map_ok(|client| (provider.id.clone(), client))
});
let pairs = future::try_join_all(discover_all).await.map_err(|e| {
error!("failed to discover one or more OIDC providers: {}", e);
Error::bad_config("failed to discover one or more OIDC providers.")
})?;
let mut result = HashMap::with_capacity(config.oidc.len());
for (id, client) in pairs {
let None = result.insert(id, client) else {
error!("OIDC providers must have unique IDs.");
return Err(Error::bad_config("OIDC providers must have unique IDs."));
};
}
result
};
let mut s = Self {
db,
config,
@ -249,7 +219,6 @@ impl Service {
rotate: RotationHandler::new(),
shutdown: AtomicBool::new(false),
macaroon,
oidc,
};
fs::create_dir_all(s.get_media_folder())?;

View file

@ -13,6 +13,7 @@ pub mod appservice;
pub mod globals;
pub mod key_backups;
pub mod media;
pub mod oidc;
pub mod pdu;
pub mod pusher;
pub mod rooms;
@ -34,6 +35,7 @@ pub struct Services {
pub key_backups: key_backups::Service,
pub media: media::Service,
pub sending: Arc<sending::Service>,
pub oidc: Arc<oidc::Service>,
}
impl Services {
@ -115,6 +117,7 @@ impl Services {
media: media::Service { db },
sending: sending::Service::build(db, &config),
oidc: oidc::Service::build(&config).await,
globals: globals::Service::load(db, config).await?,
})
}

252
src/service/oidc/mod.rs Normal file
View file

@ -0,0 +1,252 @@
use std::sync::Arc;
use macaroon::{Macaroon, MacaroonKey};
use openidconnect::{
core::{CoreAuthenticationFlow, CoreClient, CoreProviderMetadata},
reqwest::async_http_client,
AuthUrl, ClientId, ClientSecret, CsrfToken, IssuerUrl, Nonce, PkceCodeChallenge, RedirectUrl,
Scope, TokenUrl, UserInfoUrl,
};
use tokio::sync::OnceCell;
use crate::{
config::{DiscoveryConfig as Discovery, Metadata, ProviderConfig},
services, Config, Error,
};
pub const COOKIE_STATE_EXPIRATION_SECS: i64 = 10 * 60;
#[derive(Clone)]
pub struct Client(Arc<CoreClient>);
#[derive(Clone)]
pub struct Provider {
pub config: ProviderConfig,
pub client: OnceCell<Client>,
}
impl Provider {
pub fn new(config: ProviderConfig) -> Self {
Self {
config,
client: OnceCell::new(),
}
}
pub async fn handle_redirect(&self, redirect_url: &str) -> (url::Url, String) {
let client = self
.client
.get_or_try_init(|| async { Client::new(self.config.clone()).await })
.await
.map(|c| c.0.clone())
.unwrap();
let scopes = self
.config
.scopes
.iter()
.map(ToOwned::to_owned)
.map(Scope::new);
let csrf = CsrfToken::new_random();
let nonce = Nonce::new_random();
let tmp = (csrf.clone(), nonce.clone());
let mut req = client
.authorize_url(
CoreAuthenticationFlow::Implicit(true),
move || csrf,
move || nonce,
)
.add_scopes(scopes);
let (challenge, verifier) = PkceCodeChallenge::new_random_sha256();
if let Some(true) = self.config.pkce {
req = req.set_pkce_challenge(challenge);
}
let (url, csrf, nonce) = req.url();
let cookie = self.generate_macaroon(
csrf.secret(),
nonce.secret(),
redirect_url,
self.config.pkce.map(|_| verifier.secret().as_str()),
);
(url, cookie)
}
pub fn generate_macaroon(
&self,
state: &str,
nonce: &str,
redirect_url: &str,
pkce: Option<&str>,
) -> String {
let key = services()
.globals
.macaroon
.unwrap_or_else(MacaroonKey::generate_random);
let mut macaroon = Macaroon::create(None, &key, "oidc".into()).unwrap();
let expires = chrono::Utc::now() + chrono::TimeDelta::seconds(COOKIE_STATE_EXPIRATION_SECS);
let idp_id = self.config.metadata.id.as_str();
macaroon.add_first_party_caveat(format!("idp_id = {idp_id}").into());
macaroon.add_first_party_caveat(format!("state = {state}").into());
macaroon.add_first_party_caveat(format!("nonce = {nonce}").into());
macaroon.add_first_party_caveat(format!("redirect_url = {redirect_url}").into());
macaroon.add_first_party_caveat(format!("time < {expires}").into());
if let Some(verifier) = pkce {
macaroon.add_first_party_caveat(format!("verifier = {}", verifier).into());
}
macaroon.serialize(macaroon::Format::V2).unwrap()
}
}
pub struct Service {
pub inner: Vec<Provider>,
}
impl Service {
pub async fn build(config: &Config) -> Arc<Self> {
Arc::new(Self {
inner: config.oidc.clone().into_iter().map(Provider::new).collect(),
})
}
pub async fn get_provider(&self, idp_id: impl AsRef<str>) -> Result<Provider, ()> {
let Some(found) = self
.inner
.iter()
.find(|p| p.config.metadata.id == idp_id.as_ref())
.map(Clone::clone)
else {
return Err(());
};
// let client = found.client
// .get_or_try_init(|| async { Client::new(config.clone()).await })
// .await
// .unwrap();
Ok(found)
}
pub fn get_all(&self) -> &[Provider] {
self.inner.as_slice()
}
// TODO
pub fn get_metadata(&self) -> Vec<Metadata> {
self.inner
.iter()
.map(|p| p.config.metadata.clone())
.collect()
}
// pub async fn generate_auth_url<'s, S>(&self, idp_id: String, scopes: S) -> ()
// where
// S: Iterator<Item = &'s str>,
// {
// // TODO: PKCE challenge
// if false {
// let (challenge, verifier) = PkceCodeChallenge::new_random_sha256();
// // return auth_url.set_pkce_challenge(challenge).url()
// }
// // auth_url.url()
// }
// pub async fn exchange_auth_code(&self, auth_code: AuthorizationCode) {
// // -> Result<StandardTokenResponse, Error> {
// let provider = self.get_client("something").await.unwrap();
// let req = provider.exchange_code(auth_code);
// if false {
// // return req.set_pkce_verifier(pkce_verifier).request(http_client)?
// }
// let resp = req.request(http_client).unwrap();
// let id_token = resp.id_token().unwrap();
// let access_token = resp.access_token();
// let claims = id_token
// .claims(&provider.id_token_verifier(), &Nonce::new("".into()))
// .unwrap();
// if let Some(hash) = claims.access_token_hash() {
// &AccessTokenHash::from_token(access_token, &id_token.signing_alg().unwrap()).unwrap()
// == hash;
// }
// // need `UserInfo` endpoint
// // if let Some(subject) = config.subject_claim {
// if false {
// let req = provider
// .user_info(
// access_token.clone(),
// Some(SubjectIdentifier::new("id".to_owned())),
// )
// .unwrap();
// let ok: CoreUserInfoClaims = req.request(http_client).unwrap();
// }
// }
}
impl Client {
pub async fn new(config: ProviderConfig) -> Result<Self, Error> {
let mut base_url = url::Url::try_from(
services()
.globals
.well_known_client()
.as_deref()
.unwrap_or(services().globals.server_name().as_str()),
)
.expect("server_name should be a valid URL");
base_url.set_path("_conduit/client/oidc/callback");
let redirect_url = RedirectUrl::from_url(base_url);
let client = match config.discovery {
Discovery::Automatic => {
let url = config.issuer.to_string();
let url = url.strip_suffix("/").unwrap();
let discovery = CoreProviderMetadata::discover_async(
// https://github.com/ramosbugs/openidconnect-rs/issues/77
IssuerUrl::new(url.to_owned()).unwrap(),
async_http_client,
)
.await
.unwrap();
// .map_err(|e| Error::BadConfig(&e.to_string()))?;
CoreClient::from_provider_metadata(
discovery,
ClientId::new(config.client.id),
config.client.secret.map(ClientSecret::new),
)
}
Discovery::Manual(endpoints) => CoreClient::new(
ClientId::new(config.client.id),
config.client.secret.map(ClientSecret::new),
IssuerUrl::from_url(config.issuer),
AuthUrl::from_url(endpoints.auth),
endpoints.token.map(TokenUrl::from_url),
endpoints.userinfo.map(UserInfoUrl::from_url),
Default::default(),
)
.set_redirect_uri(redirect_url),
};
Ok(Self(Arc::new(client)))
}
}

View file

@ -4,13 +4,17 @@ use argon2::{Config, Variant};
use cmp::Ordering;
use rand::prelude::*;
use ring::digest;
use ruma::{canonical_json::try_from_json_map, CanonicalJsonError, CanonicalJsonObject};
use ruma::{
canonical_json::try_from_json_map, CanonicalJsonError, CanonicalJsonObject, MxcUri, MxcUriError,
};
use std::{
cmp, fmt,
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use crate::services;
pub fn millis_since_unix_epoch() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
@ -180,3 +184,26 @@ impl<'a> fmt::Display for HtmlEscape<'a> {
Ok(())
}
}
pub fn mxc_to_http_or_none(mxc_uri: Option<&MxcUri>, width: &str, height: &str) -> Option<String> {
let Some(mxc_uri) = mxc_uri else {
return None;
};
let base_url = services()
.globals
.well_known_client()
.as_deref()
.unwrap_or(services().globals.server_name().as_str());
let (server_name, media_id) = mxc_uri.parts().ok()?;
let mut host =
format!("https://{base_url}/_matrix/media/v3/thumbnail/{server_name}/{media_id}")
.parse::<url::Url>()
.expect("server_name should be a valid domain");
host.query_pairs_mut()
.append_pair("width", width)
.append_pair("height", height)
.append_pair("method", "scale");
Some(host.to_string())
}