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
68 changes: 68 additions & 0 deletions src/sturnus/application/consent_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,80 @@

from __future__ import annotations

from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from datetime import datetime
from enum import StrEnum
from typing import Protocol

from sturnus.domain.consent import ConsentRecord, is_consent_active


class RoleAssignmentError(Exception):
"""The consent role could not be assigned. `str(exc)` is the reason shown."""


class ConsentWriter(Protocol):
async def record_grant(
self,
*,
discord_user_id: int,
guild_id: int,
policy_version: str,
source: str,
now: datetime,
) -> None: ...


class GrantOutcome(StrEnum):
GRANTED = "granted"
#: The checkbox was not ticked. Nothing was assigned or written.
NOT_CONFIRMED = "not_confirmed"
#: The role could not be assigned, so no grant was written.
ROLE_FAILED = "role_failed"


@dataclass(frozen=True)
class GrantResult:
outcome: GrantOutcome
#: Set only for `ROLE_FAILED`: the reason the role could not be assigned.
reason: str | None = None


async def grant_consent(
*,
discord_user_id: int,
guild_id: int,
policy_version: str,
source: str,
now: datetime,
checkbox_ticked: bool,
assign_role: Callable[[], Awaitable[None]],
consents: ConsentWriter,
) -> GrantResult:
"""The one grant, shared by `/consent grant` and the channel prompt.

The role is assigned first, then the grant is written, so a record never
says consent was given to someone who was not given the role. The
checkbox guard lives here, not in a view: a caller that did not receive an
explicit confirmation cannot make this write.
"""
if not checkbox_ticked:
return GrantResult(GrantOutcome.NOT_CONFIRMED)
try:
await assign_role()
except RoleAssignmentError as exc:
return GrantResult(GrantOutcome.ROLE_FAILED, reason=str(exc))
await consents.record_grant(
discord_user_id=discord_user_id,
guild_id=guild_id,
policy_version=policy_version,
source=source,
now=now,
)
return GrantResult(GrantOutcome.GRANTED)


@dataclass(frozen=True)
class ConsentStatus:
has_role: bool
Expand Down
76 changes: 76 additions & 0 deletions src/sturnus/application/consent_prompt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""Decisions behind the consent prompt posted in a recording channel.

Nothing here touches Discord. `needs_prompt` says which steps a joining
member is still missing, and `PromptRecord` remembers who was already asked
in which channel, so one occupied channel never pings the same person twice.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from datetime import datetime

from sturnus.domain.consent import ConsentRecord, is_consent_active


@dataclass(frozen=True)
class PromptNeeds:
"""Which steps of the prompt a member still has to take."""

consent: bool
link: bool

@property
def any(self) -> bool:
return self.consent or self.link


def needs_prompt(
record: ConsentRecord | None,
*,
linked: bool,
policy_version: str,
now: datetime,
) -> PromptNeeds:
"""Consent is missing unless active; linking is missing unless linked.

Consent and linking are independent (spec: neither use case reads the
other's state). `now` is threaded into `is_consent_active` and never read
here: there is no expiry by elapsed time, only revocation and a changed
policy version.
"""
return PromptNeeds(
consent=not is_consent_active(record, policy_version, now),
link=not linked,
)


#: What the record stores against a (channel, person) pair. Opaque to this
#: module: the Discord layer decides what it is (a message id, typically).
MessageRef = object


@dataclass
class PromptRecord:
"""In-memory set of (channel id, person id) pairs already prompted.

Process-local on purpose: a restart loses it, and the cost is one repeated
ping per person. The optional message reference lets the later
"consented" edit find the prompt it changes.
"""

_entries: dict[tuple[int, int], MessageRef | None] = field(default_factory=dict)

def should_prompt(self, channel_id: int, person_id: int) -> bool:
return (channel_id, person_id) not in self._entries

def mark(self, channel_id: int, person_id: int, message_ref: MessageRef | None = None) -> None:
self._entries[(channel_id, person_id)] = message_ref

def message_ref(self, channel_id: int, person_id: int) -> MessageRef | None:
return self._entries.get((channel_id, person_id))

def clear_channel(self, channel_id: int) -> None:
"""Drops every pair for a channel, called when its last human leaves."""
for key in [key for key in self._entries if key[0] == channel_id]:
del self._entries[key]
53 changes: 53 additions & 0 deletions src/sturnus/application/linking.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,59 @@

import secrets
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Protocol


class LinkedIdentities(Protocol):
"""What `begin_link` reads: the external identity already linked, if any."""

async def external_identity(
self, discord_user_id: int, provider: str | None = None
) -> tuple[str, str] | None: ...


class StateIssuer(Protocol):
"""What `begin_link` writes: a fresh single-use state for one Discord id."""

async def issue(
self, discord_user_id: int, provider: str, now: datetime, ttl: timedelta
) -> str: ...


@dataclass(frozen=True)
class LinkStart:
"""Outcome of starting a link: a new state, or the link already held."""

#: The state to build the authorization URL from, or `None` when the
#: person is already linked and no state was issued.
state: str | None
#: The display name of the existing link, when there is one.
linked_as: str | None


async def begin_link(
discord_user_id: int,
*,
provider: str,
identities: LinkedIdentities,
states: StateIssuer,
now: datetime,
ttl: timedelta,
) -> LinkStart:
"""The `/link start` decision, shared with the channel prompt's link button.

A state is issued only for `discord_user_id`, the person who asked. An
already linked person gets no state: issuing one would strand it unspent.
The caller builds the URL and decides how to show it, and it must reach
the presser alone.
"""
existing = await identities.external_identity(discord_user_id)
if existing is not None:
_, display_name = existing
return LinkStart(state=None, linked_as=display_name)
state = await states.issue(discord_user_id, provider, now, ttl)
return LinkStart(state=state, linked_as=None)


def new_state() -> str:
Expand Down
25 changes: 23 additions & 2 deletions src/sturnus/application/setup_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,23 @@ class ChannelPermissions:
channel_id: int
everyone_may_speak: bool
role_may_speak: bool
#: Whether the bot's own role already has View Channel and Send Messages
#: explicitly allowed here. Without them the consent prompt can be neither
#: seen nor posted in this channel.
bot_role_may_post: bool


@dataclass(frozen=True)
class PermissionChange:
"""One voice-channel permission overwrite that setup needs to apply.

`target` is `"everyone"` or `"consent_role"` -- which Discord role the
change applies to is resolved by the caller, not carried here.
`target` is `"everyone"`, `"consent_role"` or `"bot_role"` -- which Discord
role the change applies to is resolved by the caller, not carried here.

`allow_speak` is set for the Speak overwrites. `allow_view` and
`allow_send` are set only for the bot's own role, which needs View Channel
and Send Messages to post the consent prompt. A field left `None` is not
touched.

`channel_id` says *where*. It has to: the plan now covers every allowed
channel, and the caller applies each change to the channel it names
Expand All @@ -76,6 +85,8 @@ class PermissionChange:
channel_id: int
target: str
allow_speak: bool | None
allow_view: bool | None = None
allow_send: bool | None = None


#: What `/setup` decided about the consent role: an existing stored role was
Expand Down Expand Up @@ -226,6 +237,16 @@ def _maybe_write(key: str, desired: str | None) -> None:
permission_changes.append(
PermissionChange(channel.channel_id, "consent_role", allow_speak=True)
)
if not channel.bot_role_may_post:
permission_changes.append(
PermissionChange(
channel.channel_id,
"bot_role",
allow_speak=None,
allow_view=True,
allow_send=True,
)
)

# Required keys this call supplied itself: either written above or
# already correct, so neither is still open. Derived from what the
Expand Down
72 changes: 71 additions & 1 deletion src/sturnus/entrypoints/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine

from sturnus.application.consent_prompt import PromptRecord
from sturnus.application.ports import Clock
from sturnus.application.publishing import SessionReader, announce_ready_sessions
from sturnus.application.recovery import recover_orphans
Expand All @@ -42,6 +43,11 @@
from sturnus.infrastructure.db.setup_intents import SetupIntentStore
from sturnus.infrastructure.discord.announcer import DiscordAnnouncer
from sturnus.infrastructure.discord.client import SturnusClient
from sturnus.infrastructure.discord.consent_prompt import (
PROMPT_DYNAMIC_ITEMS,
ConsentPromptServices,
count_consent_prompt,
)
from sturnus.infrastructure.discord.link_cog import PROVIDER as OUTLINE_PROVIDER
from sturnus.infrastructure.documents.outline_oauth import OutlineOAuth
from sturnus.infrastructure.health import ReadinessState, start_health_server
Expand Down Expand Up @@ -137,6 +143,56 @@ async def _publish_loop(
await asyncio.wait_for(stop.wait(), timeout=poll_seconds)


def attach_consent_prompt(client: SturnusClient, services: ConsentPromptServices) -> None:
"""Gives the join prompt's buttons their services, and registers the buttons.

Registration happens here, at startup, and not when the first prompt is
posted. A prompt posted before a restart keeps its buttons in Discord, and
only a registered `DynamicItem` answers a press on it.
"""
client.consent_prompt_services = services
client.add_dynamic_items(*PROMPT_DYNAMIC_ITEMS)


def consent_prompt_services(
client: SturnusClient,
*,
config_store: ConfigStore,
consent_repo: ConsentRepository,
account_links: AccountLinkRepository,
link_states: LinkStateStore,
outline_oauth: OutlineOAuth,
clock: Clock,
transcription_host: str,
) -> ConsentPromptServices:
"""The real services for the prompt. The policy and role are read per guild, per press."""

async def policy(guild_id: int) -> tuple[str | None, str | None]:
version = await config_store.get(guild_id, domain_settings.POLICY_VERSION)
url = await config_store.get(guild_id, domain_settings.POLICY_URL)
return version, url

async def consent_role(guild_id: int) -> discord.Role | None:
role_id = await config_store.get(guild_id, domain_settings.CONSENT_ROLE_ID)
guild = client.get_guild(guild_id)
if role_id is None or guild is None:
return None
return guild.get_role(int(role_id))

return ConsentPromptServices(
consents=consent_repo,
links=account_links,
link_states=link_states,
oauth=outline_oauth,
clock=clock,
policy=policy,
transcription_host=transcription_host,
consent_role=consent_role,
prompts=PromptRecord(),
count=count_consent_prompt,
)


async def _wait_for_schema(
engine: AsyncEngine,
timeout_seconds: float = _SCHEMA_WAIT_TIMEOUT_SECONDS,
Expand Down Expand Up @@ -289,10 +345,11 @@ async def database_ping() -> bool:

health_runner = await start_health_server(readiness, settings.health_port)

transcription_host = endpoint_host(settings.transcription_base_url)
client = SturnusClient(
clock=clock,
guild_id=settings.guild_id,
transcription_host=endpoint_host(settings.transcription_base_url),
transcription_host=transcription_host,
config_store=config_store,
admin_mirror=admin_mirror,
directory_mirror=directory_mirror,
Expand All @@ -311,6 +368,19 @@ async def database_ping() -> bool:
account_links=account_links,
capture_diagnostics=settings.capture_diagnostics,
)
attach_consent_prompt(
client,
consent_prompt_services(
client,
config_store=config_store,
consent_repo=consent_repo,
account_links=account_links,
link_states=link_states,
outline_oauth=outline_oauth,
clock=clock,
transcription_host=transcription_host,
),
)

stop = asyncio.Event()
loop = asyncio.get_running_loop()
Expand Down
Loading
Loading