moonasgi-mid

    Application-level middleware (CORS, Gzip, rate limit, session, auth) for moonbitstack/moonasgi.

    asgi
    middleware
    cors
    gzip
    ratelimit
    session
    moonbit
    Download zip
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    42 minutes ago
    Downloads
    31

    #moonasgi-mid

    Application-level middleware (Layer, Cors, Gzip, RateLimit, Quota, Session, Auth) for moonbitstack/moonasgi.

    Backend

    pub(open) trait Backend {
    fn authenticate(Self,
    Scope
    ) -> Identity
    }

    A backend answers one question: who is behind this connection? It sees the whole scope, so it can read the session, a bearer token, a client certificate or the peer address, in whatever order the service prefers.

    Layer

    Something that wraps one ASGI application in another: CORS, compression, a host check, or the caller's own. Every middleware here is a record that implements it, so a caller's middleware stacks with them on equal terms.

    Auth

    pub(all) struct Auth {
    backend : &Backend
    }

    Resolve the identity of every connection and put it on the scope, under user and auth, before the application runs. A connection the backend could not identify carries null there rather than nothing at all, so a handler can tell "this service identified nobody" from "this service has no auth layer".

    The layer sees the scope the layers outside it built, so a session written by Sessions is readable here when Sessions wraps Auth.

    Auth::new

    fn Auth::new(backend : &Backend) -> Auth

    Build an Auth layer around backend.

    BackendFn

    pub(all) struct BackendFn((
    Scope
    ) -> Identity)

    A backend written as a plain function, for a service whose rule fits on a line or two: BackendFn(fn(scope) { ... }) is a Backend with no type to declare.

    BackendFn::authenticate

    BodyLimit

    pub(all) struct BodyLimit {
    limit : Int
    } derive(Eq,
    Debug
    )

    A ceiling on a request body. A Content-Length above it is answered 413 at once, without calling the application. A body that grows past it while the application reads it is answered 413 too, when no response has started; the application then reads a disconnect, and what it sends afterwards is dropped, since the client already has its answer.

    BodyLimit::equal

    fn BodyLimit::equal(BodyLimit, BodyLimit) -> Bool
    automatically derived

    BodyLimit::new

    fn BodyLimit::new(limit? : Int) -> BodyLimit

    BodyLimit::not_equal

    fn BodyLimit::not_equal(x : BodyLimit, y : BodyLimit) -> Bool
    automatically derived

    BodyLimit::to_repr

    automatically derived

    Cors

    pub(all) struct Cors {
    origins : Array[String]
    origin_regex : String?
    methods : Array[String]
    headers : Array[String]
    credentials : Bool
    expose : Array[String]
    max_age : Int
    } derive(Eq,
    Debug
    )

    Cross-origin resource sharing, per the Fetch standard §3.2.

    origins, methods and headers are allow-lists, and "*" in one allows anything. A preflight is answered here: 200 with the negotiated headers, or 400 naming what was refused. Other cross-origin responses get access-control-allow-origin when the origin is allowed. With credentials the origin is echoed rather than *, as the standard requires.

    origin_regex is for a site that cannot list its origins: a staging host per branch, a tenant per customer. It is matched whole against the Origin header, after the list, so a listed origin is answered without the expression being compiled.

    Cors::equal

    fn Cors::equal(Cors, Cors) -> Bool
    automatically derived

    Cors::new

    fn Cors::new(origins? : Array[String], origin_regex? : String, methods? : Array[String], headers? : Array[String], credentials? : Bool, expose? : Array[String], max_age? : Int) -> Cors

    Cors::not_equal

    fn Cors::not_equal(x : Cors, y : Cors) -> Bool
    automatically derived

    Cors::to_repr

    automatically derived

    Gzip

    pub(all) struct Gzip {
    minimum : Int
    level : Int
    } derive(Eq,
    Debug
    )

    Gzip for responses a client accepts it for: a body of at least minimum octets, sent in one message, not already content-encoded. level is the zlib effort, 0 to 9.

    A body sent in several messages is passed through as it comes: compressing it would hold it back until the end, and a stream is sent in pieces so that it is not held back. An event stream is never compressed, for the same reason.

    Gzip::equal

    fn Gzip::equal(Gzip, Gzip) -> Bool
    automatically derived

    Gzip::new

    fn Gzip::new(minimum? : Int, level? : Int) -> Gzip

    Gzip::not_equal

    fn Gzip::not_equal(x : Gzip, y : Gzip) -> Bool
    automatically derived

    Gzip::to_repr

    automatically derived

    HttpsRedirect

    pub(all) struct HttpsRedirect {
    } derive(Eq,
    Debug
    )

    Send every plain request to its secure equivalent: http to https and ws to wss, with a 307 so the method and body are kept. Port 80 or 443 in the host is dropped; any other port stays.

    HttpsRedirect::equal

    automatically derived

    HttpsRedirect::new

    HttpsRedirect::not_equal

    fn HttpsRedirect::not_equal(x : HttpsRedirect, y : HttpsRedirect) -> Bool
    automatically derived

    HttpsRedirect::to_repr

    automatically derived

    Identity

    What a backend found for one connection: the user it identified, and the auth record the decision was made from (a token's claims, a role list, a tenant). Both are None when the connection carried nothing to go on.

    JSON rather than a record because the seam cannot know what a service's user looks like; a framework that wants a typed user reads it back out of the scope with user and decodes it into its own type.

    Identity::anonymous

    fn Identity::anonymous() -> Identity

    An identity with nothing in it: the answer for a connection that carried no credentials.

    Identity::equal

    fn Identity::equal(Identity, Identity) -> Bool
    automatically derived

    Identity::not_equal

    fn Identity::not_equal(x : Identity, y : Identity) -> Bool
    automatically derived

    Identity::of

    An identity for user, with no record of how it was reached.

    Identity::to_repr

    automatically derived

    ProxyHeaders

    pub(all) struct ProxyHeaders {
    trusted : Array[String]
    } derive(Eq,
    Debug
    )

    The client and scheme a reverse proxy saw, put back in the scope, by X-Forwarded-For / X-Forwarded-Proto or by RFC 7239's Forwarded. Only a request from an address in trusted is rewritten, since anyone else could claim any address; "*" trusts every peer.

    X-Forwarded-For gives the client: the rightmost address that is not trusted, every proxy before it having appended its own; when all are trusted, the leftmost. X-Forwarded-Proto gives the scheme, http or https (ws or wss for a WebSocket). Without either header, the Forwarded header is read the same way through its for and proto.

    ProxyHeaders::equal

    automatically derived

    ProxyHeaders::new

    fn ProxyHeaders::new(trusted? : Array[String]) -> ProxyHeaders

    ProxyHeaders::not_equal

    fn ProxyHeaders::not_equal(x : ProxyHeaders, y : ProxyHeaders) -> Bool
    automatically derived

    ProxyHeaders::to_repr

    automatically derived

    RateLimit

    pub(all) struct RateLimit {
    rate : Double
    burst : Double
    clients : Int
    key : (
    Scope
    ) -> String?
    clock : () -> Int64
    headers : Bool
    name : String
    }

    Requests per client, as a token bucket: rate a second on average, with bursts of up to burst after a quiet spell. A request that finds its client's bucket empty is answered 429 with Retry-After, without calling the application. WebSocket and lifespan scopes pass through.

    Behind a proxy every request arrives from the proxy's address; put ProxyHeaders outside this layer so that key reads the client's own.

    With headers the answer also carries RateLimit-Policy and RateLimit (draft-ietf-httpapi-ratelimit-headers): the quota the policy grants, and what is left of it after this request. Both are off by default, because they cost a header pair on every response and name a policy the caller may not want published.

    RateLimit::new

    fn RateLimit::new(rate? : Double, burst? : Double, clients? : Int, key? : (
    Scope
    ) -> String?, clock? : () -> Int64, headers? : Bool, name? : String) -> RateLimit

    RateLimitPolicy

    pub(all) struct RateLimitPolicy {
    name : String
    quota : Int64
    window : Int64?
    unit : String?
    key : Bytes?
    extra : Array[String]
    } derive(Eq,
    Debug
    )

    A quota policy, as one item of a RateLimit-Policy field (draft-ietf-httpapi-ratelimit-headers §3.1): the name that identifies the policy, the quota it grants, and the window it grants it over, the unit the quota counts in, the partition key it is allocated to, and any parameters the specification does not define.

    window is in seconds, and None states a quota with no time limit. unit is None for the default, requests; the other units are "content-bytes" and "concurrent-requests".

    RateLimitPolicy::encode

    fn RateLimitPolicy::encode(self : RateLimitPolicy) -> String

    The item as the field writes it: "default";q=100;w=10, with qu before w and pk last, the order the specification declares its parameters in.

    RateLimitPolicy::equal

    automatically derived

    RateLimitPolicy::not_equal

    fn RateLimitPolicy::not_equal(x : RateLimitPolicy, y : RateLimitPolicy) -> Bool
    automatically derived

    RateLimitPolicy::to_repr

    automatically derived

    ServerErrors

    pub(all) struct ServerErrors {
    debug : Bool
    handler : (Error) -> (Int, Array[(String, String)], String)?
    }

    What an application's failure becomes: a 500 when the response has not started, then the error raised on to the server, which logs it. debug puts the error in the body. handler writes the answer instead: (status, headers, body) for the error.

    ServerErrors::new

    fn ServerErrors::new(debug? : Bool, handler? : (Error) -> (Int, Array[(String, String)], String)) -> ServerErrors

    ServiceLimit

    pub(all) struct ServiceLimit {
    name : String
    remaining : Int64
    window : Int64?
    key : Bytes?
    extra : Array[String]
    } derive(Eq,
    Debug
    )

    What is left of a quota, as one item of a RateLimit field (draft-ietf-httpapi-ratelimit-headers §4.1): the name of the policy it belongs to, the remaining quota, the window within which no more than that may be used, the partition key, and any parameters the specification does not define.

    window is in seconds, and None states a quota that is not time limited. A client reads remaining as what it may still send, and window as how long that holds: it says nothing about what comes after, which the server may change between requests.

    ServiceLimit::encode

    fn ServiceLimit::encode(self : ServiceLimit) -> String

    The item as the field writes it: "default";r=50;t=30, with pk last.

    ServiceLimit::equal

    automatically derived

    ServiceLimit::not_equal

    fn ServiceLimit::not_equal(x : ServiceLimit, y : ServiceLimit) -> Bool
    automatically derived

    ServiceLimit::to_repr

    automatically derived

    Sessions

    pub(all) struct Sessions {
    secret : Bytes
    cookie : String
    max_age : Int?
    path : String
    same_site : String
    https_only : Bool
    domain : String?
    clock : () -> Int64
    }

    Data a client carries across requests, signed so it cannot be edited.

    The session is read off the request's cookie into scope.state, where a handler reads and writes it with session; the response that ends the request carries it back. Nothing is stored on the server, so the secret is the whole of the security: a client that does not have it cannot make a session that verifies, and one that does have it can read every session it ever signed.
    impl Layer for Sessions

    Sessions::new

    fn Sessions::new(secret~ : Bytes, cookie? : String, max_age? : Int?, path? : String, same_site? : String, https_only? : Bool, domain? : String, clock? : () -> Int64) -> Sessions

    Build a Sessions layer around secret.

    The defaults are the ones a web framework ships with: a cookie named session, good for fourteen days, Path=/, SameSite=Lax, not Secure (a server behind TLS that never answers over plain HTTP turns https_only on). clock is the current time in seconds since the epoch, env.now when it is not given; a test passes its own so a signed cookie it built by hand verifies.

    Sessions::wrap

    Read the session out of a request's cookie: the data the cookie carried, or an empty session when there was no cookie, the signature did not verify, the timestamp has aged out, or the payload was not the JSON object this layer wrote. Every one of those is a client that has no session, which is what a request with no cookie has too.

    TrustedHosts

    pub(all) struct TrustedHosts {
    hosts : Array[String]
    www_redirect : Bool
    } derive(Eq,
    Debug
    )

    Only the hosts listed may be asked for: a host header naming another answers 400. *.example.com allows any subdomain, * alone allows any host. With www_redirect, a request for example.com where only www.example.com is listed is sent there.

    TrustedHosts::equal

    automatically derived

    TrustedHosts::new

    fn TrustedHosts::new(hosts? : Array[String], www_redirect? : Bool) -> TrustedHosts

    TrustedHosts::not_equal

    fn TrustedHosts::not_equal(x : TrustedHosts, y : TrustedHosts) -> Bool
    automatically derived

    TrustedHosts::to_repr

    automatically derived

    auth

    The record the identity was decided from, when the backend kept one.

    body_limit

    let body_limit : BodyLimit

    One mebibyte, nginx's client_max_body_size.

    client_address

    fn client_address(scope :
    Scope
    ) -> String?

    The address a request came from: the key rate_limit uses.

    cors

    let cors : Cors

    The defaults: no origin allowed, GET only, the safelisted headers only, no credentials, preflights cached for ten minutes.

    gzip

    let gzip : Gzip

    The defaults: 500 octets and up, the most effort.

    https_redirect

    let https_redirect : HttpsRedirect

    proxy_headers

    let proxy_headers : ProxyHeaders

    The default: only a proxy on the same machine is believed.

    rate_limit

    let rate_limit : RateLimit

    One request every half second with bursts of eight, tower-governor's default; room for 160 000 clients, about what nginx keeps in the 10 MB limit_req_zone its documentation sets up. The quota fields stay off.

    server_errors

    let server_errors : ServerErrors

    The defaults: no detail in the body, the plain 500.

    session

    The session data of a connection, live: a handler that writes to the returned map is writing what the response cookie will carry. A connection with no session, or one whose cookie did not verify, starts empty.

    The map is the one in scope.state, so it survives the hop from a middleware to the application that reads it.

    stack

    app inside layers, wrapped from the last to the first, so the layer given first sees the request first and the response last.

    trusted_hosts

    let trusted_hosts : TrustedHosts

    The defaults: any host, and the redirect to www. on.

    user

    The identity the layer resolved for this connection, or None when nobody was identified — or when no Auth layer ran.