Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_net/tests/oauth.rs

12.0 KiB, 5 runs

created by r1870400018:79743, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! An OAuth sign-in for a protected MCP server, against a resource and an authorisation server served
2//! here on loopback: discovery from the 401, registration, PKCE checked by the server, the browser's
3//! round trip through the loopback listener, the exchange, a refresh, and refusals that carry no secret.
4
5use oxedyne_fe2o3_core::{
6 prelude::*,
7 sha256,
8};
9use oxedyne_fe2o3_net::{
10 http::{
11 client::url_request,
12 fields::HeaderName,
13 header::HttpMethod,
14 loc::Url,
15 pct,
16 },
17 oauth::{
18 self,
19 Bounds,
20 Grant,
21 Loopback,
22 Pkce,
23 Registered,
24 },
25};
26use oxedyne_fe2o3_text::base64;
27
28use std::{
29 sync::{
30 Arc,
31 Mutex,
32 },
33 time::Duration,
34};
35
36use tokio::{
37 io::{
38 AsyncReadExt,
39 AsyncWriteExt,
40 },
41 net::{
42 TcpListener,
43 TcpStream,
44 },
45};
46
47
48fn main() {
49 let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
50 Ok(rt) => rt,
51 Err(e) => { println!("no runtime: {}", e); std::process::exit(1); },
52 };
53 let mut failed = 0;
54 let mut check = |name: &str, r: Outcome<()>| match r {
55 Ok(()) => println!("test {} ... ok", name),
56 Err(e) => { println!("test {} ... FAILED\n{}", name, e); failed += 1; },
57 };
58 check("a_bearer_challenges_parameters_are_read", challenge());
59 check("a_callback_query_reads_its_state_and_code_or_refusal", callback());
60 check("grant_json_round_trips_and_debug_holds_no_secret", grant());
61 check("a_sign_in_runs_from_the_401_to_a_refreshed_token", rt.block_on(sign_in()));
62 check("a_resource_with_no_metadata_takes_the_default_endpoints", rt.block_on(bare()));
63 println!("\ntest result: {}. {} failed", if failed == 0 { "ok" } else { "FAILED" }, failed);
64 std::process::exit(if failed == 0 { 0 } else { 1 });
65}
66
67fn want(ok: bool, what: &str) -> Outcome<()> {
68 match ok {
69 true => Ok(()),
70 false => Err(err!("{}", what; Test)),
71 }
72}
73
74fn bounds() -> Bounds {
75 Bounds { tls: None, wait: Duration::from_secs(5), body_max: 65536 }
76}
77
78fn challenge() -> Outcome<()> {
79 let c = oauth::challenge(r#"Bearer error="invalid_token", resource_metadata="http://h/.well-known/x", scope="a b""#);
80 res!(want(c == vec![(fmt!("error"), fmt!("invalid_token")), (fmt!("resource_metadata"), fmt!("http://h/.well-known/x")),
81 (fmt!("scope"), fmt!("a b"))], &fmt!("{:?}", c)));
82 want(oauth::challenge("Basic realm=\"x\"").is_empty(), "a Basic challenge is not a bearer's")
83}
84
85fn callback() -> Outcome<()> {
86 let (s, b) = oauth::callback("?code=C%2F9&state=st-1&iss=x");
87 res!(want(s == "st-1" && matches!(&b, oauth::Back::Code(c) if c == "C/9") && !fmt!("{:?}", b).contains("C/9"),
88 &fmt!("a code: {} {:?}", s, b)));
89 let (s, b) = oauth::callback("state=st-2&error=access_denied&error_description=No+thanks&code=C");
90 res!(want(s == "st-2" && matches!(&b, oauth::Back::Refused(w) if w == "The sign-in was refused: access_denied, No thanks"),
91 &fmt!("a refusal outranks a code: {:?}", b)));
92 let (s, b) = oauth::callback("state=st-3");
93 want(s == "st-3" && matches!(b, oauth::Back::Bare), "neither code nor error is bare")
94}
95
96fn grant() -> Outcome<()> {
97 let g = Grant { url: fmt!("https://m/mcp"), token_url: fmt!("https://a/token"), resource: fmt!("https://m/mcp"),
98 client: Registered { id: fmt!("c"), secret: fmt!("CS-9") },
99 tokens: oauth::Tokens { access: fmt!("AT-9"), refresh: fmt!("RT-9"), expires: 7, scope: fmt!("s") } };
100 let back = res!(Grant::of_json(&res!(g.to_json())));
101 res!(want(back == g, "the grant read back is the one kept"));
102 let d = fmt!("{:?}", g);
103 res!(want(!d.contains("AT-9") && !d.contains("RT-9") && !d.contains("CS-9"), &fmt!("Debug shows a secret: {}", d)));
104 res!(want(g.tokens.due(Duration::from_secs(1)), "a token past its time is due"));
105 want(Grant::of_json("{}").is_err(), "an empty grant is refused")
106}
107
108// The servers' memory: the challenge each code was asked with.
109#[derive(Default)]
110struct Seen {
111 challenge: String,
112 resource: String,
113}
114
115async fn sign_in() -> Outcome<()> {
116 let l = res!(TcpListener::bind("127.0.0.1:0").await);
117 let port = res!(l.local_addr()).port();
118 let seen = Arc::new(Mutex::new(Seen::default()));
119 tokio::spawn(serve(l, port, seen.clone()));
120 let b = bounds();
121 let mcp = fmt!("http://127.0.0.1:{}/mcp", port);
122 let meta = res!(oauth::discover(&mcp, &b).await);
123 res!(want(meta.issuer == fmt!("http://127.0.0.1:{}/as", port) && meta.token.ends_with("/as/token")
124 && meta.register.ends_with("/as/register") && meta.scope == "mcp:tools" && meta.resource == mcp, &fmt!("{:?}", meta)));
125 let lb = res!(Loopback::bind(0).await);
126 let client = res!(oauth::register(&meta, &lb.redirect(), "test", &b).await);
127 res!(want(client.id == "cl-1", &fmt!("{:?}", client)));
128 let (pkce, state) = (Pkce::new(), base64::random_url(16));
129 let at = oauth::authorize_url(&meta, &client, &lb.redirect(), &pkce, &state);
130 let link = lb.link();
131 // The browser: the short link, the authorisation server, then back, after a stray callback of another state.
132 let browser = async {
133 let stray = res!(get(&fmt!("{}callback?code=X&state=other", link)).await);
134 res!(want(stray.0 == 400, "a callback of another state is refused"));
135 let (s1, to) = res!(get(&link).await);
136 res!(want(s1 == 302 && to == at, &fmt!("the link sends on to the sign-in: {} {}", s1, to)));
137 let (s2, back) = res!(get(&to).await);
138 res!(want(s2 == 302 && back.starts_with(&lb.redirect()), &fmt!("the server sends back: {} {}", s2, back)));
139 get(&back).await.map(|_| ())
140 };
141 let (code, went) = tokio::join!(lb.code(&at, &state, "Signed in.", Duration::from_secs(5)), browser);
142 res!(went);
143 let code = res!(code);
144 res!(want(code == "K1", &fmt!("code {}", code)));
145 let bad = oauth::exchange(&meta.token, &client, "WRONG", &pkce.verifier, &lb.redirect(), &meta.resource, &b).await;
146 res!(want(matches!(&bad, Err(e) if e.to_string().contains("invalid_grant, bad code") && !e.to_string().contains("S3CRET")),
147 &fmt!("a refused exchange: {:?}", bad.map(|_| ()))));
148 let t = res!(oauth::exchange(&meta.token, &client, &code, &pkce.verifier, &lb.redirect(), &meta.resource, &b).await);
149 res!(want(t.access == "A1" && t.refresh == "R1" && t.expires > oauth::now() + 3000, &fmt!("{:?}", t)));
150 res!(want(lock_mutex!(seen).resource == mcp, "the resource was named"));
151 let g = Grant { url: mcp.clone(), token_url: meta.token.clone(), resource: meta.resource.clone(), client, tokens: t };
152 let r = res!(oauth::refresh(&g, &b).await);
153 want(r.access == "A2" && r.refresh == "R1" && r.expires > 0, &fmt!("refreshed: {:?}", r))
154}
155
156async fn bare() -> Outcome<()> {
157 let l = res!(TcpListener::bind("127.0.0.1:0").await);
158 let port = res!(l.local_addr()).port();
159 tokio::spawn(serve(l, port, Arc::new(Mutex::new(Seen::default()))));
160 let meta = res!(oauth::discover(&fmt!("http://127.0.0.1:{}/bare", port), &bounds()).await);
161 want(meta.authorize == fmt!("http://127.0.0.1:{}/authorize", port) && meta.register.ends_with(":{}/register".replace("{}",
162 &port.to_string()).as_str()), &fmt!("{:?}", meta))
163}
164
165// A GET's status and Location.
166async fn get(url: &str) -> Outcome<(u16, String)> {
167 let u = res!(Url::parse(url));
168 let r = res!(url_request(&u, HttpMethod::GET, &u.target, &[], &[], None, None, Duration::from_secs(5)).await);
169 let status = match &r.header.headline {
170 oxedyne_fe2o3_net::http::header::HttpHeadline::Response { status } => status.clone() as u16,
171 _ => 0,
172 };
173 Ok((status, r.header.fields.get_one(&HeaderName::Location).map(|v| v.to_string()).unwrap_or_default()))
174}
175
176async fn serve(l: TcpListener, port: u16, seen: Arc<Mutex<Seen>>) {
177 while let Ok((c, _)) = l.accept().await {
178 tokio::spawn(one(c, port, seen.clone()));
179 }
180}
181
182async fn one(mut c: TcpStream, port: u16, seen: Arc<Mutex<Seen>>) {
183 let (mut got, mut buf) = (Vec::new(), [0u8; 4096]);
184 let (head, body) = loop {
185 match c.read(&mut buf).await {
186 Ok(0) | Err(_) => return,
187 Ok(n) => got.extend_from_slice(&buf[..n]),
188 }
189 if let Some(at) = got.windows(4).position(|w| w == b"\r\n\r\n") {
190 let head = String::from_utf8_lossy(&got[..at]).to_string();
191 let len = head.to_ascii_lowercase().lines().find_map(|l| l.strip_prefix("content-length:").map(|v| v.trim().to_string()))
192 .and_then(|v| v.parse::<usize>().ok()).unwrap_or(0);
193 if got.len() >= at + 4 + len {
194 break (head, String::from_utf8_lossy(&got[at + 4..at + 4 + len]).to_string());
195 }
196 }
197 };
198 let line = head.lines().next().unwrap_or("").to_string();
199 let mut w = line.split(' ');
200 let (method, target) = (w.next().unwrap_or(""), w.next().unwrap_or(""));
201 let (path, query) = target.split_once('?').unwrap_or((target, ""));
202 let base = fmt!("http://127.0.0.1:{}", port);
203 let json = |code: &str, j: String| fmt!("HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\
204 Connection: close\r\n\r\n{}", code, j.len(), j);
205 let field = |q: &str, k: &str| pct::form(q.as_bytes()).unwrap_or_default().into_iter().find(|(n, _)| n == k)
206 .map(|(_, v)| v).unwrap_or_default();
207 let out = match (method, path) {
208 ("POST", "/mcp") => fmt!("HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Bearer error=\"invalid_token\", \
209 resource_metadata=\"{}/.well-known/oauth-protected-resource/mcp\", scope=\"mcp:tools\"\r\nContent-Length: 0\r\n\
210 Connection: close\r\n\r\n", base),
211 ("POST", "/bare") => fmt!("HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"),
212 ("GET", "/.well-known/oauth-protected-resource/mcp") => json("200 OK", fmt!("{{\"resource\":\"{}/mcp\",\
213 \"authorization_servers\":[\"{}/as\"],\"scopes_supported\":[\"mcp:tools\"]}}", base, base)),
214 ("GET", "/.well-known/oauth-authorization-server/as") => json("200 OK", fmt!("{{\"issuer\":\"{b}/as\",\
215 \"authorization_endpoint\":\"{b}/as/authorize\",\"token_endpoint\":\"{b}/as/token\",\
216 \"registration_endpoint\":\"{b}/as/register\",\"code_challenge_methods_supported\":[\"S256\"]}}", b = base)),
217 ("POST", "/as/register") => json("201 Created", fmt!("{{\"client_id\":\"cl-1\",\"redirect_uris\":[]}}")),
218 ("GET", "/as/authorize") => {
219 if let Ok(mut s) = seen.lock() {
220 (s.challenge, s.resource) = (field(query, "code_challenge"), field(query, "resource"));
221 }
222 fmt!("HTTP/1.1 302 Found\r\nLocation: {}?code=K1&state={}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
223 field(query, "redirect_uri"), pct::encode_component(&field(query, "state")))
224 },
225 ("POST", "/as/token") => {
226 let want = seen.lock().map(|s| s.challenge.clone()).unwrap_or_default();
227 let proved = base64::encode_url(&sha256::digest(field(&body, "code_verifier").as_bytes())) == want;
228 match (field(&body, "grant_type").as_str(), field(&body, "code").as_str(), field(&body, "refresh_token").as_str()) {
229 ("authorization_code", "K1", _) if proved && field(&body, "client_id") == "cl-1"
230 => json("200 OK", fmt!("{{\"access_token\":\"A1\",\"token_type\":\"Bearer\",\"expires_in\":3600,\
231 \"refresh_token\":\"R1\"}}")),
232 ("refresh_token", _, "R1") => json("200 OK", fmt!("{{\"access_token\":\"A2\",\"token_type\":\"bearer\",\
233 \"expires_in\":60}}")),
234 _ => json("400 Bad Request", fmt!("{{\"error\":\"invalid_grant\",\
235 \"error_description\":\"bad code\",\"echo\":\"S3CRET\"}}")),
236 }
237 },
238 _ => fmt!("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"),
239 };
240 let _ = c.write_all(out.as_bytes()).await;
241}