stackure 1.20261013.90

Stackure for Rust: passwordless auth for B2B apps as tower middleware for axum, tonic and hyper.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! HTTP layer for the Stackure SDK, built directly on hyper.

use std::env;
use std::sync::OnceLock;
use std::time::Duration;

use bytes::Bytes;
use http::request::Parts;
use http::{HeaderMap, HeaderValue, Method, Request};
use http_body_util::{BodyExt, Full};
use hyper_rustls::HttpsConnector;
use hyper_util::client::legacy::Client;
use hyper_util::client::legacy::connect::HttpConnector;
use hyper_util::rt::TokioExecutor;

use crate::errors::StackureError;
use crate::types::{
    DirectoryOptions, DirectoryPage, DirectoryUser, MagicLinkResponse, Session, Team, User,
};
use crate::validation::{is_uuid, validate_email, validate_uuid};

const DEFAULT_BASE_URL: &str = "https://stackure.com";
const REQUEST_TIMEOUT: Duration = Duration::from_secs(2);
const MAX_RETRIES: u32 = 1;
const RETRY_DELAY: Duration = Duration::from_millis(500);

/// Name of the session cookie the SDK reads and writes.
pub const SESSION_COOKIE: &str = "session";
/// Name of the sign-in handoff parameter Stackure sends back.
pub const TOKEN_PARAM: &str = "session_token";

/// Resolve `STACKURE_BASE_URL` from the environment, else production.
#[must_use]
pub fn base_url() -> String {
    env::var("STACKURE_BASE_URL")
        .ok()
        .filter(|v| !v.is_empty())
        .map_or_else(
            || DEFAULT_BASE_URL.to_string(),
            |v| v.trim_end_matches('/').to_string(),
        )
}

fn app_secret() -> Result<String, StackureError> {
    env::var("STACKURE_APP_SECRET")
        .ok()
        .filter(|v| !v.is_empty())
        .ok_or_else(|| StackureError::Validation("STACKURE_APP_SECRET is not set".into()))
}

fn app_id() -> Result<String, StackureError> {
    let v = env::var("STACKURE_APP_ID")
        .ok()
        .filter(|v| !v.is_empty())
        .ok_or_else(|| StackureError::Validation("STACKURE_APP_ID is not set".into()))?;
    validate_uuid(&v, "STACKURE_APP_ID")?;
    Ok(v)
}

pub(crate) fn origin() -> String {
    base_url()
        .parse::<http::Uri>()
        .ok()
        .and_then(|u| Some(format!("{}://{}", u.scheme_str()?, u.authority()?)))
        .unwrap_or_default()
}

type HttpsClient = Client<HttpsConnector<HttpConnector>, Full<Bytes>>;

fn client() -> Result<&'static HttpsClient, StackureError> {
    static CLIENT: OnceLock<Result<HttpsClient, String>> = OnceLock::new();
    CLIENT
        .get_or_init(|| {
            let https = hyper_rustls::HttpsConnectorBuilder::new()
                .with_native_roots()
                .map_err(|e| format!("no native root certificates found: {e}"))?
                .https_or_http()
                .enable_http1()
                .build();
            Ok(Client::builder(TokioExecutor::new()).build(https))
        })
        .as_ref()
        .map_err(|e| StackureError::Network(e.clone()))
}

#[derive(Default)]
struct CallOpts<'a> {
    body: Option<Vec<u8>>,
    query: Option<String>,
    token: &'a str,
    bearer: &'a str,
    with_secret: bool,
    status_only: bool,
    ua: &'a str,
    ip: &'a str,
}

async fn send_once(
    client: &HttpsClient,
    method: &Method,
    url: &str,
    o: &CallOpts<'_>,
    secret: &str,
) -> Result<(u16, HeaderMap, Bytes), StackureError> {
    let mut builder = Request::builder().method(method).uri(url);
    if o.body.is_some() {
        builder = builder.header("content-type", "application/json");
    } else if method == Method::POST {
        builder = builder.header("content-length", "0");
    }
    if !secret.is_empty() {
        builder = builder.header("x-app-secret", secret);
    }

    let cookie = if o.token.is_empty() {
        String::new()
    } else {
        format!("{SESSION_COOKIE}={}", o.token)
    };
    let bearer = if o.bearer.is_empty() {
        String::new()
    } else {
        format!("Bearer {}", o.bearer)
    };
    for (name, value) in [
        ("authorization", bearer.as_str()),
        ("user-agent", o.ua),
        ("x-forwarded-for", o.ip),
        ("cookie", cookie.as_str()),
    ] {
        if let Some(Ok(v)) = (!value.is_empty()).then(|| HeaderValue::from_str(value)) {
            builder = builder.header(name, v);
        }
    }

    let body = Full::new(Bytes::from(o.body.clone().unwrap_or_default()));
    let req = builder
        .body(body)
        .map_err(|e| StackureError::Network(format!("failed to create request: {e}")))?;

    let response = client
        .request(req)
        .await
        .map_err(|e| StackureError::Network(format!("network request failed: {e}")))?;

    let status = response.status().as_u16();
    let headers = response.headers().clone();
    if o.status_only {
        return Ok((status, headers, Bytes::new()));
    }
    let bytes = response
        .into_body()
        .collect()
        .await
        .map_err(|_| StackureError::Network("failed to read response body".into()))?
        .to_bytes();
    Ok((status, headers, bytes))
}

async fn send(
    method: &Method,
    path: &str,
    o: &CallOpts<'_>,
) -> Result<(HeaderMap, Bytes), StackureError> {
    let deadline = tokio::time::Instant::now() + REQUEST_TIMEOUT;
    let secret = if o.bearer.is_empty() || o.with_secret {
        app_secret()?
    } else {
        String::new()
    };
    let client = client()?;
    let url = match &o.query {
        Some(q) => format!("{}{path}?{q}", base_url()),
        None => format!("{}{path}", base_url()),
    };

    let mut attempt = 0;
    loop {
        let res = tokio::time::timeout_at(deadline, send_once(client, method, &url, o, &secret))
            .await
            .map_err(|_| {
                StackureError::Timeout(format!(
                    "request timed out after {}s",
                    REQUEST_TIMEOUT.as_secs()
                ))
            })?;
        let retry = attempt < MAX_RETRIES
            && deadline.saturating_duration_since(tokio::time::Instant::now()) > RETRY_DELAY;
        match res {
            Ok((status, headers, bytes)) if status < 500 || !retry => {
                return check_status(status, &bytes).map(|()| (headers, bytes));
            }
            Err(e) if !retry => return Err(e),
            _ => {}
        }
        attempt += 1;
        tokio::time::sleep(RETRY_DELAY).await;
    }
}

async fn request(
    method: &Method,
    path: &str,
    o: CallOpts<'_>,
) -> Result<serde_json::Value, StackureError> {
    let (_, bytes) = send(method, path, &o).await?;
    json(&bytes)
}

fn json(bytes: &[u8]) -> Result<serde_json::Value, StackureError> {
    serde_json::from_str(&String::from_utf8_lossy(bytes))
        .map_err(|_| StackureError::Network("invalid JSON response from server".into()))
}

fn check_status(status: u16, bytes: &[u8]) -> Result<(), StackureError> {
    if (200..300).contains(&status) {
        return Ok(());
    }
    let text = String::from_utf8_lossy(bytes);
    let body = if text.is_empty() {
        "unknown error"
    } else {
        &text
    };
    Err(match status {
        401 => StackureError::Auth(body.to_string()),
        403 => StackureError::Forbidden(body.to_string()),
        _ => StackureError::Network(format!("api error ({status}): {body}")),
    })
}

/// The client's address: first `X-Forwarded-For` entry, else the peer address.
///
/// The peer address is read from axum's `ConnectInfo<SocketAddr>` (with the
/// default `axum` feature) or from a bare `SocketAddr` in the request
/// extensions. Behind a proxy, `X-Forwarded-For` is what matters.
#[must_use]
pub fn client_ip(parts: &Parts) -> String {
    let forwarded = parts
        .headers
        .get("x-forwarded-for")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.split(',').next())
        .map(str::trim)
        .filter(|first| !first.is_empty());
    if let Some(first) = forwarded {
        return first.to_string();
    }
    peer_addr(parts).map_or_else(String::new, |a| a.ip().to_string())
}

#[cfg(feature = "axum")]
fn peer_addr(parts: &Parts) -> Option<std::net::SocketAddr> {
    parts
        .extensions
        .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
        .map(|info| info.0)
        .or_else(|| parts.extensions.get::<std::net::SocketAddr>().copied())
}

#[cfg(not(feature = "axum"))]
fn peer_addr(parts: &Parts) -> Option<std::net::SocketAddr> {
    parts.extensions.get::<std::net::SocketAddr>().copied()
}

/// Read a single cookie off the request, or `""` if absent.
#[must_use]
pub fn cookie(parts: &Parts, name: &str) -> String {
    parts
        .headers
        .get("cookie")
        .and_then(|v| v.to_str().ok())
        .unwrap_or_default()
        .split(';')
        .find_map(|part| {
            let (key, value) = part.split_once('=')?;
            (key.trim() == name).then(|| value.trim().trim_matches('"').to_string())
        })
        .unwrap_or_default()
}

fn bearer(parts: &Parts) -> &str {
    parts
        .headers
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.split_once(' '))
        .filter(|(scheme, _)| scheme.eq_ignore_ascii_case("bearer"))
        .map(|(_, token)| token.trim())
        .filter(|token| is_uuid(token))
        .unwrap_or_default()
}

/// Read `name` out of an `application/x-www-form-urlencoded` string.
#[must_use]
pub fn form_value(encoded: &str, name: &str) -> String {
    encoded
        .split('&')
        .find_map(|pair| {
            let (key, value) = pair.split_once('=')?;
            (percent_decode(key) == name).then(|| percent_decode(value))
        })
        .unwrap_or_default()
}

fn percent_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'+' => {
                out.push(b' ');
                i += 1;
            }
            b'%' if i + 2 < bytes.len() => {
                let decoded = std::str::from_utf8(&bytes[i + 1..i + 3])
                    .ok()
                    .and_then(|h| u8::from_str_radix(h, 16).ok());
                if let Some(b) = decoded {
                    out.push(b);
                    i += 3;
                } else {
                    out.push(bytes[i]);
                    i += 1;
                }
            }
            b => {
                out.push(b);
                i += 1;
            }
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

fn percent_encode(s: &str) -> String {
    use std::fmt::Write as _;
    s.bytes().fold(String::new(), |mut out, b| {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
            out.push(char::from(b));
        } else {
            let _ = write!(out, "%{b:02X}");
        }
        out
    })
}

/// Send a passwordless sign-in email for the app in `STACKURE_APP_ID`.
///
/// # Errors
///
/// Returns [`StackureError`] on invalid input, or any transport or API failure.
pub async fn send_magic_link(email: &str) -> Result<MagicLinkResponse, StackureError> {
    validate_email(email)?;
    let body = serde_json::json!({ "user_email": email, "app_id": app_id()? });

    let data = request(
        &Method::POST,
        "/api/public/auth/magic-link/send",
        CallOpts {
            body: Some(serde_json::to_vec(&body).unwrap_or_default()),
            ..CallOpts::default()
        },
    )
    .await?;

    serde_json::from_value(data)
        .map_err(|_| StackureError::Network("unexpected API response format".into()))
}

/// Validate the request's session against Stackure.
///
/// A request without a well-formed session token gets the sign-in URL
/// without a Stackure call.
///
/// Most callers want [`crate::verify`] or [`crate::auth`].
///
/// # Errors
///
/// Returns [`StackureError`] on invalid input, or any transport or API failure.
pub async fn validate_session(parts: &Parts) -> Result<Session, StackureError> {
    validate_token(&cookie(parts, SESSION_COOKIE), parts).await
}

/// Validate an explicit session `token` for the browser that sent `parts`.
///
/// # Errors
///
/// Returns [`StackureError`] on invalid input, or any transport or API failure.
pub async fn validate_token(token: &str, parts: &Parts) -> Result<Session, StackureError> {
    let app_id = app_id()?;

    if !is_uuid(token) {
        return Ok(Session {
            sign_in_url: format!("{}/sign-in/magic-link?app_id={app_id}", base_url()),
            ..Session::default()
        });
    }

    get_with_session(
        "/api/public/auth/session/validate",
        format!("app_id={app_id}"),
        token,
        parts,
    )
    .await
    .map(|(_, session)| session)
}

/// List the users in the caller's Stackure organization who can open the
/// app, one page at a time, for pickers and sharing.
///
/// Authenticated by the request's session cookie, so call it from a route
/// behind [`crate::auth`]; MCP bearer tokens are not accepted. A request
/// without a well-formed session token gets [`StackureError::Auth`] without a
/// Stackure call.
///
/// # Example
///
/// ```no_run
/// # async fn example(parts: &http::request::Parts) -> Result<(), stackure::StackureError> {
/// let mut opts = stackure::DirectoryOptions {
///     query: Some("ada".into()),
///     ..Default::default()
/// };
/// loop {
///     let page = stackure::directory_users(parts, &opts).await?;
///     for user in &page.items {
///         println!("{}", user.user_email);
///     }
///     let Some(next) = page.next_cursor else { break };
///     opts.cursor = Some(next);
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns [`StackureError::Auth`] when there is no valid session or the app
/// secret is wrong, or any other [`StackureError`] on invalid input or a
/// transport or API failure.
pub async fn directory_users(
    parts: &Parts,
    opts: &DirectoryOptions,
) -> Result<DirectoryPage<DirectoryUser>, StackureError> {
    directory("/api/public/directory/users", parts, opts).await
}

/// List the teams in the caller's Stackure organization that have the app,
/// one page at a time: every team when the app is available to everyone,
/// otherwise the teams it's shared with.
///
/// Authenticated like [`directory_users`].
///
/// # Example
///
/// ```no_run
/// # async fn example(parts: &http::request::Parts) -> Result<(), stackure::StackureError> {
/// let opts = stackure::DirectoryOptions {
///     limit: Some(50),
///     ..Default::default()
/// };
/// let page = stackure::directory_teams(parts, &opts).await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Same as [`directory_users`].
pub async fn directory_teams(
    parts: &Parts,
    opts: &DirectoryOptions,
) -> Result<DirectoryPage<Team>, StackureError> {
    directory("/api/public/directory/teams", parts, opts).await
}

async fn directory<T: serde::de::DeserializeOwned>(
    path: &str,
    parts: &Parts,
    o: &DirectoryOptions,
) -> Result<DirectoryPage<T>, StackureError> {
    use std::fmt::Write as _;
    let mut query = format!("app_id={}", app_id()?);
    let token = cookie(parts, SESSION_COOKIE);
    if !is_uuid(&token) {
        return Err(StackureError::Auth("invalid session".into()));
    }
    for (name, value) in [("q", &o.query), ("cursor", &o.cursor)] {
        if let Some(v) = value.as_deref().filter(|v| !v.is_empty()) {
            let _ = write!(query, "&{name}={}", percent_encode(v));
        }
    }
    if let Some(n) = o.limit {
        let _ = write!(query, "&limit={n}");
    }
    for id in &o.ids {
        let _ = write!(query, "&id={}", percent_encode(id));
    }

    let (headers, items) = get_with_session(path, query, &token, parts).await?;
    let header = |name| {
        headers
            .get(name)
            .and_then(|v: &HeaderValue| v.to_str().ok())
    };
    Ok(DirectoryPage {
        items,
        next_cursor: header("x-next-cursor")
            .filter(|v| !v.is_empty())
            .map(String::from),
        total: header("x-total-count").and_then(|v| v.parse().ok()),
    })
}

async fn get_with_session<T: serde::de::DeserializeOwned>(
    path: &str,
    query: String,
    token: &str,
    parts: &Parts,
) -> Result<(HeaderMap, T), StackureError> {
    let (headers, bytes) = send(
        &Method::GET,
        path,
        &CallOpts {
            query: Some(query),
            token,
            ua: parts
                .headers
                .get("user-agent")
                .and_then(|v| v.to_str().ok())
                .unwrap_or_default(),
            ip: &client_ip(parts),
            ..CallOpts::default()
        },
    )
    .await?;

    serde_json::from_value(json(&bytes)?)
        .map(|data| (headers, data))
        .map_err(|_| StackureError::Network("unexpected API response format".into()))
}

#[derive(Default, serde::Deserialize)]
#[serde(default)]
pub(crate) struct McpSession {
    pub(crate) authenticated: bool,
    pub(crate) user: Option<User>,
    pub(crate) www_authenticate: String,
}

/// Validate an MCP request's `Authorization: Bearer` credential against
/// Stackure, for the MCP endpoint at the public URL `url`.
///
/// The call is made with or without a well-formed credential, so a caller who
/// is not signed in always gets the `WWW-Authenticate` challenge. Cookies are
/// never sent.
pub(crate) async fn validate_mcp(url: &str, parts: &Parts) -> Result<McpSession, StackureError> {
    let app_id = app_id()?;

    let data = request(
        &Method::GET,
        "/api/public/auth/session/validate",
        CallOpts {
            query: Some(format!("app_id={app_id}&mcp={}", percent_encode(url))),
            bearer: bearer(parts),
            with_secret: true,
            ua: parts
                .headers
                .get("user-agent")
                .and_then(|v| v.to_str().ok())
                .unwrap_or_default(),
            ip: &client_ip(parts),
            ..CallOpts::default()
        },
    )
    .await?;

    serde_json::from_value(data)
        .map_err(|_| StackureError::Network("unexpected API response format".into()))
}

/// End the access of the user behind the request's session token, everywhere.
///
/// A request without a well-formed session token returns `Ok` without a
/// Stackure call. A 2xx status alone is success: the response body is never
/// read. The call runs on its own task, so it completes even if the caller is
/// dropped while it is in flight.
pub(crate) async fn sign_out(parts: &Parts) -> Result<(), StackureError> {
    let token = cookie(parts, SESSION_COOKIE);
    if !is_uuid(&token) {
        return Ok(());
    }
    let ua = parts
        .headers
        .get("user-agent")
        .and_then(|v| v.to_str().ok())
        .unwrap_or_default()
        .to_string();
    let ip = client_ip(parts);

    tokio::spawn(async move {
        send(
            &Method::POST,
            "/api/public/auth/sign-out",
            &CallOpts {
                bearer: &token,
                status_only: true,
                ua: &ua,
                ip: &ip,
                ..CallOpts::default()
            },
        )
        .await
        .map(drop)
    })
    .await
    .unwrap_or_else(|e| Err(StackureError::Network(format!("sign-out task failed: {e}"))))
}