🏡 index : quine-global/nugitea.git

defmodule Nugitea.Router do
  @moduledoc """
  The app tier's HTTP side:

    * `/api/v1`: the REST API, `Nugitea.API`;
    * `/graphql`: for the web frontend, as the signed-in user;
    * `/-/session`: web sign-in (`POST`, a login and password) and sign-out
      (`DELETE`), with a session cookie (`Nugitea.Accounts.Sessions`).
      Account names can't start with `-`, so `/-/` can't be a repo path;
    * `/-/raw` and `/-/diff`: a file's content and a commit's diff or patch,
      for the web UI's Gitea-shaped `/raw/...` and `/commit/{sha}.diff`
      URLs (it works out the repo and ref, then fetches these);
    * git's smart-HTTP protocol for everything else, as Gitea's
      routers/web/repo/githttp.go serves it:

          GET  /<owner path>/<repo>.git/info/refs?service=git-upload-pack|git-receive-pack
          POST /<owner path>/<repo>.git/git-upload-pack
          POST /<owner path>/<repo>.git/git-receive-pack

  Every request is authenticated here first (`authenticate/2`): an access
  token in the Authorization header, or else the session cookie. It runs no
  git itself: it resolves the repo against the accounts directory, asks
  `Nugitea.Auth`, and hands the exchange to the storage tier.
  """
  use Plug.Router

  import Plug.Conn

  alias Nugitea.Accounts
  alias Nugitea.Accounts.Directory, as: D
  alias Nugitea.Accounts.Passwords
  alias Nugitea.Accounts.Sessions
  alias Nugitea.Accounts.Tokens
  alias Nugitea.Storage.Client

  @cookie "nugitea_session"

  plug :cors
  plug :fetch_query_params
  plug :fetch_cookies
  plug :parse_graphql_body
  plug :authenticate
  plug :graphql_context
  plug :match
  plug :dispatch

  get "/healthz" do
    send_resp(conn, 200, "ok")
  end

  forward "/api/v1", to: Nugitea.API

  # Sign in: {"login": ..., "password": ...}. The same answer for a wrong
  # password, an unknown login, an org or an account without a password.
  post "/-/session" do
    state = Accounts.state_dir()
    {:ok, dir} = Accounts.Store.load(state)

    with %{"login" => login, "password" => password}
         when is_binary(login) and is_binary(password) <- conn.body_params,
         user = user_account(dir, login),
         true <- Passwords.verify(state, user, password) do
      conn
      |> put_resp_cookie(@cookie, Sessions.create(state, user),
        http_only: true,
        same_site: "Lax",
        secure: https?(conn),
        max_age: Sessions.ttl(),
        path: "/"
      )
      |> json(200, %{login: D.path(dir, user)})
    else
      _ -> json(conn, 401, %{message: "wrong login or password"})
    end
  end

  delete "/-/session" do
    Sessions.delete(Accounts.state_dir(), conn.req_cookies[@cookie])

    conn
    |> delete_resp_cookie(@cookie,
      http_only: true,
      same_site: "Lax",
      secure: https?(conn),
      path: "/"
    )
    |> send_resp(204, "")
  end

  forward "/graphql",
    to: Absinthe.Plug.GraphiQL,
    init_opts: [schema: Nugitea.GraphQL.Schema, interface: :simple, json_codec: Jason]

  # ?repo=OWNER/NAME&ref=REF&path=FILE[&download=1], served as Gitea serves
  # raw files (modules/httplib/serve.go): text as text/plain (an HTML file
  # never renders), images, audio, video and PDF as themselves (SVG
  # sandboxed by CSP), the rest as a download; never sniffed. A repo the
  # caller can't read is 404, as if it didn't exist.
  get "/-/raw" do
    with %{"repo" => repo_path, "ref" => ref, "path" => file} <- conn.query_params,
         {:ok, repo} <- readable_repo(repo_path, conn.assigns.user_id),
         {:ok, %{content: content}} <- Client.blob(repo, ref, file) do
      {type, csp} = raw_type(file, content)
      disposition = if conn.query_params["download"], do: "attachment", else: "inline"

      conn
      |> put_resp_content_type(type, nil)
      |> put_resp_header("x-content-type-options", "nosniff")
      |> then(&if(csp, do: put_resp_header(&1, "content-security-policy", csp), else: &1))
      |> put_resp_header(
        "content-disposition",
        ~s(#{disposition}; filename="#{file |> Path.basename() |> String.replace(~s("), "")}")
      )
      |> send_resp(200, content)
    else
      _ -> send_resp(conn, 404, "not found")
    end
  end

  # ?repo=OWNER/NAME&sha=SHA&format=diff|patch, as Gitea's
  # /commit/{sha}.diff and .patch.
  get "/-/diff" do
    show =
      case conn.query_params["format"] do
        "diff" -> &Client.commit_diff/2
        "patch" -> &Client.commit_patch/2
        _ -> nil
      end

    with %{"repo" => repo_path, "sha" => sha} <- conn.query_params,
         true <- show != nil and sha =~ ~r/\A[0-9a-fA-F]{4,64}\z/,
         {:ok, repo} <- readable_repo(repo_path, conn.assigns.user_id),
         {:ok, text} <- show.(repo, sha) do
      conn
      |> put_resp_content_type("text/plain; charset=utf-8", nil)
      |> put_resp_header("x-content-type-options", "nosniff")
      |> send_resp(200, text)
    else
      _ -> send_resp(conn, 404, "not found")
    end
  end

  get "/*glob" do
    conn = fetch_query_params(conn)

    with {:ok, repo_git} <- strip_suffix(glob, "info/refs"),
         {:ok, service} <- service(conn.query_params["service"]),
         {:ok, repo} <- resolve(repo_git),
         :ok <- allow(service, conn.assigns.user_id, repo) do
      case Client.info_refs(repo, service, List.first(get_req_header(conn, "git-protocol"))) do
        {:ok, body} ->
          conn
          |> put_resp_content_type("application/x-git-#{service}-advertisement", nil)
          |> put_resp_header("cache-control", "no-cache")
          |> send_resp(200, body)
      end
    else
      {:error, status, msg} -> git_error(conn, status, msg)
    end
  end

  post "/*glob" do
    with {:ok, repo_git, service} <- rpc_path(glob),
         {:ok, repo} <- resolve(repo_git),
         :ok <- allow(service, conn.assigns.user_id, repo) do
      rpc(conn, repo, service)
    else
      {:error, status, msg} -> git_error(conn, status, msg)
    end
  end

  defp rpc(conn, repo, service) do
    exchange =
      Client.start_exchange(repo, service,
        stateless: true,
        protocol: List.first(get_req_header(conn, "git-protocol")),
        gzip: get_req_header(conn, "content-encoding") == ["gzip"]
      )

    conn = stream_request(conn, exchange)

    conn =
      conn
      |> put_resp_content_type("application/x-git-#{service}-result", nil)
      |> put_resp_header("cache-control", "no-cache")
      |> send_chunked(200)

    Enum.reduce_while(Client.output(exchange), conn, fn data, conn ->
      case chunk(conn, data) do
        {:ok, conn} -> {:cont, conn}
        {:error, :closed} -> {:halt, conn}
      end
    end)
  end

  defp stream_request(conn, exchange) do
    {status, data, conn} = read_body(conn, length: 1_000_000)
    if data != "", do: Client.input(exchange, data)
    if status == :more, do: stream_request(conn, exchange), else: conn
  end

  defp strip_suffix(glob, suffix) do
    case Enum.split(glob, -length(String.split(suffix, "/"))) do
      {repo, tail} when repo != [] ->
        if(Enum.join(tail, "/") == suffix, do: {:ok, Enum.join(repo, "/")}, else: not_found())

      _ ->
        not_found()
    end
  end

  defp rpc_path(glob) do
    case Enum.split(glob, -1) do
      {repo, ["git-" <> service]} when repo != [] ->
        with {:ok, service} <- service("git-" <> service),
             do: {:ok, Enum.join(repo, "/"), service}

      _ ->
        not_found()
    end
  end

  defp service("git-upload-pack"), do: {:ok, "upload-pack"}
  defp service("git-receive-pack"), do: {:ok, "receive-pack"}

  defp service(_),
    do: {:error, 400, "smart HTTP only: service must be git-upload-pack or git-receive-pack"}

  defp resolve(repo_git) do
    {:ok, dir} = Accounts.Store.load(Accounts.state_dir())

    case Client.resolve(dir, repo_git) do
      nil -> not_found()
      repo -> {:ok, repo}
    end
  end

  # Denied and anonymous is 401, so git asks for credentials and retries;
  # denied with credentials is 403.
  defp allow(service, user, repo) do
    cond do
      Nugitea.Auth.allow?(service, user, repo) -> :ok
      user == nil -> {:error, 401, "authentication required"}
      true -> {:error, 403, "forbidden"}
    end
  end

  defp git_error(conn, 401, msg) do
    conn
    |> put_resp_header("www-authenticate", ~s(Basic realm="nugitea"))
    |> send_resp(401, msg)
  end

  defp git_error(conn, status, msg), do: send_resp(conn, status, msg)

  # Who's calling, as Gitea accepts it: `Authorization: token T`, `Bearer T`,
  # or basic auth with the token as the password; without that header, the
  # web UI's session cookie. Neither is anonymous (nil), as is a session
  # that has ended; a token we don't know is 401, with a challenge so git
  # asks again.
  defp authenticate(conn, _opts) do
    with [header | _] <- get_req_header(conn, "authorization"),
         token when token != nil <- bearer_token(header),
         user when user != nil <- Tokens.lookup_token(Accounts.state_dir(), token) do
      assign(conn, :user_id, user)
    else
      [] ->
        assign(conn, :user_id, Sessions.lookup(Accounts.state_dir(), conn.req_cookies[@cookie]))

      nil ->
        conn
        |> put_resp_header("www-authenticate", ~s(Basic realm="nugitea"))
        |> send_resp(401, "unauthorized")
        |> halt()
    end
  end

  defp bearer_token("token " <> token), do: token
  defp bearer_token("Bearer " <> token), do: token

  defp bearer_token("Basic " <> encoded) do
    with {:ok, credentials} <- Base.decode64(encoded),
         [_user, token] <- String.split(credentials, ":", parts: 2) do
      token
    else
      _ -> nil
    end
  end

  defp bearer_token(_), do: nil

  defp not_found, do: {:error, 404, "not found"}

  # GraphQL resolvers see the caller as `context.user_id`.
  defp graphql_context(%{request_path: "/graphql"} = conn, _opts),
    do: Absinthe.Plug.put_options(conn, context: %{user_id: conn.assigns.user_id})

  defp graphql_context(conn, _opts), do: conn

  # A user account (not an org) by login, or nil.
  defp user_account(dir, login) do
    with id when id != nil <- D.resolve(dir, login),
         %{} = account <- D.account(dir, id),
         false <- D.org?(account),
         do: id,
         else: (_ -> nil)
  end

  # The repo at `path` (owner/name), if `user` may read it.
  defp readable_repo(path, user) do
    {:ok, dir} = Accounts.Store.load(Accounts.state_dir())

    case Client.resolve(dir, path <> ".git") do
      nil -> :error
      repo -> if Nugitea.Auth.allow?("upload-pack", user, repo), do: {:ok, repo}, else: :error
    end
  end

  @browsable ~w(image audio video)

  # A raw file's Content-Type, and the CSP that goes with it, if any.
  defp raw_type(file, content) do
    ext_type = MIME.from_path(file)
    text? = String.valid?(content) and not String.contains?(content, <<0>>)

    cond do
      ext_type == "image/svg+xml" and String.contains?(content, "<svg") ->
        {ext_type, "default-src 'none'; style-src 'unsafe-inline'; sandbox"}

      text? ->
        {"text/plain; charset=utf-8", nil}

      ext_type == "application/pdf" ->
        {ext_type, "default-src 'none'; style-src 'unsafe-inline'"}

      ext_type |> String.split("/") |> hd() |> then(&(&1 in @browsable)) ->
        {ext_type, nil}

      true ->
        {"application/octet-stream", nil}
    end
  end

  # Behind nginx the hop to us is plain HTTP; it says what the browser used.
  defp https?(conn),
    do: conn.scheme == :https or get_req_header(conn, "x-forwarded-proto") == ["https"]

  defp json(conn, status, body) do
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(status, Jason.encode!(body))
  end

  # The Nuxt frontend calls /graphql from its own origin; like
  # rust_nugitea's CorsLayer::permissive, allow anything.
  defp cors(%{request_path: "/graphql"} = conn, _opts) do
    conn =
      conn
      |> put_resp_header("access-control-allow-origin", "*")
      |> put_resp_header("access-control-allow-methods", "*")
      |> put_resp_header("access-control-allow-headers", "*")

    if conn.method == "OPTIONS", do: conn |> send_resp(200, "") |> halt(), else: conn
  end

  defp cors(conn, _opts), do: conn

  # Absinthe reads the query from parsed body params, and clients (the Nuxt
  # frontend included) POST `{"query": ..., "variables": ...}` as JSON; the
  # sign-in form posts JSON too. Only for those: the git routes stream their
  # bodies, and the API routes read theirs themselves.
  @graphql_parsers Plug.Parsers.init(
                     parsers: [:json, Absinthe.Plug.Parser],
                     pass: ["*/*"],
                     json_decoder: Jason
                   )

  defp parse_graphql_body(%{request_path: path} = conn, _opts)
       when path in ["/graphql", "/-/session"],
       do: Plug.Parsers.call(conn, @graphql_parsers)

  defp parse_graphql_body(conn, _opts), do: conn
end