1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Plugs.OAuthPlugTest do
6 use Pleroma.Web.ConnCase, async: true
8 alias Pleroma.Helpers.AuthHelper
9 alias Pleroma.Web.OAuth.Token
10 alias Pleroma.Web.OAuth.Token.Strategy.Revoke
11 alias Pleroma.Web.Plugs.OAuthPlug
14 import Pleroma.Factory
16 setup %{conn: conn} do
18 {:ok, oauth_token} = Token.create(insert(:oauth_app), user)
19 %{user: user, token: oauth_token, conn: conn}
22 test "it does nothing if a user is assigned", %{conn: conn} do
23 conn = assign(conn, :user, %Pleroma.User{})
24 ret_conn = OAuthPlug.call(conn, %{})
26 assert ret_conn == conn
29 test "with valid token (uppercase) in auth header, it assigns the user", %{conn: conn} = opts do
32 |> put_req_header("authorization", "BEARER #{opts[:token].token}")
33 |> OAuthPlug.call(%{})
35 assert conn.assigns[:user] == opts[:user]
38 test "with valid token (downcase) in auth header, it assigns the user", %{conn: conn} = opts do
41 |> put_req_header("authorization", "bearer #{opts[:token].token}")
42 |> OAuthPlug.call(%{})
44 assert conn.assigns[:user] == opts[:user]
47 test "with valid token (downcase) in url parameters, it assigns the user", opts do
50 |> build_conn("/?access_token=#{opts[:token].token}")
51 |> put_req_header("content-type", "application/json")
52 |> fetch_query_params()
53 |> OAuthPlug.call(%{})
55 assert conn.assigns[:user] == opts[:user]
58 test "with valid token (downcase) in body parameters, it assigns the user", opts do
61 |> build_conn("/api/v1/statuses", access_token: opts[:token].token, status: "test")
62 |> OAuthPlug.call(%{})
64 assert conn.assigns[:user] == opts[:user]
67 test "with invalid token, it does not assign the user", %{conn: conn} do
70 |> put_req_header("authorization", "bearer TTTTT")
71 |> OAuthPlug.call(%{})
73 refute conn.assigns[:user]
76 describe "with :oauth_token in session, " do
77 setup %{token: oauth_token, conn: conn} do
81 signing_salt: "cooldude"
86 |> Session.call(Session.init(session_opts))
88 |> AuthHelper.put_session_token(oauth_token.token)
93 test "if session-stored token matches a valid OAuth token, assigns :user and :token", %{
98 conn = OAuthPlug.call(conn, %{})
100 assert conn.assigns.user && conn.assigns.user.id == user.id
101 assert conn.assigns.token && conn.assigns.token.id == oauth_token.id
104 test "if session-stored token matches an expired OAuth token, does nothing", %{
108 expired_valid_until = NaiveDateTime.add(NaiveDateTime.utc_now(), -3600 * 24, :second)
111 |> Ecto.Changeset.change(valid_until: expired_valid_until)
112 |> Pleroma.Repo.update()
114 ret_conn = OAuthPlug.call(conn, %{})
115 assert ret_conn == conn
118 test "if session-stored token matches a revoked OAuth token, does nothing", %{
122 Revoke.revoke(oauth_token)
124 ret_conn = OAuthPlug.call(conn, %{})
125 assert ret_conn == conn