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
5 changes: 3 additions & 2 deletions .github/workflows/space.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
# a room in Element), so that someone looks; it changes nothing
#
# The result is the run's summary. The token is the environment matrix's secret MATRIX_ACCESS_TOKEN: the
# access token of the account the space is run as, at level 100 in the space and every room. The environment
# lets only main deploy, so a pull request's code never sees it.
# access token of the account the space is run as, at level 100 in the space and every room, made once by
# python -m matrix_space.login so that it does not expire (README). The environment lets only main deploy, so a
# pull request's code never sees it.
name: Space
on:
push:
Expand Down
18 changes: 14 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,17 +135,27 @@ Each run's summary lists what differed, changed or was posted. Runs of one workf
person's: its token can be replaced without anyone losing their login, and the space's history shows what
the bot did. An owner invites it into the space and every room and raises it to 100 there (Element: Room
settings, Roles & Permissions). The owners stay at 100 themselves and list themselves in `people.yaml`.
2. **Its access token** (Element, signed in as the bot: Settings, Help & About, Access Token; then close that
session without signing out, which would end the token) as the secret `MATRIX_ACCESS_TOKEN` of an
environment `matrix` in this repository's settings, with deployments limited to `main`. A pull request's
code never sees it.
2. **Its access token** as the secret `MATRIX_ACCESS_TOKEN` of an environment `matrix` in this repository's
settings, with deployments limited to `main`. A pull request's code never sees it. An owner makes the token
once, on their own computer, and pipes it straight into the secret:

```sh
uv run python -m matrix_space.login | gh secret set MATRIX_ACCESS_TOKEN --env matrix --repo overpressure/matrix
```

It asks for the bot's account and password and logs in as the device `overpressure-github`, asking for no
refresh token: matrix.org's logins go through MAS, which gives such a login a token without an expiry. The
token Element shows (Settings, Help & About) is no use here: Element renews it, and once copied out it dies
within a day. The helper refuses a token that expires. Running it again replaces the session and its token;
signing the session `overpressure-github` out or changing the bot's password ends the token.
3. **A first run of each workflow by hand** without *apply*: the summaries show what the settings would change
and what would be announced.

## Running it locally

```sh
uv run python -m matrix_space --check # the settings and the icons; no token
uv run python -m matrix_space.login # the bot's token that does not expire (see above)
MATRIX_ACCESS_TOKEN=... uv run python -m matrix_space # what differs, nothing changed
MATRIX_ACCESS_TOKEN=... uv run python -m matrix_space --apply # change it
MATRIX_ACCESS_TOKEN=... uv run python -m matrix_space.announce # what would be announced
Expand Down
26 changes: 23 additions & 3 deletions matrix_space/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ def q(text: str) -> str:
class Api:
"""A client for one account on one homeserver."""

def __init__(self, base: str, token: str) -> None:
"""Talk to the client API at @p base as the account whose access token is @p token."""
def __init__(self, base: str, token: str | None) -> None:
"""Talk to the client API at @p base as the account whose access token is @p token (None: to log in)."""
self.base = base.rstrip("/")
self._token = token
self.txn = int(time.time() * 1000)
Expand All @@ -52,7 +52,8 @@ def call( # noqa: PLR0913 # one request's parts
data = raw if raw is not None else None if body is None else json.dumps(body).encode()
for _ in range(10):
request = urllib.request.Request(url, data=data, method=method) # noqa: S310 # the configured https homeserver
request.add_header("Authorization", "Bearer " + self._token)
if self._token:
request.add_header("Authorization", "Bearer " + self._token)
if data is not None:
request.add_header("Content-Type", content_type)
try:
Expand All @@ -78,6 +79,25 @@ def call( # noqa: PLR0913 # one request's parts
message = f"{method} {path}: still rate-limited"
raise MatrixError(message)

def login(self, user: str, password: str, device_id: str, display_name: str) -> dict[str, Any]:
"""Log in with a password as device @p device_id and return the server's answer (no refresh token asked for).

A server whose logins go through MAS gives such a login a token that does not expire; a login that asks
for a refresh token gets one that does. The same device ID ends that device's earlier session.
"""
body = {
"type": "m.login.password",
"identifier": {"type": "m.id.user", "user": user},
"password": password,
"device_id": device_id,
"initial_device_display_name": display_name,
}
return self.call("POST", "/login", body)

def logout(self) -> None:
"""End this token's session."""
self.call("POST", "/logout", {})

def whoami(self) -> str:
"""Return the account's user ID."""
return self.call("GET", "/account/whoami")["user_id"]
Expand Down
119 changes: 119 additions & 0 deletions matrix_space/login.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# SPDX-License-Identifier: Unlicense
"""Log the bot in once and print an access token that does not expire, for the workflows' secret.

uv run python -m matrix_space.login | gh secret set MATRIX_ACCESS_TOKEN --env matrix --repo overpressure/matrix

It asks for the bot's account and password (the password is not shown and goes nowhere but the login), logs
in with a password as the device overpressure-github, and prints the token alone on standard output, so it can
go straight into the secret without appearing on screen. Everything else goes to standard error.

matrix.org's logins go through MAS: a password login that asks for no refresh token gets a token without an
expiry, while Element's own session token is renewed by Element and dies within a day once copied out. The
helper refuses an expiring token and ends its session. Logging in again as the same device ends the session
of the token before it; so does signing that session out, or changing the bot's password.
"""

from __future__ import annotations

import argparse
import getpass
import os
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Any, Protocol

from matrix_space.api import Api, MatrixError
from matrix_space.config import ConfigError, load

if TYPE_CHECKING:
from collections.abc import Callable

#: The settings, next to this package.
CONFIG = Path(__file__).resolve().parent.parent / "config"
#: The device the workflows' session is: logging in again as it replaces that session.
DEVICE_ID = "overpressure-github"
DISPLAY_NAME = "overpressure's GitHub workflows"
FAILED = 1


class Client(Protocol):
"""What the helper needs of the server: matrix_space.api.Api, or the tests' fake."""

def login(self, user: str, password: str, device_id: str, display_name: str) -> dict[str, Any]:
"""Log in and return the server's answer."""
...

def logout(self) -> None:
"""End the session."""
...

def whoami(self) -> str:
"""Return the account's user ID."""
...


def log_in(connect: Callable[[str | None], Client], user: str, password: str, device_id: str) -> str:
"""Log @p user in as @p device_id and return a token that does not expire; refuse any other.

@p connect returns a client for a token (None to log in). The token is checked by asking whose it is.
"""
reply = connect(None).login(user, password, device_id, DISPLAY_NAME)
token = str(reply.get("access_token") or "")
if not token:
message = "the server's answer has no access token"
raise MatrixError(message)
session = connect(token)
if "expires_in_ms" in reply or reply.get("refresh_token"):
session.logout() # a token that expires is of no use to the workflows
message = (
"the server gave a token that expires (expires_in_ms or a refresh token in its answer); "
"its session is ended, and nothing is printed"
)
raise MatrixError(message)
owner = session.whoami()
if owner != reply.get("user_id"):
message = f"the new token belongs to {owner}, not {reply.get('user_id')}"
raise MatrixError(message)
return token


def main(
argv: list[str] | None = None,
*,
ask: Callable[[str], str] = getpass.getpass,
connect: Callable[[str | None], Client] | None = None,
) -> int:
"""Log in, check the token and print it; @p ask and @p connect are the tests' way in."""
parser = argparse.ArgumentParser(prog="python -m matrix_space.login", description=__doc__.split("\n\n")[0])
parser.add_argument("--user", help="the bot's account, e.g. @overpressure-goggles:matrix.org (default: asked)")
parser.add_argument("--device", default=DEVICE_ID, help=f"the session's device ID (default: {DEVICE_ID})")
parser.add_argument("--config", type=Path, default=CONFIG, metavar="DIR", help="the settings (default: config/)")
args = parser.parse_args(argv)
try:
if connect is None:
homeserver = os.environ.get("MATRIX_HOMESERVER") or load(args.config).homeserver

def connect(token: str | None) -> Client:
return Api(homeserver, token)

if args.user:
user = args.user
else:
print("The bot's account (e.g. @overpressure-goggles:matrix.org): ", end="", file=sys.stderr, flush=True)
user = sys.stdin.readline().strip()
password = ask("Its password (not shown): ")
token = log_in(connect, user, password, args.device)
except (ConfigError, MatrixError) as e:
print(f"error: {e}", file=sys.stderr)
return FAILED
print(token)
print(
f"Logged in as the device {args.device}: the token on standard output does not expire. It belongs in the "
"secret MATRIX_ACCESS_TOKEN of the environment matrix (piped into gh secret set, it never shows).",
file=sys.stderr,
)
return 0


if __name__ == "__main__":
sys.exit(main())
106 changes: 106 additions & 0 deletions tests/test_login.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# SPDX-License-Identifier: Unlicense
"""The one-time login: a token that does not expire, refused otherwise, printed alone on standard output."""

from __future__ import annotations

import contextlib
import io
import unittest
from typing import Any
from unittest.mock import patch

from matrix_space import login
from matrix_space.api import MatrixError

USER = "@bot:matrix.org"


class FakeLoginServer:
"""A homeserver's login, logout and whoami, with what the tests make it answer."""

def __init__(self, reply: dict[str, Any] | None = None) -> None:
self.reply = {"user_id": USER, "access_token": "mct_new", "device_id": login.DEVICE_ID, **(reply or {})}
self.logins: list[tuple[str, str, str]] = []
self.logged_out: list[str] = []
self.owner = USER

def connect(self, token: str | None) -> FakeClient:
return FakeClient(self, token)


class FakeClient:
"""One connection to the fake server, as one token (None: not logged in)."""

def __init__(self, server: FakeLoginServer, token: str | None) -> None:
self.server = server
self.token = token

def login(self, user: str, password: str, device_id: str, display_name: str) -> dict[str, Any]: # noqa: ARG002 # Api's signature
if self.token is not None:
message = "logged in already"
raise AssertionError(message)
if password != "pw-7f3a": # noqa: S105 # the test's password
message = "POST /login: 403 M_FORBIDDEN Invalid username or password"
raise MatrixError(message)
self.server.logins.append((user, password, device_id))
return dict(self.server.reply)

def logout(self) -> None:
self.server.logged_out.append(str(self.token))

def whoami(self) -> str:
return self.server.owner


class LoginTests(unittest.TestCase):
def run_main(self, server: FakeLoginServer, argv: list[str], password: str = "pw-7f3a") -> tuple[int, str, str]: # noqa: S107 # the test's password
out, err = io.StringIO(), io.StringIO()
with (
contextlib.redirect_stdout(out),
contextlib.redirect_stderr(err),
patch("sys.stdin", io.StringIO(USER + "\n")),
):
code = login.main(argv, ask=lambda _prompt: password, connect=server.connect)
return code, out.getvalue(), err.getvalue()

def test_prints_only_the_token_on_standard_output(self):
server = FakeLoginServer()
code, out, err = self.run_main(server, [])
self.assertEqual(code, 0)
self.assertEqual(out, "mct_new\n") # alone, so it can be piped into gh secret set
self.assertNotIn("pw-7f3a", out + err)
self.assertIn("does not expire", err)
self.assertEqual(server.logins, [(USER, "pw-7f3a", "overpressure-github")])
self.assertEqual(server.logged_out, [])

def test_takes_the_account_and_the_device_from_the_command_line(self):
server = FakeLoginServer()
code, _out, _err = self.run_main(server, ["--user", "@other:matrix.org", "--device", "test-device"])
self.assertEqual(code, 0)
self.assertEqual(server.logins, [("@other:matrix.org", "pw-7f3a", "test-device")])

def test_refuses_an_expiring_token_and_ends_its_session(self):
for reply in ({"expires_in_ms": 300000}, {"refresh_token": "mcr_x"}):
with self.subTest(reply):
server = FakeLoginServer(reply)
code, out, err = self.run_main(server, [])
self.assertEqual(code, login.FAILED)
self.assertEqual(out, "")
self.assertIn("expires", err)
self.assertEqual(server.logged_out, ["mct_new"])

def test_a_wrong_password_or_a_token_of_another_account_prints_nothing(self):
code, out, err = self.run_main(FakeLoginServer(), [], password="wrong") # noqa: S106 # the test's password
self.assertEqual((code, out), (login.FAILED, ""))
self.assertIn("M_FORBIDDEN", err)
server = FakeLoginServer()
server.owner = "@someone-else:matrix.org"
code, out, err = self.run_main(server, [])
self.assertEqual((code, out), (login.FAILED, ""))
self.assertIn("belongs to @someone-else", err)
server = FakeLoginServer({"access_token": ""})
self.assertEqual(self.run_main(server, [])[:2], (login.FAILED, ""))


if __name__ == "__main__":
unittest.main()