14.4 KiB · text History 3208487
import Config

# config/runtime.exs is executed for all environments, including
# during releases. It is executed after compilation and before the
# system starts, so it is typically used to load production configuration
# and secrets from environment variables or elsewhere. Do not define
# any compile-time configuration in here, as it won't be applied.
# The block below contains prod specific runtime configuration.

# ## Using releases
#
# If you use `mix release`, you need to explicitly enable the server
# by passing the PHX_SERVER=true when you start it:
#
#     PHX_SERVER=true bin/vigil start
#
# Alternatively, you can use `mix phx.gen.release` to generate a `bin/server`
# script that automatically sets the env var above.
# Invite-only unless REGISTRATION_OPEN=true (config.exs). With NEIAM's
# OIDC_PROVISION=invite_only, a first NEIAM login needs an invite too.
if registration_open = System.get_env("REGISTRATION_OPEN") do
  config :vigil, :registration_open, registration_open in ~w(true 1)
end

# Organization membership from identity-provider groups, declared rather
# than made in the UI: comma-separated org:group:role[:provider], e.g.
# "neiam:neiam:member,neiam:neiam-admins:admin". Organizations named are
# made if missing. Accounts themselves still come from neiam_auth's
# OIDC_PROVISION_GROUPS (set it to the same groups).
if rules = System.get_env("VIGIL_ORG_GROUP_RULES") do
  # Parsed at boot (Vigil.Organizations.GroupSync.parse_env/1).
  config :vigil, :org_group_rules_env, rules
end

if System.get_env("PHX_SERVER") do
  config :vigil, VigilWeb.Endpoint, server: true
end

config :vigil, VigilWeb.Endpoint, http: [port: String.to_integer(System.get_env("PORT", "4000"))]

if config_env() == :dev do
  # Reload browser tabs when matching files change.
  config :vigil, VigilWeb.Endpoint,
    live_reload: [
      web_console_logger: true,
      patterns: [
        # Static assets, except user uploads
        ~r"priv/static/(?!uploads/).*\.(js|css|png|jpeg|jpg|gif|svg)$"E,
        # Gettext translations
        ~r"priv/gettext/.*\.po$"E,
        # Router, Controllers, LiveViews and LiveComponents
        ~r"lib/vigil_web/router\.ex$"E,
        ~r"lib/vigil_web/(controllers|live|components)/.*\.(ex|heex)$"E
      ]
    ]
end

if config_env() == :prod do
  database_url =
    System.get_env("DATABASE_URL") ||
      raise """
      environment variable DATABASE_URL is missing.
      For example: ecto://USER:PASS@HOST/DATABASE
      """

  maybe_ipv6 = if System.get_env("ECTO_IPV6") in ~w(true 1), do: [:inet6], else: []

  config :vigil, Vigil.Repo,
    # ssl: true,
    url: database_url,
    pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
    # For machines with several cores, consider starting multiple pools of `pool_size`
    # pool_count: 4,
    socket_options: maybe_ipv6

  # The secret key base is used to sign/encrypt cookies and other secrets.
  # A default value is used in config/dev.exs and config/test.exs but you
  # want to use a different value for prod and you most likely don't want
  # to check this value into version control, so we use an environment
  # variable instead.
  secret_key_base =
    System.get_env("SECRET_KEY_BASE") ||
      raise """
      environment variable SECRET_KEY_BASE is missing.
      You can generate one by calling: mix phx.gen.secret
      """

  host = System.get_env("PHX_HOST") || "example.com"

  config :vigil, :dns_cluster_query, System.get_env("DNS_CLUSTER_QUERY")

  config :vigil, VigilWeb.Endpoint,
    url: [host: host, port: 443, scheme: "https"],
    http: [
      # Enable IPv6 and bind on all interfaces.
      # Set it to  {0, 0, 0, 0, 0, 0, 0, 1} for local network only access.
      # See the documentation on https://bandit.hexdocs.pm/Bandit.html#t:options/0
      # for details about using IPv6 vs IPv4 and loopback vs public addresses.
      ip: {0, 0, 0, 0, 0, 0, 0, 0}
    ],
    secret_key_base: secret_key_base

  # ## SSL Support
  #
  # To get SSL working, you will need to add the `https` key
  # to your endpoint configuration:
  #
  #     config :vigil, VigilWeb.Endpoint,
  #       https: [
  #         ...,
  #         port: 443,
  #         cipher_suite: :strong,
  #         keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
  #         certfile: System.get_env("SOME_APP_SSL_CERT_PATH")
  #       ]
  #
  # The `cipher_suite` is set to `:strong` to support only the
  # latest and more secure SSL ciphers. This means old browsers
  # and clients may not be supported. You can set it to
  # `:compatible` for wider support.
  #
  # `:keyfile` and `:certfile` expect an absolute path to the key
  # and cert in disk or a relative path inside priv, for example
  # "priv/ssl/server.key". For all supported SSL configuration
  # options, see https://plug.hexdocs.pm/Plug.SSL.html#configure/1
  #
  # We also recommend setting `force_ssl` in your config/prod.exs,
  # ensuring no data is ever sent via http, always redirecting to https:
  #
  #     config :vigil, VigilWeb.Endpoint,
  #       force_ssl: [hsts: true]
  #
  # Check `Plug.SSL` for all available options in `force_ssl`.

  # -- Mail (slice 11) ---------------------------------------------------------
  # Mailer adapter selection by MAIL_PROVIDER, as the sibling apps
  # (clayman, waxx):
  #
  #   * "mail_prism" → MailPrism.SwooshAdapter, needs MAIL_PRISM_URL and
  #                    MAIL_PRISM_API_KEY: send through mail-prism
  #                    (prism.neiam.org), which holds the relay credentials
  #                    and renders priv/mail_prism/ (synced at boot, see
  #                    Vigil.Application). MAIL_FROM_ADDRESS must be the
  #                    address the key was issued for.
  #   * "smtp"       → Swoosh.Adapters.SMTP (via gen_smtp), needs SMTP_RELAY
  #   * "log"        → Swoosh.Adapters.Logger
  #   * unset        → mail_prism if both MAIL_PRISM_* are set (blank counts
  #                    as unset), else smtp if SMTP_RELAY is set, else log
  #
  # The Logger adapter doesn't actually send mail — it logs the rendered
  # email at :info — but it gets us off Swoosh.Adapters.Local (the dev
  # mailbox), so login links and alerts at least leave a trail in the pod
  # log when SMTP isn't configured.
  #
  # Map env-string to a literal atom. `String.to_existing_atom/1` doesn't
  # work here in a release: runtime.exs runs before the application that
  # owns these atoms has loaded, so the atoms aren't in the table yet.
  smtp_tri = fn var, default ->
    case System.get_env(var, default) do
      "always" -> :always
      "if_available" -> :if_available
      "never" -> :never
      other -> raise "#{var} must be one of always|if_available|never, got: #{inspect(other)}"
    end
  end

  smtp_opts = fn relay ->
    # Eager-load the OS CA bundle into OTP's `public_key` cache. Without
    # this, `:public_key.cacerts_get/0` returns `:undefined`, and
    # `gen_smtp`'s internal default `tls_options` injects
    # `cacerts: :undefined` — which `:ssl` then rejects as incompatible
    # with `verify: :verify_peer`, clobbering our explicit `cacertfile`.
    case :public_key.cacerts_load() do
      :ok ->
        :ok

      {:error, reason} ->
        require Logger

        Logger.warning("public_key:cacerts_load failed: #{inspect(reason)} — TLS verify may fail")
    end

    # CA bundle for TLS verification: `cacertfile` (path) as a fallback
    # to the cacerts_load above, belt-and-braces. Override
    # `SMTP_CACERTFILE` if your image puts the bundle elsewhere; set
    # `SMTP_TLS_VERIFY=verify_none` for self-signed / private relays
    # where you'd rather skip cert validation.
    smtp_cacertfile = System.get_env("SMTP_CACERTFILE", "/etc/ssl/certs/ca-certificates.crt")

    smtp_verify =
      case System.get_env("SMTP_TLS_VERIFY", "verify_peer") do
        "verify_peer" ->
          :verify_peer

        "verify_none" ->
          :verify_none

        other ->
          raise "SMTP_TLS_VERIFY must be verify_peer or verify_none, got: #{inspect(other)}"
      end

    # Resolve the CA store NOW (after `cacerts_load`) rather than letting
    # the downstream stack call `cacerts_get/0` lazily. gen_smtp / ssl
    # has a habit of evaluating it in a context where it still returns
    # `:undefined`, which then collides with our `cacertfile`. Passing
    # `cacerts: <list>` explicitly is unambiguous — `:ssl` honors it and
    # never re-derives.
    smtp_cacerts =
      case :public_key.cacerts_get() do
        certs when is_list(certs) and certs != [] -> certs
        _ -> nil
      end

    tls_options =
      [
        verify: smtp_verify,
        server_name_indication: String.to_charlist(relay),
        depth: 99
      ] ++
        cond do
          smtp_verify != :verify_peer -> []
          is_list(smtp_cacerts) -> [cacerts: smtp_cacerts]
          true -> [cacertfile: smtp_cacertfile]
        end

    # Pin modern TLS at both the top level (read by gen_smtp before it
    # calls :ssl.connect) and inside tls_options (read by :ssl itself).
    tls_versions = [:"tlsv1.2", :"tlsv1.3"]

    # gen_smtp 1.2 has two distinct connection paths with different
    # option keys:
    #
    #   * `ssl: true` (port 465 implicit TLS) reads its TLS opts from
    #     `sockopts`. `tls_options` is ignored on this path.
    #   * `tls: :always|:if_available` (STARTTLS upgrade) reads from
    #     `tls_options` — only used during do_STARTTLS.
    #
    # Without sockopts on the implicit-TLS path, OTP 28's `:ssl` falls
    # through to its own defaults (verify_peer + `cacerts_get()` which
    # returns `:undefined`) and bails with `{options, incompatible,
    # [verify: verify_peer, cacerts: undefined]}`. Putting the same opts
    # on both keys covers both relay setups.
    ssl_opts = [{:versions, tls_versions} | tls_options]

    [
      adapter: Swoosh.Adapters.SMTP,
      relay: relay,
      port: String.to_integer(System.get_env("SMTP_PORT", "587")),
      username: System.get_env("SMTP_USERNAME"),
      password: System.get_env("SMTP_PASSWORD"),
      tls: smtp_tri.("SMTP_TLS", "if_available"),
      ssl: System.get_env("SMTP_SSL", "false") == "true",
      auth: smtp_tri.("SMTP_AUTH", "if_available"),
      allowed_tls_versions: tls_versions,
      sockopts: ssl_opts,
      tls_options: ssl_opts,
      retries: 1,
      no_mx_lookups: false
    ]
  end

  log_opts = [adapter: Swoosh.Adapters.Logger, level: :info]

  present = fn var ->
    case System.get_env(var) do
      nil -> nil
      v -> if String.trim(v) == "", do: nil, else: String.trim(v)
    end
  end

  mail_prism = {present.("MAIL_PRISM_URL"), present.("MAIL_PRISM_API_KEY")}
  mail_prism? = match?({url, key} when is_binary(url) and is_binary(key), mail_prism)

  mail_prism_opts = fn ->
    case mail_prism do
      {url, key} when is_binary(url) and is_binary(key) ->
        [adapter: MailPrism.SwooshAdapter, url: url, api_key: key]

      _ ->
        raise "MAIL_PROVIDER=mail_prism needs MAIL_PRISM_URL and MAIL_PRISM_API_KEY"
    end
  end

  mailer_opts =
    case {present.("MAIL_PROVIDER"), present.("SMTP_RELAY")} do
      {"mail_prism", _} ->
        mail_prism_opts.()

      {nil, _} when mail_prism? ->
        mail_prism_opts.()

      {"log", _} ->
        log_opts

      {"smtp", nil} ->
        raise "MAIL_PROVIDER=smtp needs SMTP_RELAY"

      {"smtp", relay} ->
        smtp_opts.(relay)

      {nil, nil} ->
        log_opts

      {nil, relay} ->
        smtp_opts.(relay)

      {other, _} ->
        raise "MAIL_PROVIDER must be one of mail_prism|smtp|log, got: #{inspect(other)}"
    end

  config :vigil, Vigil.Mailer, mailer_opts

  # Who every email (login links, alerts) comes from (Vigil.Mailer.sender/0).
  config :vigil, Vigil.Mailer,
    from_name: System.get_env("MAIL_FROM_NAME", "Vigil"),
    from_address: System.get_env("MAIL_FROM_ADDRESS") || "noreply@#{host}"

  # -- end mail ------------------------------------------------------------------

  # -- libcluster (slice 11) -----------------------------------------------------
  # As the sibling apps run it: peers are found by listing the pods labelled
  # CLUSTER_SELECTOR through the Kubernetes API (the pod's service account
  # needs `list` on pods), each node named vigil@<pod ip> by rel/env.sh.eex.
  # Phoenix PubSub then spans the replicas, which keeps Vigil.Ingest.Keys'
  # cache coherent (flushes are broadcast). Rate limits are counted per
  # node. Off unless POD_IP is set, so a release run outside Kubernetes
  # stays a single node (DNS_CLUSTER_QUERY is the other way to cluster).
  if System.get_env("POD_IP") do
    config :libcluster,
      topologies: [
        vigil: [
          strategy: Cluster.Strategy.Kubernetes,
          config: [
            mode: :ip,
            # List *pods* by label: Endpoints carry their Service's labels,
            # not the pods', so filtering those finds nobody, silently.
            kubernetes_ip_lookup_mode: :pods,
            kubernetes_selector: System.get_env("CLUSTER_SELECTOR", "name=vigil"),
            kubernetes_service_name: System.get_env("CLUSTER_SERVICE", "vigil-headless"),
            kubernetes_node_basename: "vigil",
            kubernetes_namespace: System.get_env("POD_NAMESPACE", "vigil"),
            polling_interval: 10_000
          ]
        ]
      ]
  end

  # -- end libcluster ------------------------------------------------------------
end

# Uploaded files (sourcemap chunks and bundles): local disk under
# VIGIL_STORAGE_ROOT, or an S3-compatible bucket when S3_BUCKET is set.
if root = System.get_env("VIGIL_STORAGE_ROOT") do
  config :vigil, Vigil.Storage.Local, root: root
end

if bucket = System.get_env("S3_BUCKET") do
  config :vigil, :storage, Vigil.Storage.S3

  config :vigil, Vigil.Storage.S3,
    bucket: bucket,
    endpoint: System.fetch_env!("S3_ENDPOINT"),
    region: System.get_env("S3_REGION", "us-east-1"),
    access_key_id: System.fetch_env!("S3_ACCESS_KEY_ID"),
    secret_access_key: System.fetch_env!("S3_SECRET_ACCESS_KEY")
end

# /metrics (VigilWeb.HealthPlug): behind a bearer token, or open on a
# private network, or off (the default).
if token = System.get_env("METRICS_TOKEN") do
  config :vigil, :metrics_token, token
end

if System.get_env("METRICS_PUBLIC") in ~w(true 1) do
  config :vigil, :metrics_public, true
end

# Self-reporting: Vigil's own errors and cron jobs go to this DSN (a
# project on this instance, or on another). Unset: nothing is sent.
if dsn = System.get_env("VIGIL_SELF_DSN") do
  config :sentry,
    dsn: dsn,
    environment_name: System.get_env("VIGIL_SELF_ENVIRONMENT", "production"),
    release: "vigil@" <> to_string(Application.spec(:vigil, :vsn) || "dev")
end