diff --git a/test/support/fixtures/devices_fixtures.ex b/test/support/fixtures/devices_fixtures.ex index f9293e34..ab77a9d7 100644 --- a/test/support/fixtures/devices_fixtures.ex +++ b/test/support/fixtures/devices_fixtures.ex @@ -9,9 +9,14 @@ defmodule Towerops.DevicesFixtures do Generate a device with all required fields. """ def device_fixture(attrs \\ %{}) do + # Handle organization_id specially to ensure proper site creation + {organization_id, attrs} = Map.pop(attrs, :organization_id) + {organization_id, attrs} = if organization_id, do: {organization_id, attrs}, else: Map.pop(attrs, "organization_id") + # Ensure organization and site exist organization = - attrs[:organization] || Map.get(attrs, "organization") || create_organization() + attrs[:organization] || Map.get(attrs, "organization") || + (if organization_id, do: get_organization(organization_id), else: create_organization()) site = attrs[:site] || Map.get(attrs, "site") || create_site(organization) @@ -42,6 +47,10 @@ defmodule Towerops.DevicesFixtures do defp to_atom_key(key) when is_atom(key), do: key defp to_atom_key(key) when is_binary(key), do: String.to_existing_atom(key) + defp get_organization(organization_id) do + Towerops.Organizations.get_organization!(organization_id) + end + defp create_organization do user = Towerops.AccountsFixtures.user_fixture() {:ok, organization} = Towerops.Organizations.create_organization(%{name: "Test Org"}, user.id) @@ -49,7 +58,10 @@ defmodule Towerops.DevicesFixtures do end defp create_site(organization) do - {:ok, site} = Towerops.Sites.create_site(%{name: "Test Site", organization_id: organization.id}) + {:ok, site} = Towerops.Sites.create_site(%{ + name: "Test Site #{System.unique_integer([:positive])}", + organization_id: organization.id + }) site end end diff --git a/test/support/fixtures/organizations_fixtures.ex b/test/support/fixtures/organizations_fixtures.ex index 887c5fa5..79772ff5 100644 --- a/test/support/fixtures/organizations_fixtures.ex +++ b/test/support/fixtures/organizations_fixtures.ex @@ -21,4 +21,15 @@ defmodule Towerops.OrganizationsFixtures do organization end + + def membership_fixture(organization_id, user_id, role) do + {:ok, membership} = + Organizations.create_membership(%{ + organization_id: organization_id, + user_id: user_id, + role: role + }) + + membership + end end diff --git a/test/towerops_web/controllers/api/v1/devices_controller_test.exs b/test/towerops_web/controllers/api/v1/devices_controller_test.exs new file mode 100644 index 00000000..3cf6a482 --- /dev/null +++ b/test/towerops_web/controllers/api/v1/devices_controller_test.exs @@ -0,0 +1,373 @@ +defmodule ToweropsWeb.Api.V1.DevicesControllerTest do + use ToweropsWeb.ConnCase, async: true + + import Towerops.AccountsFixtures + import Towerops.DevicesFixtures + import Towerops.OrganizationsFixtures + + alias Towerops.ApiTokens + alias Towerops.Sites + + setup do + # Create organization with owner + user = user_fixture() + organization = organization_fixture(user.id) + + # Create API token for authentication + {:ok, {_token, raw_token}} = + ApiTokens.create_api_token(%{ + organization_id: organization.id, + user_id: user.id, + name: "Test Token" + }) + + # Setup authenticated connection + conn = + build_conn() + |> put_req_header("authorization", "Bearer #{raw_token}") + |> put_req_header("accept", "application/json") + + %{ + conn: conn, + user: user, + organization: organization, + raw_token: raw_token + } + end + + describe "index/2" do + test "lists all devices for authenticated organization", %{ + conn: conn, + organization: organization + } do + device1 = device_fixture(%{organization_id: organization.id}) + device2 = device_fixture(%{organization_id: organization.id}) + + conn = get(conn, ~p"/api/v1/devices") + + assert %{"devices" => devices} = json_response(conn, 200) + assert length(devices) == 2 + + device_ids = Enum.map(devices, & &1["id"]) + assert device1.id in device_ids + assert device2.id in device_ids + + # Check response structure + device_json = List.first(devices) + assert Map.has_key?(device_json, "id") + assert Map.has_key?(device_json, "name") + assert Map.has_key?(device_json, "ip_address") + assert Map.has_key?(device_json, "site_id") + assert Map.has_key?(device_json, "monitoring_enabled") + assert Map.has_key?(device_json, "snmp_enabled") + assert Map.has_key?(device_json, "inserted_at") + end + + test "filters devices by site_id when provided", %{ + conn: conn, + organization: organization + } do + {:ok, site1} = Sites.create_site(%{name: "Site 1", organization_id: organization.id}) + {:ok, site2} = Sites.create_site(%{name: "Site 2", organization_id: organization.id}) + + device_in_site1 = device_fixture(%{organization_id: organization.id, site_id: site1.id}) + device_in_site2 = device_fixture(%{organization_id: organization.id, site_id: site2.id}) + _device_no_site = device_fixture(%{organization_id: organization.id}) + + conn = get(conn, ~p"/api/v1/devices", site_id: site1.id) + + assert %{"devices" => devices} = json_response(conn, 200) + assert length(devices) == 1 + assert List.first(devices)["id"] == device_in_site1.id + refute device_in_site2.id in Enum.map(devices, & &1["id"]) + end + + test "returns empty list when organization has no devices", %{conn: conn} do + conn = get(conn, ~p"/api/v1/devices") + + assert %{"devices" => []} = json_response(conn, 200) + end + + test "does not return devices from other organizations", %{conn: conn} do + # Create another organization with a device + other_user = user_fixture() + other_org = organization_fixture(other_user.id) + _other_device = device_fixture(%{organization_id: other_org.id}) + + conn = get(conn, ~p"/api/v1/devices") + + assert %{"devices" => devices} = json_response(conn, 200) + assert Enum.empty?(devices) + end + end + + describe "create/2" do + test "creates device with valid attributes", %{conn: conn, organization: organization} do + device_params = %{ + "device" => %{ + "name" => "Test Router", + "ip_address" => "192.168.1.1", + "snmp_enabled" => true, + "snmp_community" => "public" + } + } + + conn = post(conn, ~p"/api/v1/devices", device_params) + + assert %{ + "id" => id, + "name" => "Test Router", + "ip_address" => "192.168.1.1", + "organization_id" => org_id, + "snmp_enabled" => true + } = json_response(conn, 201) + + assert org_id == organization.id + assert is_binary(id) + end + + test "creates device with site_id", %{conn: conn, organization: organization} do + {:ok, site} = Sites.create_site(%{name: "Test Site", organization_id: organization.id}) + + device_params = %{ + "device" => %{ + "name" => "Test Router", + "ip_address" => "192.168.1.1", + "site_id" => site.id + } + } + + conn = post(conn, ~p"/api/v1/devices", device_params) + + assert %{"id" => _id, "site_id" => site_id} = json_response(conn, 201) + assert site_id == site.id + end + + test "defaults organization_id to authenticated organization", %{ + conn: conn, + organization: organization + } do + device_params = %{ + "device" => %{ + "name" => "Test Router", + "ip_address" => "192.168.1.1" + } + } + + conn = post(conn, ~p"/api/v1/devices", device_params) + + assert %{"organization_id" => org_id} = json_response(conn, 201) + assert org_id == organization.id + end + + test "returns 403 when site belongs to different organization", %{conn: conn} do + # Create another organization with a site + other_user = user_fixture() + other_org = organization_fixture(other_user.id) + + {:ok, other_site} = + Sites.create_site(%{name: "Other Site", organization_id: other_org.id}) + + device_params = %{ + "device" => %{ + "name" => "Test Router", + "ip_address" => "192.168.1.1", + "site_id" => other_site.id + } + } + + conn = post(conn, ~p"/api/v1/devices", device_params) + + assert %{"error" => "Access denied to this site"} = json_response(conn, 403) + end + + test "returns 403 when site_id does not exist", %{conn: conn} do + device_params = %{ + "device" => %{ + "name" => "Test Router", + "ip_address" => "192.168.1.1", + "site_id" => Ecto.UUID.generate() + } + } + + conn = post(conn, ~p"/api/v1/devices", device_params) + + assert %{"error" => "Site not found"} = json_response(conn, 403) + end + + test "returns 422 with invalid device params", %{conn: conn} do + device_params = %{ + "device" => %{ + "name" => "", + "ip_address" => "invalid-ip" + } + } + + conn = post(conn, ~p"/api/v1/devices", device_params) + + assert %{"errors" => errors} = json_response(conn, 422) + assert Map.has_key?(errors, "name") or Map.has_key?(errors, "ip_address") + end + + test "returns 400 when device parameter is missing", %{conn: conn} do + conn = post(conn, ~p"/api/v1/devices", %{}) + + assert %{"error" => "Missing 'device' parameter"} = json_response(conn, 400) + end + end + + describe "show/2" do + test "returns device when it belongs to organization", %{ + conn: conn, + organization: organization + } do + device = device_fixture(%{organization_id: organization.id}) + + conn = get(conn, ~p"/api/v1/devices/#{device.id}") + + assert %{ + "id" => id, + "name" => name, + "ip_address" => ip, + "monitoring_enabled" => _, + "snmp_enabled" => _, + "snmp_version" => _, + "snmp_port" => _, + "description" => _, + "check_interval_seconds" => _ + } = json_response(conn, 200) + + assert id == device.id + assert name == device.name + assert ip == device.ip_address + end + + test "returns 404 when device does not exist", %{conn: conn} do + conn = get(conn, ~p"/api/v1/devices/#{Ecto.UUID.generate()}") + + assert %{"error" => "Device not found"} = json_response(conn, 404) + end + + test "returns 403 when device belongs to different organization", %{conn: conn} do + # Create another organization with a device + other_user = user_fixture() + other_org = organization_fixture(other_user.id) + other_device = device_fixture(%{organization_id: other_org.id}) + + conn = get(conn, ~p"/api/v1/devices/#{other_device.id}") + + assert %{"error" => "Access denied to this device"} = json_response(conn, 403) + end + end + + describe "update/2" do + test "updates device with valid attributes", %{conn: conn, organization: organization} do + device = device_fixture(%{organization_id: organization.id}) + + update_params = %{ + "device" => %{ + "name" => "Updated Router", + "ip_address" => "192.168.1.100" + } + } + + conn = patch(conn, ~p"/api/v1/devices/#{device.id}", update_params) + + assert %{ + "id" => id, + "name" => "Updated Router", + "ip_address" => "192.168.1.100" + } = json_response(conn, 200) + + assert id == device.id + end + + test "returns 404 when device does not exist", %{conn: conn} do + update_params = %{ + "device" => %{ + "name" => "Updated Router" + } + } + + conn = patch(conn, ~p"/api/v1/devices/#{Ecto.UUID.generate()}", update_params) + + assert %{"error" => "Device not found"} = json_response(conn, 404) + end + + test "returns 403 when device belongs to different organization", %{conn: conn} do + # Create another organization with a device + other_user = user_fixture() + other_org = organization_fixture(other_user.id) + other_device = device_fixture(%{organization_id: other_org.id}) + + update_params = %{ + "device" => %{ + "name" => "Updated Router" + } + } + + conn = patch(conn, ~p"/api/v1/devices/#{other_device.id}", update_params) + + assert %{"error" => "Access denied to this device"} = json_response(conn, 403) + end + + test "returns 422 with invalid update params", %{conn: conn, organization: organization} do + device = device_fixture(%{organization_id: organization.id}) + + update_params = %{ + "device" => %{ + "name" => "", + "ip_address" => "invalid-ip" + } + } + + conn = patch(conn, ~p"/api/v1/devices/#{device.id}", update_params) + + assert %{"errors" => errors} = json_response(conn, 422) + assert Map.has_key?(errors, "name") or Map.has_key?(errors, "ip_address") + end + + test "returns 400 when device parameter is missing", %{ + conn: conn, + organization: organization + } do + device = device_fixture(%{organization_id: organization.id}) + + conn = patch(conn, ~p"/api/v1/devices/#{device.id}", %{}) + + assert %{"error" => "Missing 'device' parameter"} = json_response(conn, 400) + end + end + + describe "delete/2" do + test "deletes device successfully", %{conn: conn, organization: organization} do + device = device_fixture(%{organization_id: organization.id}) + + conn = delete(conn, ~p"/api/v1/devices/#{device.id}") + + assert %{"success" => true} = json_response(conn, 200) + + # Verify device is deleted + assert_raise Ecto.NoResultsError, fn -> + Towerops.Devices.get_device!(device.id) + end + end + + test "returns 404 when device does not exist", %{conn: conn} do + conn = delete(conn, ~p"/api/v1/devices/#{Ecto.UUID.generate()}") + + assert %{"error" => "Device not found"} = json_response(conn, 404) + end + + test "returns 403 when device belongs to different organization", %{conn: conn} do + # Create another organization with a device + other_user = user_fixture() + other_org = organization_fixture(other_user.id) + other_device = device_fixture(%{organization_id: other_org.id}) + + conn = delete(conn, ~p"/api/v1/devices/#{other_device.id}") + + assert %{"error" => "Access denied to this device"} = json_response(conn, 403) + end + end +end diff --git a/test/towerops_web/permissions_test.exs b/test/towerops_web/permissions_test.exs new file mode 100644 index 00000000..3a35095a --- /dev/null +++ b/test/towerops_web/permissions_test.exs @@ -0,0 +1,410 @@ +defmodule ToweropsWeb.PermissionsTest do + use Towerops.DataCase, async: true + + import Towerops.AccountsFixtures + import Towerops.OrganizationsFixtures + + alias Phoenix.LiveView.Socket + alias Towerops.Accounts.Scope + alias Towerops.Repo + alias ToweropsWeb.Permissions + + describe "can?/3 with superuser" do + setup do + user = user_fixture(%{is_superuser: true}) + organization = organization_fixture(user.id) + organization = Repo.preload(organization, :memberships) + + scope = + Scope.for_user(user) + |> Scope.put_organization(organization) + + %{scope: scope, user: user, organization: organization} + end + + test "superuser can perform any action", %{scope: scope} do + # Test various actions and resources + assert Permissions.can?(scope, :delete, :organization) + assert Permissions.can?(scope, :delete, :device) + assert Permissions.can?(scope, :edit, :device) + assert Permissions.can?(scope, :create, :device) + assert Permissions.can?(scope, :delete, :backup) + assert Permissions.can?(scope, :manage, :anything) + end + + test "superuser can? works with Socket", %{scope: scope} do + socket = %Socket{assigns: %{current_scope: scope}} + + assert Permissions.can?(socket, :delete, :organization) + assert Permissions.can?(socket, :delete, :device) + end + end + + describe "can?/3 with owner role" do + setup do + user = user_fixture() + organization = organization_fixture(user.id) + organization = Repo.preload(organization, :memberships) + + scope = + Scope.for_user(user) + |> Scope.put_organization(organization) + + %{scope: scope, user: user, organization: organization} + end + + test "owner can perform any action", %{scope: scope} do + assert Permissions.can?(scope, :delete, :organization) + assert Permissions.can?(scope, :delete, :device) + assert Permissions.can?(scope, :edit, :device) + assert Permissions.can?(scope, :create, :device) + assert Permissions.can?(scope, :delete, :backup) + assert Permissions.can?(scope, :create, :invitation) + end + end + + describe "can?/3 with admin role" do + setup do + owner = user_fixture() + organization = organization_fixture(owner.id) + + admin_user = user_fixture() + membership_fixture(organization.id, admin_user.id, :admin) + + organization = Repo.preload(organization, :memberships, force: true) + + scope = + Scope.for_user(admin_user) + |> Scope.put_organization(organization) + + %{scope: scope, user: admin_user, organization: organization} + end + + test "admin can perform most actions", %{scope: scope} do + assert Permissions.can?(scope, :edit, :device) + assert Permissions.can?(scope, :create, :device) + assert Permissions.can?(scope, :delete, :device) + assert Permissions.can?(scope, :delete, :backup) + assert Permissions.can?(scope, :create, :invitation) + assert Permissions.can?(scope, :view, :organization) + end + + test "admin cannot delete organization", %{scope: scope} do + refute Permissions.can?(scope, :delete, :organization) + end + end + + describe "can?/3 with member role" do + setup do + owner = user_fixture() + organization = organization_fixture(owner.id) + + member_user = user_fixture() + membership_fixture(organization.id, member_user.id, :member) + + organization = Repo.preload(organization, :memberships, force: true) + + scope = + Scope.for_user(member_user) + |> Scope.put_organization(organization) + + %{scope: scope, user: member_user, organization: organization} + end + + test "member can view and edit devices", %{scope: scope} do + assert Permissions.can?(scope, :view, :device) + assert Permissions.can?(scope, :list, :device) + assert Permissions.can?(scope, :create, :device) + assert Permissions.can?(scope, :edit, :device) + end + + test "member can view and edit sites", %{scope: scope} do + assert Permissions.can?(scope, :view, :site) + assert Permissions.can?(scope, :list, :site) + assert Permissions.can?(scope, :create, :site) + assert Permissions.can?(scope, :edit, :site) + end + + test "member can view and edit alerts", %{scope: scope} do + assert Permissions.can?(scope, :view, :alert) + assert Permissions.can?(scope, :list, :alert) + assert Permissions.can?(scope, :create, :alert) + assert Permissions.can?(scope, :edit, :alert) + end + + test "member cannot delete anything", %{scope: scope} do + refute Permissions.can?(scope, :delete, :device) + refute Permissions.can?(scope, :delete, :site) + refute Permissions.can?(scope, :delete, :alert) + refute Permissions.can?(scope, :delete, :backup) + refute Permissions.can?(scope, :delete, :organization) + end + + test "member cannot manage memberships", %{scope: scope} do + refute Permissions.can?(scope, :create, :membership) + refute Permissions.can?(scope, :edit, :membership) + end + + test "member cannot manage invitations", %{scope: scope} do + refute Permissions.can?(scope, :create, :invitation) + refute Permissions.can?(scope, :delete, :invitation) + end + + test "member can view organization", %{scope: scope} do + assert Permissions.can?(scope, :view, :organization) + assert Permissions.can?(scope, :list, :organization) + end + end + + describe "can?/3 with viewer role" do + setup do + owner = user_fixture() + organization = organization_fixture(owner.id) + + viewer_user = user_fixture() + membership_fixture(organization.id, viewer_user.id, :viewer) + + organization = Repo.preload(organization, :memberships, force: true) + + scope = + Scope.for_user(viewer_user) + |> Scope.put_organization(organization) + + %{scope: scope, user: viewer_user, organization: organization} + end + + test "viewer can only view resources", %{scope: scope} do + assert Permissions.can?(scope, :view, :device) + assert Permissions.can?(scope, :list, :device) + assert Permissions.can?(scope, :view, :site) + assert Permissions.can?(scope, :list, :site) + assert Permissions.can?(scope, :view, :organization) + end + + test "viewer cannot perform any write actions", %{scope: scope} do + refute Permissions.can?(scope, :create, :device) + refute Permissions.can?(scope, :edit, :device) + refute Permissions.can?(scope, :delete, :device) + refute Permissions.can?(scope, :create, :site) + refute Permissions.can?(scope, :edit, :site) + refute Permissions.can?(scope, :delete, :site) + end + end + + describe "can?/3 with no organization context" do + test "returns false when scope has no organization" do + user = user_fixture() + scope = Scope.for_user(user) + + refute Permissions.can?(scope, :view, :device) + refute Permissions.can?(scope, :edit, :device) + refute Permissions.can?(scope, :delete, :device) + end + end + + describe "can?/3 with nil scope" do + test "returns false for nil scope" do + refute Permissions.can?(nil, :view, :device) + refute Permissions.can?(nil, :edit, :device) + refute Permissions.can?(nil, :delete, :device) + end + end + + describe "owner?/1 with various roles" do + test "returns true for superuser" do + user = user_fixture(%{is_superuser: true}) + organization = organization_fixture(user.id) + organization = Repo.preload(organization, :memberships) + + scope = + Scope.for_user(user) + |> Scope.put_organization(organization) + + assert Permissions.owner?(scope) + end + + test "returns true for owner role" do + user = user_fixture() + organization = organization_fixture(user.id) + organization = Repo.preload(organization, :memberships) + + scope = + Scope.for_user(user) + |> Scope.put_organization(organization) + + assert Permissions.owner?(scope) + end + + test "returns false for admin role" do + owner = user_fixture() + organization = organization_fixture(owner.id) + + admin_user = user_fixture() + membership_fixture(organization.id, admin_user.id, :admin) + + organization = Repo.preload(organization, :memberships, force: true) + + scope = + Scope.for_user(admin_user) + |> Scope.put_organization(organization) + + refute Permissions.owner?(scope) + end + + test "returns false for member role" do + owner = user_fixture() + organization = organization_fixture(owner.id) + + member_user = user_fixture() + membership_fixture(organization.id, member_user.id, :member) + + organization = Repo.preload(organization, :memberships, force: true) + + scope = + Scope.for_user(member_user) + |> Scope.put_organization(organization) + + refute Permissions.owner?(scope) + end + + test "returns false for viewer role" do + owner = user_fixture() + organization = organization_fixture(owner.id) + + viewer_user = user_fixture() + membership_fixture(organization.id, viewer_user.id, :viewer) + + organization = Repo.preload(organization, :memberships, force: true) + + scope = + Scope.for_user(viewer_user) + |> Scope.put_organization(organization) + + refute Permissions.owner?(scope) + end + + test "returns false when no organization context" do + user = user_fixture() + scope = Scope.for_user(user) + + refute Permissions.owner?(scope) + end + + test "returns false for nil scope" do + refute Permissions.owner?(nil) + end + + test "works with Socket" do + user = user_fixture() + organization = organization_fixture(user.id) + organization = Repo.preload(organization, :memberships) + + scope = + Scope.for_user(user) + |> Scope.put_organization(organization) + + socket = %Socket{assigns: %{current_scope: scope}} + + assert Permissions.owner?(socket) + end + end + + describe "admin?/1 with various roles" do + test "returns true for superuser" do + user = user_fixture(%{is_superuser: true}) + organization = organization_fixture(user.id) + organization = Repo.preload(organization, :memberships) + + scope = + Scope.for_user(user) + |> Scope.put_organization(organization) + + assert Permissions.admin?(scope) + end + + test "returns true for owner role" do + user = user_fixture() + organization = organization_fixture(user.id) + organization = Repo.preload(organization, :memberships) + + scope = + Scope.for_user(user) + |> Scope.put_organization(organization) + + assert Permissions.admin?(scope) + end + + test "returns true for admin role" do + owner = user_fixture() + organization = organization_fixture(owner.id) + + admin_user = user_fixture() + membership_fixture(organization.id, admin_user.id, :admin) + + organization = Repo.preload(organization, :memberships, force: true) + + scope = + Scope.for_user(admin_user) + |> Scope.put_organization(organization) + + assert Permissions.admin?(scope) + end + + test "returns false for member role" do + owner = user_fixture() + organization = organization_fixture(owner.id) + + member_user = user_fixture() + membership_fixture(organization.id, member_user.id, :member) + + organization = Repo.preload(organization, :memberships, force: true) + + scope = + Scope.for_user(member_user) + |> Scope.put_organization(organization) + + refute Permissions.admin?(scope) + end + + test "returns false for viewer role" do + owner = user_fixture() + organization = organization_fixture(owner.id) + + viewer_user = user_fixture() + membership_fixture(organization.id, viewer_user.id, :viewer) + + organization = Repo.preload(organization, :memberships, force: true) + + scope = + Scope.for_user(viewer_user) + |> Scope.put_organization(organization) + + refute Permissions.admin?(scope) + end + + test "returns false when no organization context" do + user = user_fixture() + scope = Scope.for_user(user) + + refute Permissions.admin?(scope) + end + + test "returns false for nil scope" do + refute Permissions.admin?(nil) + end + + test "works with Socket" do + user = user_fixture() + organization = organization_fixture(user.id) + organization = Repo.preload(organization, :memberships) + + scope = + Scope.for_user(user) + |> Scope.put_organization(organization) + + socket = %Socket{assigns: %{current_scope: scope}} + + assert Permissions.admin?(socket) + end + end +end diff --git a/test/towerops_web/plugs/api_auth_test.exs b/test/towerops_web/plugs/api_auth_test.exs new file mode 100644 index 00000000..8fe8a7f2 --- /dev/null +++ b/test/towerops_web/plugs/api_auth_test.exs @@ -0,0 +1,195 @@ +defmodule ToweropsWeb.Plugs.ApiAuthTest do + use ToweropsWeb.ConnCase, async: true + + import Towerops.AccountsFixtures + import Towerops.OrganizationsFixtures + + alias Towerops.ApiTokens + alias ToweropsWeb.Plugs.ApiAuth + + describe "call/2 with valid authorization" do + setup do + user = user_fixture() + organization = organization_fixture(user.id) + + {:ok, {_token, raw_token}} = + ApiTokens.create_api_token(%{ + organization_id: organization.id, + user_id: user.id, + name: "Test Token" + }) + + %{ + user: user, + organization: organization, + raw_token: raw_token + } + end + + test "authenticates successfully with valid Bearer token", %{ + conn: conn, + raw_token: raw_token, + organization: organization, + user: user + } do + conn = + conn + |> put_req_header("authorization", "Bearer #{raw_token}") + |> ApiAuth.call([]) + + refute conn.halted + assert conn.assigns.current_organization_id == organization.id + assert conn.assigns.current_user.id == user.id + assert conn.assigns.api_authenticated == true + end + + test "authenticates successfully with token without user_id", %{ + conn: conn, + organization: organization + } do + {:ok, {_token, raw_token}} = + ApiTokens.create_api_token(%{ + organization_id: organization.id, + name: "Token Without User" + }) + + conn = + conn + |> put_req_header("authorization", "Bearer #{raw_token}") + |> ApiAuth.call([]) + + refute conn.halted + assert conn.assigns.current_organization_id == organization.id + assert is_nil(conn.assigns.current_user) + assert conn.assigns.api_authenticated == true + end + end + + describe "call/2 with missing authorization" do + test "returns 401 when Authorization header is missing", %{conn: conn} do + conn = ApiAuth.call(conn, []) + + assert conn.halted + assert conn.status == 401 + assert json_response(conn, 401) == %{"error" => "Missing or invalid Authorization header"} + end + + test "returns 401 when Authorization header is empty", %{conn: conn} do + conn = + conn + |> put_req_header("authorization", "") + |> ApiAuth.call([]) + + assert conn.halted + assert conn.status == 401 + assert json_response(conn, 401) == %{"error" => "Missing or invalid Authorization header"} + end + end + + describe "call/2 with invalid authorization format" do + test "returns 401 when Authorization header doesn't start with 'Bearer '", %{conn: conn} do + conn = + conn + |> put_req_header("authorization", "Basic dGVzdDp0ZXN0") + |> ApiAuth.call([]) + + assert conn.halted + assert conn.status == 401 + assert json_response(conn, 401) == %{"error" => "Missing or invalid Authorization header"} + end + + test "returns 401 when Bearer token is malformed", %{conn: conn} do + conn = + conn + |> put_req_header("authorization", "Bearertoken123") + |> ApiAuth.call([]) + + assert conn.halted + assert conn.status == 401 + assert json_response(conn, 401) == %{"error" => "Missing or invalid Authorization header"} + end + + test "returns 401 when authorization has only 'Bearer' with no token", %{conn: conn} do + conn = + conn + |> put_req_header("authorization", "Bearer ") + |> ApiAuth.call([]) + + assert conn.halted + assert conn.status == 401 + assert json_response(conn, 401) == %{"error" => "Invalid or expired API token"} + end + end + + describe "call/2 with invalid token" do + test "returns 401 for non-existent token", %{conn: conn} do + conn = + conn + |> put_req_header("authorization", "Bearer towerops_invalid_token_12345") + |> ApiAuth.call([]) + + assert conn.halted + assert conn.status == 401 + assert json_response(conn, 401) == %{"error" => "Invalid or expired API token"} + end + + test "returns 401 for randomly generated token", %{conn: conn} do + random_token = "towerops_" <> Base.encode64(:crypto.strong_rand_bytes(32)) + + conn = + conn + |> put_req_header("authorization", "Bearer #{random_token}") + |> ApiAuth.call([]) + + assert conn.halted + assert conn.status == 401 + assert json_response(conn, 401) == %{"error" => "Invalid or expired API token"} + end + end + + describe "call/2 with expired token" do + setup do + user = user_fixture() + organization = organization_fixture(user.id) + + # Create an expired token (1 day in the past) + expires_at = DateTime.add(DateTime.utc_now(), -1, :day) + + {:ok, {_token, raw_token}} = + ApiTokens.create_api_token(%{ + organization_id: organization.id, + user_id: user.id, + name: "Expired Token", + expires_at: expires_at + }) + + %{ + user: user, + organization: organization, + expired_token: raw_token + } + end + + test "returns 401 for expired token", %{conn: conn, expired_token: expired_token} do + conn = + conn + |> put_req_header("authorization", "Bearer #{expired_token}") + |> ApiAuth.call([]) + + assert conn.halted + assert conn.status == 401 + assert json_response(conn, 401) == %{"error" => "Invalid or expired API token"} + end + end + + describe "init/1" do + test "returns options unchanged" do + opts = [some: :option] + assert ApiAuth.init(opts) == opts + end + + test "returns empty list unchanged" do + assert ApiAuth.init([]) == [] + end + end +end