# `Macaw.Live.Proxy`
[🔗](https://github.com/dcoai/macaw_live/blob/v0.1.0/lib/macaw/live/proxy.ex#L1)

The one same-origin asset proxy (spec/06 §1): media a component needs from another
origin, map tiles first, fetched by the host's server so a page under `img-src 'self'`
holds same-origin paths only. Copied from visualize's `Visualize.TileProxy` (D-298) and
made generic: routes are components' declared `proxy_routes` by component, name and
digest, the enabled origins are the host's configuration value, never application
config, and every step is a value.

    proxy = Macaw.Live.Proxy.config!(
      live: MyApp.Macaw,
      origins: %{"https://tile.openstreetmap.org" => []}
    )

    plug Macaw.Live.Proxy.Plug, proxy

**Closed by default:** with no `origins:` every request is refused. An origin is listed
exactly, `<scheme>://<host>[:<port>]`, `https` only, no wildcard; a template whose host
is a placeholder has each filled host listed one by one. **Credentials come from
configuration, never from a document:** only an origin's `headers:` add any.

This module holds the configuration (`config/1`), the steps of a request (`request/4`,
each refusal a status), the upstream answer checked (`answer/4`) and the upstream's
freshness (`freshness/1`). `Macaw.Live.Proxy.Plug` runs them.

# `t`

```elixir
@type t() :: %Macaw.Live.Proxy{
  at: String.t(),
  clock: Macaw.Data.Clock.t(),
  fetcher: {module(), term()},
  live: atom(),
  max_bytes: pos_integer(),
  origins: %{required(String.t()) =&gt; %{headers: [{String.t(), String.t()}]}},
  timeout: pos_integer()
}
```

The proxy's configuration, built once at boot by `config/1`.

# `upstream`

```elixir
@type upstream() :: %{
  url: String.t(),
  origin: String.t(),
  route: Macaw.Component.Proxy.route(),
  headers: [{String.t(), String.t()}],
  method: String.t()
}
```

A request the steps admitted: the filled upstream URL, its route and headers.

# `answer`

```elixir
@spec answer(t(), Macaw.Component.Proxy.route(), term(), non_neg_integer() | nil) ::
  {pos_integer(), [{String.t(), String.t()}], binary()}
```

The upstream's answer checked (spec/06 §1.4): `{status, headers, body}`. An upstream
`200` whose `content-type`, its parameters dropped and lower-cased, is among the
route's declared `types`, with a body of at most `max_bytes`, is `200` with the checked
type, `cache-control` (`public, max-age=<fresh>` from `fresh`, the seconds left, or
`no-store` when `nil`), `x-content-type-options: nosniff` and `content-security-policy:
default-src 'none'; sandbox`. Anything else, another status (a redirect among them),
another type, a body over the cap, or a fetch error or timeout, is `{502, [], ""}`. No
upstream header passes but the checked type.

# `config`

```elixir
@spec config(term()) :: {:ok, t()} | {:error, [Macaw.Base.Fault.t(), ...]}
```

The proxy's configuration (spec/06 §1.1): `{:ok, %Macaw.Live.Proxy{}}`, or every fault
at once. Options: `live:` (required, the supervisor whose asset store holds the routes),
`origins:` (`%{}`, each enabled origin to its options, `headers:` a list of `{name,
value}` strings), `at:` (`"/macaw/proxy"`), `max_bytes:` (1,048,576), `timeout:`
(10,000 ms), `fetcher:` (`{Macaw.Live.Proxy.Fetcher.Httpc, []}`) and `clock:`
(`{Macaw.Data.Clock.System, nil}`, the wall time the cache's freshness is read on, a
`Macaw.Data.Clock.Manual` in a test).

Each origin is lower-cased, its scheme's default port dropped. Faults:
`{[:live], :required}`, `{[:live], {:type, :atom}}`; `{[:origins], {:type, :map}}`;
`{[:origins, entry], :origin}` for an entry that isn't an `https` origin (a path, a
query, a userinfo, a wildcard or placeholder host, another scheme);
`{[:origins, origin], {:type, :keyword}}` and `{[:origins, origin, key], :unknown_key}`
for its options; `{[:origins, origin, :headers, i], {:type, :header}}`; `{[:at], {:type,
:path}}`; `{[key], {:type, :pos_integer}}` for `max_bytes:` or `timeout:`; `{[:fetcher],
{:type, :fetcher}}`; `{[:clock], {:type, :clock}}`; `{[key], :unknown_key}`; `{[], {:type, :keyword}}` for options that
aren't a keyword list.

    iex> {:ok, proxy} = Macaw.Live.Proxy.config(live: MyApp.Macaw, origins: %{"HTTPS://Tiles.Example:443" => []})
    iex> proxy.origins
    %{"https://tiles.example" => %{headers: []}}

# `config!`

```elixir
@spec config!(term()) :: t()
```

`config/1`, raising its faults as an `ArgumentError` for a host at boot.

# `freshness`

```elixir
@spec freshness(term()) :: non_neg_integer() | nil
```

An upstream response's freshness in seconds (spec/06 §1.5), as a shared cache reads it:
`s-maxage`, else `max-age`, else `Expires` less `Date`; `nil` for `no-store`, `private`
or `no-cache`, or with none of these, since the proxy guesses no freshness.

    iex> Macaw.Live.Proxy.freshness([{"cache-control", "public, max-age=60, s-maxage=30"}])
    30
    iex> Macaw.Live.Proxy.freshness([{"cache-control", "private, max-age=60"}])
    nil

# `origin`

```elixir
@spec origin(term()) :: String.t() | nil
```

The URL's origin, `<scheme>://<host>[:<port>]` lower-cased, the port only when it isn't
the scheme's default; `nil` for a URL with no `//` authority, a host that isn't one, or
a userinfo, which no origin the proxy reaches carries.

    iex> Macaw.Live.Proxy.origin("HTTPS://Tiles.Example:8443/0/0/0.png")
    "https://tiles.example:8443"
    iex> Macaw.Live.Proxy.origin("https://user@tiles.example/0.png")
    nil

# `request`

```elixir
@spec request(t(), term(), term(), term()) ::
  {:ok, upstream()} | {:error, 400..405} | :pass
```

The steps of one request below `at` (spec/06 §1.3), in order, each a value:
`{:ok, upstream}` to fetch, `{:error, status}` refused, or `:pass` for a path not below
`at`, which the plug passes on.

  * a method other than `GET` or `HEAD`: `405`;
  * a path not of a component, a route and a digest below `at`: `404`;
  * a route the supervisor's asset store doesn't hold (`Macaw.Live.Assets.route/4`):
    `404`;
  * query names other than exactly the template's placeholders, a value empty, longer
    than 256 bytes or repeated, or a query that isn't one: `400`;
  * the template filled, each value percent-encoded whole so no value adds a `/`, a `?`
    or an `@`, its origin not `https` or not enabled: `403`.

The upstream headers are built fresh: `user-agent: macaw-live-proxy` and the enabled
origin's configured `headers:`, nothing of the viewer's.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
