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
38 changes: 38 additions & 0 deletions docs/adr/0001-delete-rules-for-system-and-asset-references.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# 0001 Delete rules for system and asset references

**Status:** Proposed (2026-10-07)

## Context

Assets and threats can reference a system, and threats can reference an asset. The
database had no delete rule for these references, so a system with assets or threats and
an asset with threats could not be deleted: the delete failed with a foreign key error,
and the page crashed. In production, 18 of 21 systems were in this state.

The migrations from September 2023 had set `on_delete: :delete_all` for both system
references. The consolidation of the migrations in February 2024 lost these rules.

## Decision

- Deleting a **system** deletes its assets and its threats (`on_delete: :delete_all` for
`assets.system_id` and `threats.system_id`). This restores the original rule.
- Deleting an **asset** keeps its threats and clears the reference
(`on_delete: :nilify_all` for `threats.asset_id`). A threat belongs to the organisation
and may also belong to a system; the asset is one aspect of it.

The rules live in the database, not in application code, so every delete path behaves
the same.

## Consequences

- A system delete can remove many entities, with their risks and mitigations. The user
interface asks for a confirmation already; the text should name the effect.
- After an asset delete, its former threats show no asset.

## Rejected alternatives

- **Clear the reference for all three columns.** Keeps all data, but leaves assets and
threats that belong to no system, which the pages do not present well, and it differs
from the original design.
- **Delete children in application code.** Would need the same logic in every delete
path and would not protect against direct database changes.
13 changes: 12 additions & 1 deletion docs/plans/backlog.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Backlog

**Status:** open list. Last updated 2026-10-06.
**Status:** open list. Last updated 2026-10-07.

Short entries for open work without a plan of its own. When work on an entry starts and
needs steps, it gets its own file in this folder and is removed from here.
Expand Down Expand Up @@ -52,3 +52,14 @@ that consists of sub-systems, which contain services.

Open points: the number of levels and their names, and how assets and threats relate to
a component and to its parent system.

## Upgrade PostgreSQL in production

Production runs PostgreSQL 15.18 (Cloud SQL instance `threatshield-db`, checked on
2026-10-07). The repository uses 18 everywhere: CI, Docker Compose, the Kubernetes files,
and `deployment/gcp/create_database.py`. So the tests run against a newer major version
than production.

Upgrade the instance to 18 with an in-place major version upgrade of Cloud SQL. Take a
backup first and check that automated backups are enabled. Until then, consider running
the tests against 15 as well.
3 changes: 3 additions & 0 deletions lib/threat_shield/accounts/organisation.ex
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ defmodule ThreatShield.Accounts.Organisation do
:attributes
])
|> validate_required([:name])
|> validate_length(:name, max: 255)
|> validate_length(:location, max: 255)
|> DynamicAttribute.validate_values(:attributes)
end

def attributes() do
Expand Down
4 changes: 3 additions & 1 deletion lib/threat_shield/accounts/user.ex
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ defmodule ThreatShield.Accounts.User do
"""
def registration_changeset(user, attrs, opts \\ []) do
user
|> cast(attrs, [:email, :password])
|> cast(attrs, [:email, :password, :first_name, :last_name])
|> validate_length(:first_name, max: 40)
|> validate_length(:last_name, max: 40)
|> validate_email(opts)
|> validate_password(opts)
end
Expand Down
6 changes: 2 additions & 4 deletions lib/threat_shield/ai.ex
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ defmodule ThreatShield.AI do
when is_function(fun, 0) do
case QuotaManager.check_quota(org, @quota_ai_requests_per_month, 1) do
{:ok, :quota_available} ->
Task.start(fn -> protocol_quota_usage(scope, "AI request") end)
{:ok, _usage} = protocol_quota_usage(scope, "AI request")
{:ok, fun.()}

{:error, :quota_exceeded} ->
Expand Down Expand Up @@ -250,14 +250,12 @@ defmodule ThreatShield.AI do
# Quotas

defp protocol_quota_usage(%Scope{} = scope, message) do
QuotaManager.add_usage_async(
QuotaManager.add_usage(
scope.organisation,
scope.user,
@quota_ai_requests_per_month,
1.0,
message
)

{:ok, :usage_recorded}
end
end
4 changes: 2 additions & 2 deletions lib/threat_shield/assets.ex
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ defmodule ThreatShield.Assets do
|> Organisation.for_user(user_id, :create_asset)
|> Repo.one!()

Repo.insert!(changeset)
Repo.insert_or_rollback(changeset)
|> Repo.reload!()
|> Repo.preload(:system)
end)
Expand All @@ -90,7 +90,7 @@ defmodule ThreatShield.Assets do
|> Asset.for_user(user_id, :edit_asset)
|> Repo.one!()

Repo.update!(changeset)
Repo.update_or_rollback(changeset)
|> Repo.reload!()
|> Repo.preload(:system)
end)
Expand Down
11 changes: 11 additions & 0 deletions lib/threat_shield/assets/asset.ex
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ defmodule ThreatShield.Assets.Asset do
|> cast(attrs, @fields)
|> validate_required([:name, :description, :organisation])
|> validate_length(:name, max: 60)
|> validate_length(:description, max: 4000)
|> validate_number(:criticality_loss, greater_than_or_equal_to: 0, less_than_or_equal_to: 5)
|> validate_number(:criticality_theft, greater_than_or_equal_to: 0, less_than_or_equal_to: 5)
|> validate_number(:criticality_publication,
greater_than_or_equal_to: 0,
less_than_or_equal_to: 5
)
|> validate_number(:criticality_overall,
greater_than_or_equal_to: 0,
less_than_or_equal_to: 5
)
end

def calc_overall_criticality(%__MODULE__{
Expand Down
21 changes: 21 additions & 0 deletions lib/threat_shield/dynamic_attribute.ex
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,27 @@ defmodule ThreatShield.DynamicAttribute do

def get_suggestions(%__MODULE__{sample_values: handcoded_values}), do: handcoded_values

@max_value_length 500

@doc """
Validates the attribute map of a changeset: every value must be a string of at
most #{@max_value_length} characters.
"""
def validate_values(%Ecto.Changeset{} = changeset, field) do
Ecto.Changeset.validate_change(changeset, field, fn _field, attributes ->
if is_map(attributes) and Enum.all?(attributes, &valid_value?/1) do
[]
else
[{field, "must be texts of at most #{@max_value_length} characters"}]
end
end)
end

defp valid_value?({_key, value}) when is_binary(value),
do: String.length(value) <= @max_value_length

defp valid_value?(_), do: false

def init(nil) do
:ets.new(@table, [:set, :public, :named_table])
{:ok, nil}
Expand Down
36 changes: 19 additions & 17 deletions lib/threat_shield/members.ex
Original file line number Diff line number Diff line change
Expand Up @@ -60,21 +60,21 @@ defmodule ThreatShield.Members do
def create_invite(%User{} = actor, %Organisation{id: org_id}, attrs \\ %{}) do
token = generate_token()

case Repo.transaction(fn ->
organisation =
Organisation.get(org_id)
|> Organisation.for_user(actor.id, :invite_new_members)
|> Repo.one!()

%Invite{token: token}
|> Invite.changeset(attrs)
|> Ecto.Changeset.put_assoc(:organisation, organisation)
|> Repo.insert()
end) do
{:ok, {:ok, invite}} -> {:ok, invite}
{:ok, {:error, changeset}} -> {:error, changeset}
{:error, err} -> {:error, err}
end
Repo.transaction(fn ->
organisation =
Organisation.get(org_id)
|> Organisation.for_user(actor.id, :invite_new_members)
|> Repo.one!()

%Invite{token: token}
|> Invite.changeset(attrs)
|> Ecto.Changeset.put_assoc(:organisation, organisation)
|> Repo.insert()
|> case do
{:ok, invite} -> invite
{:error, changeset} -> Repo.rollback(changeset)
end
end)
end

def delete_membership_by_id(%User{} = actor, org_id, membership_id) do
Expand All @@ -101,14 +101,16 @@ defmodule ThreatShield.Members do

def accept_invite(%User{confirmed_at: nil}, _invite_id), do: {:error, :email_not_confirmed}

def accept_invite(%User{email: invitee_email} = invitee, invite_id) do
def accept_invite(%User{} = invitee, invite_id) do
# the address is compared by the database, without regard to case
invite =
Invite.get(invite_id)
|> Invite.where_invitee(invitee)
|> Invite.with_time_limit()
|> Invite.with_organisation()
|> Repo.one()

with %Invite{email: ^invitee_email} <- invite,
with %Invite{} <- invite,
{:ok, :no_member} <- check_membership(invitee, invite.organisation_id) do
convert_to_membership(invitee, invite)
else
Expand Down
4 changes: 4 additions & 0 deletions lib/threat_shield/members/invite.ex
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ defmodule ThreatShield.Members.Invite do
|> validate_required([:email])
|> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces")
|> validate_length(:email, max: 160)
|> unique_constraint([:organisation_id, :email],
error_key: :email,
message: "has already been invited to this organisation"
)
end

def generate_url(%__MODULE__{token: token}) do
Expand Down
28 changes: 12 additions & 16 deletions lib/threat_shield/mitigations.ex
Original file line number Diff line number Diff line change
Expand Up @@ -60,22 +60,18 @@ defmodule ThreatShield.Mitigations do

"""
def create_mitigation(%User{id: user_id}, %Risk{id: risk_id}, attrs \\ %{}) do
case Repo.transaction(fn ->
risk =
Risk.get(risk_id)
|> Risk.for_user(user_id, :create_mitigation)
|> Repo.one!()

%Mitigation{}
|> Mitigation.changeset(attrs)
|> update_implementation_status()
|> Ecto.Changeset.put_assoc(:risk, risk)
|> Repo.insert()
end) do
{:ok, {:error, reason}} -> {:error, reason}
{:ok, {:ok, payload}} -> {:ok, payload}
{:error, rollback} -> {:error, rollback}
end
Repo.transaction(fn ->
risk =
Risk.get(risk_id)
|> Risk.for_user(user_id, :create_mitigation)
|> Repo.one!()

%Mitigation{}
|> Mitigation.changeset(attrs)
|> update_implementation_status()
|> Ecto.Changeset.put_assoc(:risk, risk)
|> Repo.insert_or_rollback()
end)
end

@doc """
Expand Down
5 changes: 5 additions & 0 deletions lib/threat_shield/mitigations/mitigation.ex
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ defmodule ThreatShield.Mitigations.Mitigation do
|> cast(attrs, @fields)
|> validate_required([:name, :description, :is_implemented])
|> validate_length(:name, max: 60)
|> validate_length(:description, max: 4000)
|> validate_length(:implementation_notes, max: 255)
|> validate_length(:verification_method, max: 255)
|> validate_length(:verification_result, max: 255)
|> validate_length(:issue_link, max: 255)
end

import Ecto.Query
Expand Down
33 changes: 13 additions & 20 deletions lib/threat_shield/organisations.ex
Original file line number Diff line number Diff line change
Expand Up @@ -50,25 +50,18 @@ defmodule ThreatShield.Organisations do
end

def create_organisation(attrs \\ %{}, %User{} = current_user) do
case Repo.transaction(fn ->
case %Organisation{}
|> Organisation.changeset(attrs)
|> Repo.insert() do
{:ok, org} ->
%Membership{organisation: org, user: current_user, role: :owner}
|> Membership.changeset(%{})
|> Repo.insert()

{:ok, org}

x ->
x
end
end) do
{:ok, {:ok, org}} -> {:ok, org}
{:ok, {:error, e}} -> {:error, e}
{:error, e} -> e
end
Repo.transaction(fn ->
organisation =
%Organisation{}
|> Organisation.changeset(attrs)
|> Repo.insert_or_rollback()

%Membership{organisation: organisation, user: current_user, role: :owner}
|> Membership.changeset(%{})
|> Repo.insert_or_rollback()

organisation
end)
end

def update_organisation(
Expand All @@ -81,7 +74,7 @@ defmodule ThreatShield.Organisations do
|> Organisation.for_user(user_id, :edit_organisation)
|> Repo.one!()
|> Organisation.changeset(attrs)
|> Repo.update!()
|> Repo.update_or_rollback()
end)
end

Expand Down
21 changes: 4 additions & 17 deletions lib/threat_shield/quotas/quota_manager.ex
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,9 @@ defmodule ThreatShield.Quotas.QuotaManager do
query =
from q in QuotaUsage,
where:
q.organisation_id == ^org.id and q.quota_type == ^quota_type and q.timestamp >= ^start,
select: q
q.organisation_id == ^org.id and q.quota_type == ^quota_type and q.timestamp >= ^start

query
|> Repo.all()
|> Enum.map(& &1.amount)
|> Enum.sum()
Repo.aggregate(query, :sum, :amount) || 0.0
end

def check_quota(%Organisation{} = org, quota_type, amount \\ 1.0) do
Expand All @@ -42,21 +38,12 @@ defmodule ThreatShield.Quotas.QuotaManager do
user: user,
quota_type: quota_type,
amount: amount,
message: message
message: message,
timestamp: DateTime.utc_now()
}
|> Repo.insert()
end

def add_usage_async(
%Organisation{} = org,
%User{} = user,
quota_type,
amount,
message \\ nil
) do
Task.async(fn -> add_usage(org, user, quota_type, amount, message) end)
end

defp start_time(quota_type) when is_atom(quota_type) do
case quota_type do
:ai_requests_per_month -> Timex.shift(Timex.now(), months: -1)
Expand Down
2 changes: 1 addition & 1 deletion lib/threat_shield/quotas/quota_usage.ex
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ defmodule ThreatShield.Quotas.QuotaUsage do
field :quota_type, :string
field :amount, :float, default: 0.0
field :message, :string
field :timestamp, :utc_datetime_usec, default: Timex.now()
field :timestamp, :utc_datetime_usec

belongs_to :organisation, Organisation
belongs_to :user, User
Expand Down
Loading
Loading