prop/lib/microwaveprop/beacons.ex
Graham McIntire 14b90ee9f3
fix(security,perf): address 9 audit findings (access control, DoS, crashes)
- Beacon detail endpoints (LiveView + REST API) now hide unapproved
  beacons from anonymous and unauthorized viewers; only the submitter
  and admins can see pending records before approval. Adds
  Beacons.get_visible_beacon/2 with scope-aware checks.
- API contact pagination now honors per_page end-to-end.
  Radio.list_contacts/1 accepts :per_page and clamps to 200.
- API rate limiter: ETS table is now owned by a long-lived Sweeper
  GenServer (won't die with a request task); Sweeper periodically
  prunes expired-window rows to bound memory; init_table/0 race is
  rescued.
- /scores/cells and /weather/cells: add per-IP rate limiting and a
  shared GridBounds clamp/413 guard so global / oversized viewports
  no longer drive unbounded binary responses.
- NEXRAD PNG unfilter (sub/up/average/paeth): replace acc++[byte]
  + Enum.at(acc, idx-bpp) with O(n) binary recursion. Decode time
  for the 12200x5400 n0q frame goes from quadratic to linear.
- LiveTableFooter.parse_page and ScoresFile.fetch_bound: switch
  String.to_integer/String.to_float to Integer.parse/Float.parse,
  fall back to defaults instead of raising.
- PathLive and MapLive band-event handlers: replace
  String.to_integer(params["band"]) with parse_int / parse_band_param
  so a non-numeric band parameter no longer crashes the LiveView.
2026-05-11 18:53:21 -05:00

169 lines
5 KiB
Elixir

defmodule Microwaveprop.Beacons do
@moduledoc """
The Beacons context. Anyone can submit a beacon — authenticated or not —
but submissions are held as unapproved until an admin approves them.
Only approved beacons appear in the public list.
"""
import Ecto.Query, warn: false
alias Microwaveprop.Accounts.User
alias Microwaveprop.Beacons.Beacon
alias Microwaveprop.Repo
@topic "beacons"
@doc """
Subscribes to beacon change notifications. Messages:
* `{:created, %Beacon{}}`
* `{:updated, %Beacon{}}`
* `{:deleted, %Beacon{}}`
"""
@spec subscribe_beacons() :: :ok | {:error, term()}
def subscribe_beacons do
Phoenix.PubSub.subscribe(Microwaveprop.PubSub, @topic)
end
defp broadcast(message) do
Phoenix.PubSub.broadcast(Microwaveprop.PubSub, @topic, message)
end
@doc "Returns approved beacons ordered by most recently added."
@spec list_beacons() :: [Beacon.t()]
def list_beacons do
Repo.all(
from b in Beacon,
where: b.approved == true,
order_by: [desc: b.inserted_at]
)
end
@doc """
Base Ecto query for approved beacons. Used as a `live_table`
`data_provider` so sort/search/pagination can be applied on top.
"""
@spec approved_beacons_query() :: Ecto.Query.t()
def approved_beacons_query do
from b in Beacon, as: :resource, where: b.approved == true
end
@doc "Returns unapproved beacons awaiting admin review."
@spec list_pending_beacons() :: [Beacon.t()]
def list_pending_beacons do
Repo.all(
from b in Beacon,
where: b.approved == false,
order_by: [asc: b.inserted_at]
)
end
@doc """
Returns every beacon (approved or pending) that the given user submitted,
newest first. Used by the public `/u/:callsign` profile page.
"""
@spec list_beacons_for_user(User.t()) :: [Beacon.t()]
def list_beacons_for_user(%User{id: user_id}) do
Repo.all(
from b in Beacon,
where: b.user_id == ^user_id,
order_by: [desc: b.inserted_at]
)
end
@doc "Gets a single beacon. Raises if not found."
@spec get_beacon!(Ecto.UUID.t()) :: Beacon.t() | [Beacon.t()] | nil
def get_beacon!(id), do: Beacon |> Repo.get!(id) |> Repo.preload(:user)
@doc """
Returns a beacon only if the viewer is allowed to see it. Approved
beacons are visible to everyone; pending (unapproved) beacons are
visible only to the submitter and admins. Returns `nil` for
not-found, malformed ids, and unauthorized viewers — callers render
the same 404 in each case so existence of a pending beacon is not
observable.
"""
@spec get_visible_beacon(Ecto.UUID.t() | String.t(), User.t() | nil) :: Beacon.t() | nil
def get_visible_beacon(id, viewer) do
case fetch_beacon(id) do
nil -> nil
beacon -> if can_view?(beacon, viewer), do: beacon
end
end
defp fetch_beacon(id) do
Beacon |> Repo.get(id) |> Repo.preload(:user)
rescue
Ecto.Query.CastError -> nil
end
defp can_view?(%Beacon{approved: true}, _viewer), do: true
defp can_view?(%Beacon{}, %User{is_admin: true}), do: true
defp can_view?(%Beacon{user_id: uid}, %User{id: uid}) when not is_nil(uid), do: true
defp can_view?(%Beacon{}, _viewer), do: false
@doc """
Creates a beacon. When a user is provided they are recorded as the
creator; anonymous submissions pass `nil` and leave `user_id` unset.
"""
@spec create_beacon(User.t() | nil, map()) :: {:ok, Beacon.t()} | {:error, Ecto.Changeset.t()}
def create_beacon(user, attrs)
def create_beacon(%User{} = user, attrs) do
%Beacon{user_id: user.id}
|> Beacon.changeset(attrs)
|> Repo.insert()
|> broadcast_if_ok(:created)
end
def create_beacon(nil, attrs) do
%Beacon{}
|> Beacon.changeset(attrs)
|> Repo.insert()
|> broadcast_if_ok(:created)
end
@doc "Updates a beacon."
@spec update_beacon(Beacon.t(), map()) :: {:ok, Beacon.t()} | {:error, Ecto.Changeset.t()}
def update_beacon(%Beacon{} = beacon, attrs) do
beacon
|> Beacon.changeset(attrs)
|> Repo.update()
|> broadcast_if_ok(:updated)
end
@doc "Marks a beacon as approved, making it visible in the public list."
@spec approve_beacon(Beacon.t()) :: {:ok, Beacon.t()} | {:error, Ecto.Changeset.t()}
def approve_beacon(%Beacon{} = beacon) do
beacon
|> Ecto.Changeset.change(approved: true)
|> Repo.update()
|> broadcast_if_ok(:updated)
end
@doc "Deletes a beacon."
@spec delete_beacon(Beacon.t()) :: {:ok, Beacon.t()} | {:error, Ecto.Changeset.t()}
def delete_beacon(%Beacon{} = beacon) do
case Repo.delete(beacon) do
{:ok, beacon} ->
_ = broadcast({:deleted, beacon})
{:ok, beacon}
other ->
other
end
end
@doc "Returns an `%Ecto.Changeset{}` for tracking beacon changes."
@spec change_beacon(Beacon.t(), map()) :: Ecto.Changeset.t()
def change_beacon(%Beacon{} = beacon, attrs \\ %{}) do
Beacon.changeset(beacon, attrs)
end
defp broadcast_if_ok({:ok, beacon} = result, type) do
_ = broadcast({type, beacon})
result
end
defp broadcast_if_ok(other, _type), do: other
end