# `MishkaCmsCore.Runtime.Redirects`
[🔗](https://github.com/mishka-group/mishka_cms_core/blob/v0.0.5-alpha.13/lib/mishka_cms_core/runtime/redirects.ex#L5)

The redirect rules of each site, answered on the request that asks for an old address.

`MishkaCmsCore.Runtime.Redirect` is the table and `MishkaCmsCore.Runtime.States.RedirectsState`
the ETS copy every request reads; this module is what stands between them and the rest of the
system — the form both addresses are stored in, the rule that a chain of redirects never comes
back on itself, and the answer a matching request gets.

## Where a redirect is answered

`MishkaCmsCore.Runtime.Plugs.SiteLookupPlug` calls `redirect/2` the moment the request's site is
known, before the session is touched and before any page is resolved, so a rule answers every
address the `:browser` pipeline reaches — a page that moved, and a file `Plug.Static` did not find,
which falls through to the router's catch-all.

A live navigation inside an open socket reaches no plug; `lookup/3` answers it the same way, for
the LiveView that serves the site's pages to ask in `handle_params/3`.

## What a rule answers

A rule's `kind` says what the visitor gets, as the answer `lookup/3` gives:

  * `:redirect` — `{:redirect, location, status}`: sent to `to` with 301, 302, 307 or 308.
  * `:rewrite` — `{:rewrite, path, 200}`: the address stays in the browser and `path`, one of the
    site's own, is served at it. A media file under `/uploads/<site_id>/media/` is sent by
    `redirect/2` the way the endpoint serves it; any other path is a page, which the LiveView that
    serves the site's pages resolves in place of the address asked for. The target is served as it
    is, never looked up again, so a rewrite cannot loop.
  * `:gone` — `{:gone, nil, 410}` and `:not_found` — `{:not_found, nil, 404}`: the site's error
    page with that status.

A request whose page is rewritten goes on through the pipeline with its target in
`conn.private[:mishka_cms_rewrite]`, so `MishkaCmsCore.Runtime.Plugs.LanguagePlug` leaves the
address it asked for where it is.

## The event

Every answer a rule gives passes through `web:request:redirected` before it is served, with
`meta: %{site_id:, path:, query:}` — the address as the request asked it. A target is only ever
the stored row's: nothing the request carries — its query values, its `Host` — becomes a
`location`, and a path on the site takes the visitor's query string as its query alone. A plugin returns the
answer to serve: the same one, another in the same shape (a redirect turned into a 410, a target
of its own), or `nil` to serve none, so the request goes on to its page. Only a request a rule
names reaches it; an extension that adds rules of its own writes them as
`MishkaCmsCore.Runtime.Redirect` rows, which are served from memory like every other.

# `answer`

```elixir
@type answer() ::
  {:redirect, String.t(), 301 | 302 | 307 | 308}
  | {:rewrite, String.t(), 200}
  | {:gone, nil, 410}
  | {:not_found, nil, 404}
```

What a rule answers a request with — see the moduledoc.

# `check_target`

```elixir
@spec check_target(Ash.Changeset.t(), map()) :: :ok | {:error, keyword()}
```

The validation every create and update of `MishkaCmsCore.Runtime.Redirect` runs on where a rule
that will be served lands.

A redirect refuses a target that is its own source, and a target the site's other active
redirects lead back from — to the source or to any address already on the way. A rule leaving the
site, or for a host `MishkaCmsCore.Runtime.States.SiteState` gives another site, ends the chain.
A rewrite refuses its own address, and a file that is not one of its site's media files
(`MishkaCmsCore.Runtime.Media.storage_paths/2`); it is served without being looked up again, so
it never takes part in a chain.

Checked when the rule is written active, or restored, and when its addresses, its `kind` or its
`active` change — as the action runs, not while a form is being typed. The other rules are read
with the action's own actor, tenant and authorization, so a check the system runs reads as the
system.

# `clear_unmatched_query`

```elixir
@spec clear_unmatched_query(map()) :: map()
```

The admin form's save params with `from_query` emptied when the "Match a query string" box was
unticked, so a rule stops matching its query.

# `form_kind`

```elixir
@spec form_kind(map()) :: atom()
```

The kind the admin form holds now, `:redirect` until one is chosen — what decides which of its
fields it shows. `state` is the form's gervaz state.

# `form_match_query?`

```elixir
@spec form_match_query?(map()) :: boolean()
```

Whether the admin form's "Match a query string" box is ticked, which is what shows its `from_query`
field. `state` is the form's gervaz state.

# `kind_label`

```elixir
@spec kind_label(atom()) :: String.t()
```

The name of `kind` in the reader's language.

# `kind_options`

```elixir
@spec kind_options() :: [{String.t(), atom()}]
```

The kinds as `{label, value}` pairs for a select, each label in the reader's language.

# `kinds`

```elixir
@spec kinds() :: [:redirect | :rewrite | :gone | :not_found]
```

What a rule may answer: `:redirect`, `:rewrite`, `:gone` or `:not_found`.

# `lookup`

```elixir
@spec lookup(String.t(), String.t(), String.t()) :: answer() | nil
```

The answer `site_id` serves for `request_path` and `query_string` (with no `?`), or `nil`. Read
from `MishkaCmsCore.Runtime.States.RedirectsState`, with no query, then passed through
`web:request:redirected` — see the moduledoc.

A request with a query string asks first for a rule on its whole query, then on each of its
parameters (`p=123` among `p=123&utm_source=x`), then on each parameter's wildcard (`p=*`), and a
redirect sends it to that rule's target as written. Otherwise the rule on the path alone answers,
and a redirect's target takes the request's `query_string` when it has none of its own. A request
with no query string asks for the path alone.

    lookup(site.id, "/old", "page=2")  #=> {:redirect, "/new?page=2", 301}
    lookup(site.id, "/", "p=55")       #=> {:rewrite, "/fa/blog/hello", 200}
    lookup(site.id, "/retired", "")    #=> {:gone, nil, 410}
    lookup(site.id, "/about", "")      #=> nil

# `normalize`

```elixir
@spec normalize(Ash.Changeset.t(), map()) :: Ash.Changeset.t()
```

The change every create and update of `MishkaCmsCore.Runtime.Redirect` runs: `from_path` through
`normalize_path/1` and `from_query` through `normalize_query/1`, each only when it is being
written, and `to` by the rule's `kind` — `normalize_target/1` for a redirect, `rewrite_target/1`
for a rewrite, and none for a 410 or a 404. A value these refuse is refused on its field, and so
is a `from_path` that `reserved?/1` and a wildcard among other parameters.

# `normalize_path`

```elixir
@spec normalize_path(String.t()) :: {:ok, String.t()} | :error
```

The address a rule answers, as it is stored and matched: one leading `/`, no scheme or host, no
query or fragment, no empty segment and so no trailing `/` but the root's, and every `%XX` escape
decoded. `:error` for what cannot be an address on a site: an empty value, whitespace or a control
character, a scheme other than `http` or `https`, or an escape that decodes to invalid UTF-8.

    normalize_path("https://mishka.tools/images/blog/a.jpg?w=1") #=> {:ok, "/images/blog/a.jpg"}
    normalize_path("old-page/")                                  #=> {:ok, "/old-page"}
    normalize_path("/fa/%D8%A8%D9%84%D8%A7%DA%AF")               #=> {:ok, "/fa/بلاگ"}
    normalize_path("/a b")                                       #=> :error

# `normalize_query`

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

The query string a rule answers, as it is stored and matched: a leading `?` dropped, every
parameter decoded, and the parameters in order, joined with `&`. `nil` for none.

`*` as the value — `p=*` — is a rule's wildcard: it answers that parameter with any value, at its
own path, when no rule on the exact query does. A wildcard is a rule's whole query.

    normalize_query("?page_id=7")   #=> "page_id=7"
    normalize_query("p=1&cat=%33")  #=> "cat=3&p=1"
    normalize_query("p=*")          #=> "p=*"
    normalize_query("")             #=> nil

# `normalize_target`

```elixir
@spec normalize_target(String.t()) :: {:ok, String.t()} | :error
```

Where a rule may send a visitor, trimmed: a path on the site (`/x`, with a query or a fragment if
it has one) or an absolute `http(s)` URL with a host. `:error` for anything `safe_target?/1`
refuses.

# `permanent?`

```elixir
@spec permanent?(pos_integer()) :: boolean()
```

Whether `status` tells a browser and a search engine the move is for good: 301 and 308.

# `redirect`

```elixir
@spec redirect(Plug.Conn.t(), %{:id =&gt; String.t(), optional(atom()) =&gt; term()}) ::
  Plug.Conn.t()
```

Answers `conn` with what `site` serves for its address, if anything, from `lookup/3`:

  * a redirect — its status and `location`, halted;
  * a rewritten media file — the file, sent as the endpoint sends `/uploads`, halted; a file that
    is not there is the site's 404;
  * a rewritten page — the conn goes on, with the target in `conn.private[:mishka_cms_rewrite]`;
  * a 410 or a 404 — the site's error page with that status, raised in a `Plug.Conn.WrapperError`
    that carries this conn, so `render_errors` draws the site's own page.

A file, a 410 and a 404 are answered only while the site is open
(`MishkaCmsCore.Runtime.SiteAvailability.state/1`); on an offline site the conn goes on, for the
gate that answers an offline site to answer it. A `GET` or `HEAD` whose path has an empty segment,
`//about/`, and is none of the CMS's own addresses (`reserved?/1`), is first sent with a 301 to the same path with each `//` made one `/`, `/about/`, its
query kept; the target always starts with a single `/`, so `//evil.com` is `/evil.com` on this
site. A conn no rule matches is returned untouched.

# `reserved?`

```elixir
@spec reserved?(String.t()) :: boolean()
```

Whether `path` (normalized) is one of the CMS's own addresses, which no rule may take.

# `rewrite_target`

```elixir
@spec rewrite_target(String.t()) :: {:ok, String.t()} | :error
```

Where a rewrite may serve from: a path on the site with no query or fragment, none of the CMS's
own (`reserved?/1`), as `normalize_path/1` writes it. `:error` for anything else, a full address
included: a rewrite never fetches from another host.

    rewrite_target("/fa/blog/hello")  #=> {:ok, "/fa/blog/hello"}
    rewrite_target("https://x.com/a") #=> :error
    rewrite_target("/admin")          #=> :error

# `safe_target?`

```elixir
@spec safe_target?(String.t()) :: boolean()
```

Whether `target` is somewhere a visitor may be sent, asked when a rule is saved and again when
its answer is built. Both `target` and its `URI.decode/1` form must hold no whitespace, control
character or `\` (which a browser reads as `/`), and must parse with `URI.new/1` as the same one
of:

  * a path on the site — no scheme, no host, no userinfo, one leading `/` (`//host` is another
    host to a browser);
  * a full address — `http` or `https`, a host, and no userinfo (`http://good.com@evil.com` goes
    to `evil.com`).

So `/%2F%2Fevil.com`, `/%5Cevil.com`, `javascript:` and `data:` are all refused.

    safe_target?("/fa/blog?page=2")         #=> true
    safe_target?("https://docs.example.com") #=> true
    safe_target?("//evil.com")              #=> false
    safe_target?("http://good.com@evil.com") #=> false

# `status_label`

```elixir
@spec status_label(pos_integer()) :: String.t()
```

The name of `status` in the reader's language, such as `301 Moved permanently`.

# `status_options`

```elixir
@spec status_options() :: [{String.t(), pos_integer()}]
```

The statuses as `{label, value}` pairs for a select, each label in the reader's language.

# `statuses`

```elixir
@spec statuses() :: [301 | 302 | 307 | 308]
```

The statuses a rule may answer with.

# `tick_match_query`

```elixir
@spec tick_match_query(Phoenix.HTML.Form.t(), map()) :: Phoenix.HTML.Form.t()
```

The admin form once opened: a rule that already has a `from_query` starts with the "Match a query
string" box ticked.

# `writes?`

```elixir
@spec writes?(map() | nil) :: boolean()
```

Whether `user` writes redirect rules from the dashboard: it holds
`admin:dashboard:runtime:redirect`, or a name above it. Which site's rules it writes is the
resource's policies' question.

---

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