sputnik 0.1.1

A lightweight layer on top of hyper to facilitate building web applications.
Documentation

Sputnik

A lightweight layer on top of Hyper to facilitate building web applications.

Sputnik provides:

  • convenience wrappers around hyper's Request & Response
    • parse, set and delete cookies (powered by the cookie crate)
    • parse query strings and HTML form data (powered by the serde_urlencoded crate)
  • cookie-based CSRF tokens
  • Key: a convenience wrapper around HMAC (stolen from the cookie crate, so that you don't have to use CookieJars if you don't need them)
  • decode_expiring_claim & encode_expiring_claim, which can be combined with Key to implement signed & expiring cookies (with the expiry date encoded into the signed cookie value)

Sputnik does not:

  • handle routing: for most web apps matching on (method, path) suffices
  • handle configuration: we recommend toml
  • handle persistence: we recommend diesel
  • handle templating: we recommend maud

CsrfToken example

use std::convert::Infallible;
use hyper::service::{service_fn, make_service_fn};
use hyper::{Method, Server};
use serde::Deserialize;
use sputnik::security::CsrfToken;
use sputnik::{Request, Response, Error};

async fn route(req: &mut Request) -> Result<Response,Error> {
    match (req.method(), req.uri().path()) {
        (&Method::GET, "/form") => get_form(req).await,
        (&Method::POST, "/form") => post_form(req).await,
        _ => return Err(Error::not_found("page not found".to_owned()))
    }
}

async fn get_form(req: &mut Request) -> Result<Response, Error> {
    let mut response = Response::new();
    let csrf_token = CsrfToken::from_request(req, &mut response);
    *response.body() = format!("<form method=post>
        <input name=text>{}<button>Submit</button></form>", csrf_token.html_input()).into();
    Ok(response)
}

#[derive(Deserialize)]
struct FormData {text: String}

async fn post_form(req: &mut Request) -> Result<Response, Error> {
    let mut response = Response::new();
    let csrf_token = CsrfToken::from_request(req, &mut response);
    let msg: FormData = req.into_form_csrf(&csrf_token).await?;
    *response.body() = format!("hello {}", msg.text).into();
    Ok(response)
}

/// adapt between Hyper's types and Sputnik's convenience types
async fn service(req: hyper::Request<hyper::Body>) -> Result<hyper::Response<hyper::Body>, Infallible> {
    match route(&mut req.into()).await {
        Ok(res) => Ok(res.into()),
        Err(err) => Ok(err.response_builder().body(err.message.into()).unwrap())
        // you can easily wrap or log errors here
    }
}

#[tokio::main]
async fn main() {
    let service = make_service_fn(move |_| {
        async move {
            Ok::<_, hyper::Error>(service_fn(move |req| {
                service(req)
            }))
        }
    });

    let addr = ([127, 0, 0, 1], 8000).into();
    let server = Server::bind(&addr).serve(service);
    println!("Listening on http://{}", addr);
    server.await;
}

Signed & expiring cookies

After a successful authentication you can build a session id cookie for example as follows:

let expiry_date = OffsetDateTime::now_utc() + Duration::hours(24);
let mut cookie = Cookie::new("userid",
    key.sign(
        &encode_expiring_claim(&userid, expiry_date)
    ));
cookie.set_secure(Some(true));
cookie.set_expires(expiry_date);
cookie.set_same_site(SameSite::Lax);
resp.set_cookie(cookie);

This session id cookie can then be retrieved and verified as follows:

let userid = req.cookies().get("userid")
    .ok_or_else(|| Error::unauthorized("expected userid cookie".to_owned()))
    .and_then(|cookie| key.verify(cookie.value()).map_err(Error::unauthorized))
    .and_then(|value| decode_expiring_claim(value).map_err(|e| Error::unauthorized(format!("failed to decode userid cookie: {}", e))))?;

Tip: If you want to store multiple claims in the cookie, you can (de)serialize a struct with serde_json. This approach can pose a lightweight alternative to JWT, if you don't care about the standardization aspect.