Skip to main content

mcp_server_core/
upstream.rs

1//! Signing in through the upstream service's own OAuth: the person approves access at the
2//! provider (FreeAgent, GitHub, Google and the like) instead of pasting a key, and the credential
3//! the provider grants is sealed into their tokens like any other carried credential.
4//!
5//! A [`CredentialVerifier`] opts in by returning an
6//! [`UpstreamSignIn`] from [`upstream`](crate::credential::CredentialVerifier::upstream). The
7//! sign-in page then asks the person to approve the MCP client and continue to the provider, and
8//! the server, acting as the provider's OAuth client, finishes the sign-in at
9//! [`CALLBACK_PATH`]:
10//!
11//! 1. `GET /authorize` shows which client is asking and where it will be sent, with a button to
12//!    continue to the provider. Consent is asked here for every client, because every client
13//!    reaches the provider under this server's one OAuth client id.
14//! 2. `POST /authorize` sets a short-lived cookie holding the pending authorization request,
15//!    encrypted and bound to a random `state`, and sends the browser to
16//!    [`UpstreamSignIn::authorize_url`].
17//! 3. The provider sends the browser back to `PUBLIC_URL/callback` with a code and the `state`.
18//!    The server checks the `state` against the cookie, calls [`UpstreamSignIn::exchange`], seals
19//!    the [`UpstreamGrant`]'s credential into an authorization code and sends the browser on to the
20//!    MCP client, which redeems the code at `/token` as usual.
21//!
22//! Nothing is stored on the server: the pending request lives in the person's browser, and the
23//! credential in their tokens. Register `PUBLIC_URL/callback` as a redirect URI with the provider.
24//!
25//! The credential is usually the provider's refresh token, from which tools obtain access tokens
26//! as they need them; it is handed to tools as a [`Credential`](crate::credential::Credential)
27//! exactly as a pasted key would be.
28
29use crate::credential::{CheckFuture, CredentialCheck, CredentialVerifier};
30use std::future::Future;
31use std::pin::Pin;
32
33/// Where the provider sends people back to, below `PUBLIC_URL`. A service cannot be named
34/// `callback` when people sign in through an upstream provider.
35pub const CALLBACK_PATH: &str = "/callback";
36
37/// How long a person has to approve access at the provider, from leaving the sign-in page.
38pub const PENDING_TTL_SECS: u64 = 600;
39
40/// Longest credential an exchange may return, in bytes. It travels sealed in every access token,
41/// so it is kept small.
42pub const MAX_UPSTREAM_CREDENTIAL_LEN: usize = 2048;
43
44/// Longest subject an exchange may name, in characters.
45pub const MAX_SUBJECT_CHARS: usize = 200;
46
47/// What the provider granted: the credential to seal into the person's tokens and, optionally,
48/// who they are.
49#[derive(Clone)]
50#[non_exhaustive]
51pub struct UpstreamGrant {
52    /// The credential tools receive, such as the provider's refresh token. Never logged.
53    pub credential: String,
54    /// Who signed in, as the `sub` of their tokens and the audit log's subject, such as the
55    /// provider's user id. It must not reveal the credential, and is readable by anyone who sees
56    /// a token or a log line. `None` lets the server name them from the credential
57    /// ([`AuthState::subject_of`](crate::oauth::AuthState::subject_of)), which changes every time
58    /// the provider grants a new credential.
59    pub subject: Option<String>,
60}
61
62impl UpstreamGrant {
63    /// A grant of `credential`, named by the server.
64    pub fn new(credential: impl Into<String>) -> Self {
65        UpstreamGrant {
66            credential: credential.into(),
67            subject: None,
68        }
69    }
70
71    /// The same grant, naming who signed in.
72    pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
73        self.subject = Some(subject.into());
74        self
75    }
76}
77
78impl std::fmt::Debug for UpstreamGrant {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        f.debug_struct("UpstreamGrant")
81            .field("credential", &"[redacted]")
82            .field("subject", &self.subject)
83            .finish()
84    }
85}
86
87/// The outcome of exchanging the provider's authorization code.
88#[derive(Debug)]
89#[non_exhaustive]
90pub enum Exchange {
91    /// The provider granted access.
92    Granted(UpstreamGrant),
93    /// The provider refused the code (expired, already used, or for another client), with a reason
94    /// to show the person. Counts as a failed attempt for the sign-in limits.
95    Refused(String),
96    /// The provider could not be reached or answered unexpectedly: say why. It does not count as
97    /// a failed attempt.
98    Unavailable(String),
99}
100
101/// The future returned by [`UpstreamSignIn::exchange`].
102pub type ExchangeFuture<'a> = Pin<Box<dyn Future<Output = Exchange> + Send + 'a>>;
103
104/// The upstream provider's side of the sign-in: where to send people and how to turn the code the
105/// provider sends back into a credential.
106///
107/// ```
108/// use mcp_server_core::upstream::{Exchange, ExchangeFuture, UpstreamGrant, UpstreamSignIn};
109///
110/// struct Example;
111///
112/// impl UpstreamSignIn for Example {
113///     fn provider(&self) -> &str {
114///         "Example"
115///     }
116///     fn authorize_url(&self, redirect_uri: &str, state: &str) -> String {
117///         let mut url = url::Url::parse("https://example.com/oauth/authorize").unwrap();
118///         url.query_pairs_mut()
119///             .append_pair("response_type", "code")
120///             .append_pair("client_id", "my-client-id")
121///             .append_pair("redirect_uri", redirect_uri)
122///             .append_pair("state", state);
123///         url.into()
124///     }
125///     fn exchange<'a>(&'a self, code: &'a str, _redirect_uri: &'a str) -> ExchangeFuture<'a> {
126///         Box::pin(async move {
127///             // POST the code to the provider's token endpoint here.
128///             Exchange::Granted(UpstreamGrant::new(format!("refresh-token-for-{code}")))
129///         })
130///     }
131/// }
132/// # fn main() {}
133/// ```
134pub trait UpstreamSignIn: Send + Sync + 'static {
135    /// The provider's name as it reads in a sentence, e.g. "FreeAgent": the sign-in page's button
136    /// says "Continue to FreeAgent".
137    fn provider(&self) -> &str;
138    /// The provider's authorization URL for this sign-in: its authorization endpoint with at least
139    /// `response_type=code`, the server's OAuth client id, `redirect_uri` and `state`, each passed
140    /// on exactly as given. `redirect_uri` is `PUBLIC_URL/callback`.
141    fn authorize_url(&self, redirect_uri: &str, state: &str) -> String;
142    /// Exchanges the authorization `code` the provider sent back, at its token endpoint, sending
143    /// the same `redirect_uri`. Runs with a timeout.
144    fn exchange<'a>(&'a self, code: &'a str, redirect_uri: &'a str) -> ExchangeFuture<'a>;
145}
146
147/// A [`CredentialVerifier`] for people who sign in through `upstream`, labelled `label` (such as
148/// "FreeAgent account"). Its credentials are carried and never accepted as bearer tokens, and it
149/// changes every sign-in's version with `generation` (pass the bytes that should sign everyone out
150/// when they change, such as the provider's environment and client id).
151pub struct UpstreamVerifier<U> {
152    label: String,
153    help: String,
154    generation: Vec<u8>,
155    upstream: U,
156}
157
158impl<U: UpstreamSignIn> UpstreamVerifier<U> {
159    /// People sign in through `upstream`; `label` names what they sign in with.
160    pub fn new(label: impl Into<String>, upstream: U) -> Self {
161        UpstreamVerifier {
162            label: label.into(),
163            help: String::new(),
164            generation: Vec::new(),
165            upstream,
166        }
167    }
168
169    /// One sentence of help on the sign-in page.
170    pub fn with_help(mut self, help: impl Into<String>) -> Self {
171        self.help = help.into();
172        self
173    }
174
175    /// Bytes that sign everyone out when they change. See
176    /// [`CredentialVerifier::generation`].
177    pub fn with_generation(mut self, generation: impl Into<Vec<u8>>) -> Self {
178        self.generation = generation.into();
179        self
180    }
181
182    /// The provider.
183    pub fn provider(&self) -> &U {
184        &self.upstream
185    }
186}
187
188impl<U: UpstreamSignIn> CredentialVerifier for UpstreamVerifier<U> {
189    fn label(&self) -> &str {
190        &self.label
191    }
192    fn help(&self) -> &str {
193        &self.help
194    }
195    /// Never asked: nothing is typed, and bearer credentials are not accepted.
196    fn check<'a>(&'a self, _credential: &'a str) -> CheckFuture<'a> {
197        Box::pin(async { CredentialCheck::Invalid(None) })
198    }
199    fn accepts_bearer(&self) -> bool {
200        false
201    }
202    fn generation(&self) -> &[u8] {
203        &self.generation
204    }
205    fn upstream(&self) -> Option<&dyn UpstreamSignIn> {
206        Some(&self.upstream)
207    }
208}
209
210/// Whether `subject` can name a person: non-empty, at most [`MAX_SUBJECT_CHARS`], no control
211/// characters.
212pub(crate) fn valid_subject(subject: &str) -> bool {
213    !subject.trim().is_empty()
214        && subject.chars().count() <= MAX_SUBJECT_CHARS
215        && !subject.chars().any(char::is_control)
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    struct Fake;
223
224    impl UpstreamSignIn for Fake {
225        fn provider(&self) -> &str {
226            "Fake"
227        }
228        fn authorize_url(&self, _redirect_uri: &str, _state: &str) -> String {
229            "https://fake.example.com/authorize".into()
230        }
231        fn exchange<'a>(&'a self, _code: &'a str, _redirect_uri: &'a str) -> ExchangeFuture<'a> {
232            Box::pin(async { Exchange::Refused("no".into()) })
233        }
234    }
235
236    #[test]
237    fn the_verifier_carries_credentials_but_never_takes_them_as_bearer_tokens() {
238        let v = UpstreamVerifier::new("Fake account", Fake)
239            .with_help("Sign in at Fake.")
240            .with_generation(b"live".to_vec());
241        assert_eq!(v.label(), "Fake account");
242        assert_eq!(v.help(), "Sign in at Fake.");
243        assert!(v.carried());
244        assert!(!v.accepts_bearer());
245        assert_eq!(v.generation(), b"live");
246        assert_eq!(v.upstream().map(|u| u.provider()), Some("Fake"));
247    }
248
249    #[tokio::test]
250    async fn the_verifier_rejects_anything_checked() {
251        let v = UpstreamVerifier::new("Fake account", Fake);
252        assert_eq!(v.check("anything").await, CredentialCheck::Invalid(None));
253    }
254
255    #[test]
256    fn grants_never_show_their_credential() {
257        let g = UpstreamGrant::new("secret-refresh-token").with_subject("user:1");
258        let shown = format!("{g:?}");
259        assert!(!shown.contains("secret"), "{shown}");
260        assert!(shown.contains("user:1"), "{shown}");
261    }
262
263    #[test]
264    fn subjects_are_short_printable_names() {
265        assert!(valid_subject("freeagent:user:123"));
266        for bad in ["", "   ", "a\nb", &"x".repeat(MAX_SUBJECT_CHARS + 1)] {
267            assert!(!valid_subject(bad), "{bad:?}");
268        }
269    }
270}