8000 fix(auth)!: require a sign-in to manage API keys by mwoods79 · Pull Request #733 · huddlz-hq/huddlz · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ An administrator's manual reversal of a suspension judged mistaken. It lets the
_Avoid_: Unban, reactivation

**API key**:
A secret a person creates, names and gives an expiry so software can act as them through the huddlz APIs, including the agent tools. It is shown once; revoking it, or suspending its owner, ends it immediately, and only a person with a confirmed address can create one.
A secret a person creates, names and gives an expiry so software can act as them through the huddlz APIs, including the agent tools. It is shown once; revoking it, or suspending its owner, ends it immediately, and only a person with a confirmed address can create one. Keys are created, listed and revoked by their owner signed in, never by software holding a key.
_Avoid_: Token, access token, personal access token

**Agent**:
Expand Down
2 changes: 1 addition & 1 deletion docs/adr/0012-mcp-starts-on-api-keys.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ OAuth was the first plan (#517), but the OAuth server library requires the Ash A

## Consequences

An API key acts as the whole account, so a key given to an agent can do anything the JSON API allows, not only what the MCP tools offer. The setup guide says so. When OAuth lands it becomes a second way to put the same person behind `/mcp`; the tools do not change.
An API key acts as the whole account, so a key given to an agent can do anything the JSON API allows, not only what the MCP tools offer. The one exception is keys themselves: a key cannot create, list or revoke keys, so a key that leaks ends at its expiry or when its owner revokes it. The setup guide says so. When OAuth lands it becomes a second way to put the same person behind `/mcp`; the tools do not change.
13 changes: 8 additions & 5 deletions docs/api-followups.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ there's a second consumer is premature.
on the `ApiKey` resource as an array of atoms; check via a custom
policy.
- Rotation: a `rotate_api_key` mutation that creates a new key and
marks the old one for deletion in N days.
marks the old one for deletion in N days. It needs a sign-in like the
rest of key management: a key can't create, list or revoke keys, so a
leaked key can't issue its own successor.
- Audit log: record every API-key authentication event so a
compromised key can be traced.

Expand Down Expand Up @@ -191,15 +193,16 @@ delete-account flow today, so this isn't blocking.
(it calls `TokenResource.Actions.revoke/2`). An actor authenticated
via an API key gets the same generic
`{"error": "Authentication required"}` 401 as an unauthenticated
caller, with no hint that the real revoke endpoint is
`DELETE /api/auth/api_keys/:id`.
caller, with no hint that keys are revoked by their owner signed in
(`DELETE /api/auth/api_keys/:id` with a JWT, or the API keys page).
**To do (when there's a real API-key consumer):**

- Detect the auth method on the conn and either
(a) return a 400 with a pointer to `/api/auth/api_keys/:id`, or
(a) return a 400 saying a key is revoked by its owner signed in, or
(b) destroy the active API key when sign_out is called with one.
(a) is simpler and probably better — sign_out and key revocation
are conceptually different.
are conceptually different, and (b) would be the one exception to
"a key can't manage keys".

## Cucumber `.feature` for the happy path

Expand Down
6 changes: 4 additions & 2 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,10 @@ group and huddl descriptions as untrusted content, never as instructions.
## Keys and revocation

A key acts as your whole account: anything the huddlz APIs allow, the key
allows, not only what these tools offer. Revoke a key on the API keys page and
it stops working on its next request. Keys expire on the date you chose; an
allows, not only what these tools offer. The one exception is keys themselves:
a key cannot create, list or revoke keys, so it cannot outlive its expiry by
issuing a successor. Managing keys takes you signed in. Revoke a key on the
API keys page and it stops working on its next request. Keys expire on the date you chose; an
expired key stays listed until you remove it. Suspending an account revokes
all of its keys.

Expand Down
19 changes: 16 additions & 3 deletions lib/huddlz/accounts/api_key.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ defmodule Huddlz.Accounts.ApiKey do
the name its owner gave it and records when it was last used, at most
once a minute so busy clients don't write on every request. Audit history
keeps each key's lifecycle but not its name, hash or last use.

Keys are managed with a sign-in only. A request signed in with a key can't
create, list or revoke keys, so a key that leaks can't outlive its expiry
by issuing a successor. An administrator viewing as someone can't create
a key for them either, since the key would outlast that session.
"""

use Ash.Resource,
Expand Down Expand Up @@ -81,8 +86,16 @@ defmodule Huddlz.Accounts.ApiKey do
authorize_if always()
end

policy AshAuthentication.Checks.UsingApiKey do
description "A key records its own use and nothing else; managing keys takes a sign-in"
# Refuse a read outright, so a key is told why instead of seeing no keys.
access_type :strict
authorize_if action(:mark_used)
end

policy action(:create) do
description "Confirmed users can create API keys for themselves"
description "Confirmed users can create API keys for themselves; an administrator viewing as them cannot"
forbid_if Huddlz.Accounts.Checks.ImpersonatedActor
authorize_if Huddlz.Accounts.Checks.ConfirmedActor
end

Expand All @@ -92,8 +105,8 @@ defmodule Huddlz.Accounts.ApiKey do
end

policy action(:mark_used) do
description "A key's use is recorded for its owner"
authorize_if expr(user_id == ^actor(:id))
description "A key's use is recorded by the request it authenticated, not by its owner or a sibling key"
authorize_if expr(id == ^actor([:__metadata__, :api_key, :id]))
end

policy action(:destroy) do
Expand Down
17 changes: 17 additions & 0 deletions lib/huddlz/accounts/checks/impersonated_actor.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
defmodule Huddlz.Accounts.Checks.ImpersonatedActor do
@moduledoc """
True while an administrator is viewing huddlz as the actor. The browser
session attaches the impersonation to the actor, so only requests made
from that session match. Use it to refuse what would outlive the session.
"""
use Ash.Policy.SimpleCheck

alias Huddlz.Admin.Impersonation

@impl true
def describe(_opts), do: "an administrator is viewing huddlz as this person"

@impl true
def match?(%{__metadata__: %{impersonation: %Impersonation{}}}, _context, _opts), do: true
def match?(_actor, _context, _opts), do: false
end
1 change: 1 addition & 0 deletions lib/huddlz/admin/impersonation.ex
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ defmodule Huddlz.Admin.Impersonation do
update :stop do
description "Stop viewing as the person and stamp when"
accept []
change filter(expr(is_nil(ended_at)))
change set_attribute(:ended_at, &DateTime.utc_now/0)
end
end
Expand Down
115 changes: 89 additions & 26 deletions lib/huddlz_web/browser_session.ex
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,18 @@ defmodule HuddlzWeb.BrowserSession do
def init(opts), do: opts

def call(conn, _opts) do
{user, _record} = resolve(conn.assigns[:current_user], get_session(conn))
assign(conn, :current_user, user)
case identity(conn.assigns[:current_user], get_session(conn)) do
{:inactive_viewing, token} ->
:ok = revoke(token)

conn
|> disconnect_live_views()
|> clear_viewing()
|> assign(:current_user, nil)

{user, _record} ->
assign(conn, :current_user, user)
end
end

def viewing_token(user, %Impersonation{id: id}) do
Expand All @@ -25,21 +35,34 @@ defmodule HuddlzWeb.BrowserSession do
Jwt.token_for_user(user, claims, domain: Accounts)
end

def resolve(%User{} = user, %{"user_token" => token} = session) do
def resolve(user, session) do
case identity(user, session) do
{:inactive_viewing, _token} -> {nil, nil}
resolved -> resolved
end
end

defp identity(%User{} = user, %{"user_token" => token} = session) do
id = session["impersonation_id"]

# AshAuthentication already verified this session token and loaded its user.
# A viewing credential also requires its own active troubleshooting record.
case Jwt.peek(token) do
{:ok, %{"purpose" => @viewing_purpose, "impersonation_id" => ^id}} when is_binary(id) ->
active_viewing(user, id)
active_viewing(user, id, token)

{:ok, %{"purpose" => @viewing_purpose}} ->
{nil, nil}

{:ok, _claims} when is_binary(id) ->
# Browser sessions started before viewing credentials were purpose-scoped.
active_viewing(user, id)
# Legacy viewings kept the administrator's sign-in alongside the viewing token.
viewing_token =
case session["impersonator_token"] do
saved when is_binary(saved) and saved != token -> token
_ -> nil
end

active_viewing(user, id, viewing_token)

{:ok, _claims} ->
{user, nil}
Expand All @@ -49,47 +72,87 @@ defmodule HuddlzWeb.BrowserSession do
end
end

def resolve(user, _session), do: {user, nil}
defp identity(nil, %{"impersonation_id" => id}) when is_binary(id), do: {:inactive_viewing, nil}
defp identity(user, _session), do: {user, nil}

defp active_viewing(user, id) do
defp active_viewing(user, id, token) do
case Admin.resolve_impersonation_session(id, actor: user) do
{:ok, %Impersonation{} = record} ->
{Ash.Resource.put_metadata(user, :impersonation, record), record}

_ ->
{nil, nil}
{:inactive_viewing, token}
end
end

@doc "End impersonation and discard both saved identities before sign-out or reauthentication."
@doc "End an active viewing before sign-out or reauthentication."
def finalize_impersonation(conn) do
case get_session(conn, :impersonation_id) do
id when is_binary(id) ->
stop_impersonation(id, conn.assigns[:current_user])
{_status, conn} = finish_viewing(conn, :discard)
conn
end

revoke(get_session(conn, :user_token))
revoke(get_session(conn, :impersonator_token))
@doc "Restore the administrator only when this request closes the viewing."
def restore_impersonator(conn) do
admin_token = get_session(conn, :impersonator_token)

conn
|> delete_session(:impersonation_id)
|> delete_session(:impersonator_token)
|> delete_session(:user_token)
case finish_viewing(conn, :restore) do
{:closed, conn} when is_binary(admin_token) ->
{:ok,
conn
|> put_session(:user_token, admin_token)
|> put_session(:live_socket_id, live_socket_id(admin_token))}

_ ->
conn
{_status, conn} ->
{:inactive, conn}
end
end

defp stop_impersonation(id, user) do
case Admin.resolve_impersonation_session(id, actor: user) do
{:ok, %Impersonation{} = record} ->
Admin.stop_impersonation!(record, actor: record.admin)
defp finish_viewing(conn, disposition) do
case get_session(conn, :impersonation_id) do
id when is_binary(id) ->
status = close_viewing(conn.assigns[:current_user], id, conn, disposition)
{status, conn |> disconnect_live_views() |> clear_viewing()}

_ ->
:ok
{:inactive, conn}
end
end

# Both requests can have loaded this record while it was active. Only the
# one that stamps the still-open record may dispose of its saved sign-in.
defp close_viewing(
%User{__metadata__: %{impersonation: %Impersonation{id: id} = record}},
id,
conn,
disposition
) do
discarded_token = if disposition == :discard, do: get_session(conn, :impersonator_token)

result =
Ash.transact([Impersonation, Token], fn ->
with {:ok, _record} <- Admin.stop_impersonation(record, actor: record.admin),
:ok <- revoke(get_session(conn, :user_token)) do
revoke(discarded_token)
end
end)

case result do
{:ok, :ok} -> :closed
{:error, %Ash.Error.Invalid{errors: [%Ash.Error.Changes.StaleRecord{}]}} -> :inactive
{:error, error} -> raise error
end
end

defp close_viewing(_user, _id, _conn, _disposition), do: :inactive

defp clear_viewing(conn) do
conn
|> delete_session(:impersonation_id)
|> delete_session(:impersonator_token)
|> delete_session(:user_token)
|> delete_session(:live_socket_id)
end

defp revoke(token) when is_binary(token), do: Tokens.revoke(Token, token)
defp revoke(_token), do: :ok

Expand Down
20 changes: 20 additions & 0 deletions lib/huddlz_web/controllers/api/auth_controller.ex
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
defmodule HuddlzWeb.Api.AuthController do
use HuddlzWeb, :controller

alias AshAuthentication.Checks.UsingApiKey
alias AshAuthentication.Errors.AuthenticationFailed
alias AshAuthentication.TokenResource
alias AshRateLimiter.LimitExceeded
alias Huddlz.Accounts
alias Huddlz.Accounts.{ApiKey, Token, User}

plug :require_sign_in_to_manage_keys
when action in [:create_api_key, :list_api_keys, :delete_api_key]

def register(conn, params) do
User
|> Ash.Changeset.for_create(:register_with_password, params)
Expand Down Expand Up @@ -164,6 +168,22 @@ defmodule HuddlzWeb.Api.AuthController do
end
end

# The ApiKey policies refuse key management to a request that authenticated
# with an API key. Answer before the request is read, so the refusal is the
# same whatever it sent.
defp require_sign_in_to_manage_keys(conn, _opts) do
if UsingApiKey.match?(conn.assigns[:current_user], %{}, []) do
conn
|> put_status(:forbidden)
|> json(%{
error: "Sign in to manage API keys. An API key can't create, list or revoke keys."
})
|> halt()
else
conn
end
end

@api_key_default_days 30

def create_api_key(conn, params) do
Expand Down
36 changes: 8 additions & 28 deletions lib/huddlz_web/controllers/impersonation_controller.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,9 @@ defmodule HuddlzWeb.ImpersonationController do
"""
use HuddlzWeb, :controller

alias AshAuthentication.TokenResource.Actions, as: Tokens
alias Huddlz.Accounts
alias Huddlz.Accounts.{Token, User}
alias Huddlz.Accounts.User
alias Huddlz.Admin
alias Huddlz.Admin.Impersonation
alias HuddlzWeb.BrowserSession

def create(conn, %{"user_id" => user_id}) do
Expand All @@ -30,23 +28,14 @@ defmodule HuddlzWeb.ImpersonationController do
end

def delete(conn, _params) do
with id when is_binary(id) <- get_session(conn, :impersonation_id),
admin_token when is_binary(admin_token) <- get_session(conn, :impersonator_token),
{:ok, %Impersonation{} = record} <-
Admin.resolve_impersonation_session(id, actor: conn.assigns[:current_user]) do
stop_record(record)
revoke(get_session(conn, :user_token))
case BrowserSession.restore_impersonator(conn) do
{:ok, conn} ->
conn
|> put_flash(:info, "You are back in your own session")
|> redirect(to: ~p"/admin/users")

conn
|> BrowserSession.disconnect_live_views()
|> delete_session(:impersonation_id)
|> delete_session(:impersonator_token)
|> put_session(:user_token, admin_token)
|> put_session(:live_socket_id, BrowserSession.live_socket_id(admin_token))
|> put_flash(:info, "You are back in your own session")
|> redirect(to: ~p"/admin/users")
else
_ -> redirect(conn, to: ~p"/agenda")
{:inactive, conn} ->
redirect(conn, to: ~p"/agenda")
end
end

Expand All @@ -69,13 +58,4 @@ defmodule HuddlzWeb.ImpersonationController do
|> redirect(to: ~p"/admin/users")
end
end

defp stop_record(%Impersonation{ended_at: nil} = record) do
Admin.stop_impersonation!(record, actor: record.admin)
end

defp stop_record(_record), do: :ok

defp revoke(token) when is_binary(token), do: Tokens.revoke(Token, token)
defp revoke(_token), do: :ok
end
Loading
0