Skip to main content

vault_core/
oauth.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! OAuth refresh-token grants, shared by `unv oauth refresh` and the desktop
4//! app's "Refresh access token" (Phase 24.5). Pure over JSON: the HTTP call is
5//! the caller's (the CLI's blocking client, the app's pinned `remote_request`),
6//! so there is exactly one reading of what an issuer's answer means and one rule
7//! for what gets stored.
8
9use crate::type_emit::var;
10use serde_json::{json, Value};
11
12pub fn set_var(entry: &mut Value, key: &str, value: &str, secret: bool) {
13    let vars = entry
14        .as_object_mut()
15        .expect("entry is an object")
16        .entry("extra_vars")
17        .or_insert_with(|| json!([]));
18    let vars = vars.as_array_mut().expect("extra_vars is an array");
19    match vars
20        .iter_mut()
21        .find(|v| v.get("key").and_then(Value::as_str) == Some(key))
22    {
23        Some(slot) => slot["value"] = json!(value),
24        None => vars.push(json!({ "key": key, "value": value, "secret": secret })),
25    }
26}
27
28/// The request an `oauth_client` entry makes to refresh itself: the `token_url`
29/// and the form fields. Refuses plain http except to localhost, and an entry with
30/// no refresh token, before anything is sent.
31pub fn refresh_request(entry: &Value) -> Result<(String, Vec<(String, String)>), String> {
32    let url = var(entry, "token_url").to_string();
33    if !(url.starts_with("https://")
34        || url.starts_with("http://127.0.0.1")
35        || url.starts_with("http://localhost"))
36    {
37        return Err("token_url must be https:// (plain http is allowed for localhost only)".into());
38    }
39    let refresh = var(entry, "refresh_token");
40    if refresh.is_empty() {
41        return Err("the entry holds no refresh_token".into());
42    }
43    let mut form = vec![
44        ("grant_type".to_string(), "refresh_token".to_string()),
45        ("refresh_token".to_string(), refresh.to_string()),
46        ("client_id".to_string(), var(entry, "client_id").to_string()),
47    ];
48    for (field, name) in [("client_secret", "client_secret"), ("scopes", "scope")] {
49        let v = var(entry, field);
50        if !v.is_empty() {
51            form.push((name.to_string(), v.to_string()));
52        }
53    }
54    Ok((url, form))
55}
56
57/// The host a refresh would contact, for the confirmation prompt.
58pub fn refresh_host(url: &str) -> &str {
59    url.split("://")
60        .nth(1)
61        .and_then(|r| r.split('/').next())
62        .unwrap_or("")
63}
64
65/// What the token endpoint said, reduced to what is stored.
66#[derive(Debug, PartialEq)]
67pub struct Grant {
68    pub access_token: String,
69    pub refresh_token: Option<String>,
70    pub expires_in: Option<i64>,
71}
72
73pub fn parse_grant(body: &Value) -> Result<Grant, String> {
74    if let Some(err) = body.get("error").and_then(Value::as_str) {
75        // Names the issuer's error code, never echoes the response body.
76        return Err(format!("the issuer refused the refresh: {err}"));
77    }
78    let access = body
79        .get("access_token")
80        .and_then(Value::as_str)
81        .filter(|s| !s.is_empty())
82        .ok_or("the response has no access_token")?;
83    Ok(Grant {
84        access_token: access.to_string(),
85        refresh_token: body
86            .get("refresh_token")
87            .and_then(Value::as_str)
88            .filter(|s| !s.is_empty())
89            .map(String::from),
90        expires_in: body.get("expires_in").and_then(Value::as_i64),
91    })
92}
93
94/// Stores a grant on the entry. Returns whether the refresh token rotated.
95pub fn apply_grant(entry: &mut Value, g: &Grant, now_unix: i64) -> bool {
96    let rotated = g
97        .refresh_token
98        .as_deref()
99        .is_some_and(|r| r != var(entry, "refresh_token"));
100    if let Some(r) = &g.refresh_token {
101        set_var(entry, "refresh_token", r, true);
102    }
103    set_var(entry, "access_token", &g.access_token, true);
104    if let Some(secs) = g.expires_in {
105        let at = crate::pool::iso_at(now_unix + secs);
106        set_var(entry, "access_expires_at", &at, false);
107    }
108    rotated
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114    use crate::type_emit::var;
115
116    fn entry() -> Value {
117        json!({"secretType":"oauth_client","provider":"Slack","extra_vars":[
118            {"key":"refresh_token","value":"old-r","secret":true}]})
119    }
120
121    #[test]
122    fn a_rotated_refresh_token_replaces_the_old_one_and_is_reported() {
123        let g =
124            parse_grant(&json!({"access_token":"a1","refresh_token":"new-r","expires_in":3600}))
125                .unwrap();
126        let mut e = entry();
127        assert!(apply_grant(&mut e, &g, 1_700_000_000));
128        assert_eq!(var(&e, "refresh_token"), "new-r");
129        assert_eq!(var(&e, "access_token"), "a1");
130        assert_eq!(var(&e, "access_expires_at"), "2023-11-14T23:13:20Z");
131    }
132
133    #[test]
134    fn an_unrotated_response_keeps_the_stored_refresh_token() {
135        let g = parse_grant(&json!({"access_token":"a2"})).unwrap();
136        let mut e = entry();
137        assert!(!apply_grant(&mut e, &g, 0));
138        assert_eq!(var(&e, "refresh_token"), "old-r");
139        assert_eq!(var(&e, "access_expires_at"), "");
140    }
141
142    #[test]
143    fn issuer_errors_are_named_without_echoing_the_body() {
144        let err = parse_grant(
145            &json!({"error":"invalid_grant","error_description":"secret-bearing text"}),
146        )
147        .unwrap_err();
148        assert!(err.contains("invalid_grant") && !err.contains("secret-bearing"));
149        assert!(parse_grant(&json!({})).is_err());
150    }
151}