Skip to main content

mas_handlers/upstream_oauth2/
template.rs

1// Copyright 2026 Element Creations Ltd.
2// Copyright 2024, 2025 New Vector Ltd.
3// Copyright 2023, 2024 The Matrix.org Foundation C.I.C.
4//
5// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
6// Please see LICENSE files in the repository root for full details.
7
8use std::{collections::HashMap, sync::Arc};
9
10use base64ct::{Base64, Base64Unpadded, Base64Url, Base64UrlUnpadded, Encoding};
11use minijinja::{
12    Environment, Error, ErrorKind, Value,
13    value::{Enumerator, Object},
14};
15
16/// Context passed to the attribute mapping template
17///
18/// The variables available in the template are:
19/// - `user`: claims for the user, merged from the ID token and userinfo
20///   endpoint
21/// - `id_token_claims`: claims from the ID token
22/// - `userinfo_claims`: claims from the userinfo endpoint
23/// - `extra_callback_parameters`: extra parameters passed to the callback
24#[derive(Debug, Default)]
25pub(crate) struct AttributeMappingContext {
26    id_token_claims: Option<HashMap<String, serde_json::Value>>,
27    extra_callback_parameters: Option<serde_json::Value>,
28    userinfo_claims: Option<serde_json::Value>,
29}
30
31impl AttributeMappingContext {
32    pub fn new() -> Self {
33        Self::default()
34    }
35
36    pub fn with_id_token_claims(
37        mut self,
38        id_token_claims: HashMap<String, serde_json::Value>,
39    ) -> Self {
40        self.id_token_claims = Some(id_token_claims);
41        self
42    }
43
44    pub fn with_extra_callback_parameters(
45        mut self,
46        extra_callback_parameters: serde_json::Value,
47    ) -> Self {
48        self.extra_callback_parameters = Some(extra_callback_parameters);
49        self
50    }
51
52    pub fn with_userinfo_claims(mut self, userinfo_claims: serde_json::Value) -> Self {
53        self.userinfo_claims = Some(userinfo_claims);
54        self
55    }
56
57    pub fn build(self) -> Value {
58        Value::from_object(self)
59    }
60}
61
62impl Object for AttributeMappingContext {
63    fn get_value(self: &Arc<Self>, name: &Value) -> Option<Value> {
64        match name.as_str()? {
65            "user" => {
66                if self.id_token_claims.is_none() && self.userinfo_claims.is_none() {
67                    return None;
68                }
69                let mut merged_user: HashMap<String, serde_json::Value> = HashMap::new();
70                if let serde_json::Value::Object(userinfo) = self
71                    .userinfo_claims
72                    .clone()
73                    .unwrap_or(serde_json::Value::Null)
74                {
75                    merged_user.extend(userinfo);
76                }
77                if let Some(id_token) = self.id_token_claims.clone() {
78                    merged_user.extend(id_token);
79                }
80                Some(Value::from_serialize(merged_user))
81            }
82            "id_token_claims" => self.id_token_claims.as_ref().map(Value::from_serialize),
83            "userinfo_claims" => self.userinfo_claims.as_ref().map(Value::from_serialize),
84            "extra_callback_parameters" => self
85                .extra_callback_parameters
86                .as_ref()
87                .map(Value::from_serialize),
88            _ => None,
89        }
90    }
91
92    fn enumerate(self: &Arc<Self>) -> Enumerator {
93        let mut attrs = Vec::new();
94        if self.id_token_claims.is_some() || self.userinfo_claims.is_none() {
95            attrs.push(minijinja::Value::from("user"));
96        }
97        if self.id_token_claims.is_some() {
98            attrs.push(minijinja::Value::from("id_token_claims"));
99        }
100        if self.userinfo_claims.is_some() {
101            attrs.push(minijinja::Value::from("userinfo_claims"));
102        }
103        if self.extra_callback_parameters.is_some() {
104            attrs.push(minijinja::Value::from("extra_callback_parameters"));
105        }
106        Enumerator::Values(attrs)
107    }
108}
109
110fn b64decode(value: &str) -> Result<Value, Error> {
111    // We're not too concerned about the performance of this filter, so we'll just
112    // try all the base64 variants when decoding
113    let bytes = Base64::decode_vec(value)
114        .or_else(|_| Base64Url::decode_vec(value))
115        .or_else(|_| Base64Unpadded::decode_vec(value))
116        .or_else(|_| Base64UrlUnpadded::decode_vec(value))
117        .map_err(|e| {
118            Error::new(
119                ErrorKind::InvalidOperation,
120                "Failed to decode base64 string",
121            )
122            .with_source(e)
123        })?;
124
125    // It is not obvious, but the cleanest way to get a Value stored as raw bytes is
126    // to wrap it in an Arc, because Value implements From<Arc<Vec<u8>>>
127    Ok(Value::from(Arc::new(bytes)))
128}
129
130fn b64encode(bytes: &[u8]) -> String {
131    Base64::encode_string(bytes)
132}
133
134/// Decode a Tag-Length-Value encoded byte array into a map of tag to value.
135fn tlvdecode(bytes: &[u8]) -> Result<HashMap<Value, Value>, Error> {
136    let mut iter = bytes.iter().copied();
137    let mut ret = HashMap::new();
138    // TODO: this assumes the tag and the length are both single bytes, which is not
139    // always the case with protobufs. We should properly decode varints
140    // here.
141    while let Some(tag) = iter.next() {
142        let len = iter
143            .next()
144            .ok_or_else(|| Error::new(ErrorKind::InvalidOperation, "Invalid ILV encoding"))?;
145
146        let mut bytes = Vec::with_capacity(len.into());
147        for _ in 0..len {
148            bytes.push(
149                iter.next().ok_or_else(|| {
150                    Error::new(ErrorKind::InvalidOperation, "Invalid ILV encoding")
151                })?,
152            );
153        }
154
155        ret.insert(tag.into(), Value::from(Arc::new(bytes)));
156    }
157
158    Ok(ret)
159}
160
161fn string(value: &Value) -> String {
162    value.to_string()
163}
164
165fn from_json(value: &str) -> Result<Value, minijinja::Error> {
166    let value: serde_json::Value = serde_json::from_str(value).map_err(|e| {
167        minijinja::Error::new(
168            minijinja::ErrorKind::InvalidOperation,
169            "Failed to decode JSON",
170        )
171        .with_source(e)
172    })?;
173
174    Ok(Value::from_serialize(value))
175}
176
177pub fn environment() -> Environment<'static> {
178    let mut env = Environment::new();
179
180    minijinja_contrib::add_to_environment(&mut env);
181
182    env.add_filter("b64decode", b64decode);
183    env.add_filter("b64encode", b64encode);
184    env.add_filter("tlvdecode", tlvdecode);
185    env.add_filter("string", string);
186    env.add_filter("from_json", from_json);
187
188    env.set_unknown_method_callback(minijinja_contrib::pycompat::unknown_method_callback);
189
190    env
191}
192
193#[cfg(test)]
194mod tests {
195    use super::environment;
196
197    #[test]
198    fn test_split() {
199        let env = environment();
200        let res = env
201            .render_str(r#"{{ 'foo, bar' | split(', ') | join(" | ") }}"#, ())
202            .unwrap();
203        assert_eq!(res, "foo | bar");
204    }
205
206    #[test]
207    fn test_ilvdecode() {
208        let env = environment();
209        let res = env
210            .render_str(
211                r#"
212                    {%- set tlv = 'Cg0wLTM4NS0yODA4OS0wEgRtb2Nr' | b64decode | tlvdecode -%}
213                    {%- if tlv[18]|string != 'mock' -%}
214                        {{ "FAIL"/0 }}
215                    {%- endif -%}
216                    {{- tlv[10]|string -}}
217                "#,
218                (),
219            )
220            .unwrap();
221        assert_eq!(res, "0-385-28089-0");
222    }
223
224    #[test]
225    fn test_base64_decode() {
226        let env = environment();
227
228        let res = env
229            .render_str("{{ 'cGFkZGluZw==' | b64decode }}", ())
230            .unwrap();
231        assert_eq!(res, "padding");
232
233        let res = env
234            .render_str("{{ 'dW5wYWRkZWQ' | b64decode }}", ())
235            .unwrap();
236        assert_eq!(res, "unpadded");
237    }
238}