Skip to content
Open
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
4 changes: 4 additions & 0 deletions pipeline/bot/manifests/nemo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ features:
description: Look up members and mentions, add notes, open cases, set slow mode, purge messages
usage_hint: help | queue | lookup @member | mentions @member | note @member | open @member | shush @member 3d | unshush @member | channelban @member #channel 3d | unban @member #channel | slowmode #channel 30s 2h | purge #channel 50 | readonly #channel on | accountage #channel 7d | botallow #channel on | 3864
should_escape: true
- command: /publicize
description: Make this private channel public (admins, channel managers, creators)
should_escape: false

oauth_config:
redirect_urls:
Expand All @@ -37,6 +40,7 @@ oauth_config:
user:
- admin
- admin.analytics:read
- admin.conversations:write
- admin.roles:read
- admin.conversations:read
- admin.teams:read
Expand Down
3 changes: 2 additions & 1 deletion pipeline/bot/nemo/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from slack_bolt import App
from slack_sdk import WebClient

from bot.nemo import command, handlers, surface
from bot.nemo import command, handlers, publicize, surface
from bot.nemo.enforcement import ( # noqa: F401
account_age,
channel_ban,
Expand Down Expand Up @@ -50,5 +50,6 @@ def build(on_reply=None):
)
handlers.register(app, on_reply)
command.register(app)
publicize.register(app)
surface.register(app)
return app
137 changes: 137 additions & 0 deletions pipeline/bot/nemo/publicize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import logging
import os

from bot.core import audit, privileged, session

log = logging.getLogger("bot.nemo.publicize")

COMMAND = "/publicize"
CHANNEL_MANAGER_ROLE = "Rl0A"
MANAGER_TTL = "1 hour"
PAGE_CAP = 20

ALREADY_PUBLIC = ":neocat: this channel already public"
REFUSED = ":bleh: sorry it doesnt appear you're an admin, the cm, or the creator"
DONE = ":kitty-wow: meoww ur channel public now :3"
FAILED = "Couldn't convert this channel. Try again, or ping an admin."


def call(method, params):
return privileged.proxy().call(method, params, credential="admin", max_retries=1) or {}


def channel_info(channel_id):
try:
channel = call("conversations.info", {"channel": channel_id}).get("channel") or {}
return channel.get("is_private") is not False, channel.get("creator")
except Exception as failure: # noqa: BLE001
log.info("publicize: cannot read %s, trying admin search: %s", channel_id, failure)
return search_channel(channel_id)


def search_channel(channel_id):
"""Admin search sees every channel in the org, member or not."""
try:
found = call("admin.conversations.search", {"query": channel_id, "limit": 10})
except Exception as failure: # noqa: BLE001
log.info("publicize: admin search failed for %s, assuming private: %s", channel_id, failure)
return True, None
for channel in found.get("conversations") or []:
if channel.get("id") == channel_id:
return channel.get("is_private") is not False, channel.get("creator_id")
return True, None


def is_admin(user_id):
user = privileged.profile(user_id) or {}
return any(user.get(flag) for flag in ("is_admin", "is_owner", "is_primary_owner"))


def role_id():
return os.environ.get("SLACK_CHANNEL_MANAGER_ROLE_ID", "").strip() or CHANNEL_MANAGER_ROLE


FRESH_MANAGERS = f"""
SELECT array(SELECT user_id FROM api.channel_manager WHERE channel_id = %s)
FROM api.channel_sweep WHERE channel_id = %s AND synced_at > now() - interval '{MANAGER_TTL}'
"""


def cached_managers(channel_id):
"""The managers the web API's channel-manager check cached, if fresh."""
with session() as conn:
row = conn.execute(FRESH_MANAGERS, (channel_id, channel_id)).fetchone()
return set(row[0]) if row else None


def fetch_managers(channel_id):
managers, cursor = set(), None
for _ in range(PAGE_CAP):
page = call("admin.roles.listAssignments",
{"role_ids": role_id(), "entity_ids": channel_id, "limit": 200, "cursor": cursor})
managers |= {row["user_id"] for row in page.get("role_assignments") or []
if row.get("entity_id") == channel_id and row.get("user_id")}
cursor = (page.get("response_metadata") or {}).get("next_cursor")
if not cursor:
break
return managers


def store_managers(channel_id, managers):
with session() as conn:
conn.execute("DELETE FROM api.channel_manager WHERE channel_id = %s", (channel_id,))
for user in managers:
conn.execute("INSERT INTO api.channel_manager (channel_id, user_id) VALUES (%s, %s)",
(channel_id, user))
conn.execute(
"INSERT INTO api.channel_sweep (channel_id, synced_at, managers) VALUES (%s, now(), %s) "
"ON CONFLICT (channel_id) DO UPDATE SET synced_at = now(), managers = EXCLUDED.managers",
(channel_id, len(managers)))


def channel_managers(channel_id):
"""Same source as the /api/v1/channels/{id}/managers/{user} check."""
cached = cached_managers(channel_id)
if cached is not None:
return cached
managers = fetch_managers(channel_id)
store_managers(channel_id, managers)
return managers


def may_publicize(user_id, channel_id, creator):
if is_admin(user_id):
return True
managers = channel_managers(channel_id)
if managers:
return user_id in managers
return creator == user_id


def publicize(user_id, channel_id):
is_private, creator = channel_info(channel_id)
if not is_private:
return ALREADY_PUBLIC
if not may_publicize(user_id, channel_id, creator):
return REFUSED
try:
call("admin.conversations.convertToPublic", {"channel_id": channel_id})
except Exception as failure: # noqa: BLE001
log.warning("publicize: could not convert %s: %s", channel_id, failure)
return FAILED
with session() as conn:
audit.record(conn, "channel", 0, "publicized", user_id, after={"channel_id": channel_id})
log.info("publicize: %s made %s public", user_id, channel_id)
return DONE


def register(app):
@app.command(COMMAND)
def on_publicize(ack, command, respond):
ack()
try:
text = publicize(command["user_id"], command["channel_id"])
except Exception:
log.exception("publicize: failed for %s", command.get("channel_id"))
text = FAILED
respond(text=text, response_type="ephemeral")
2 changes: 1 addition & 1 deletion pipeline/tests/test_nemo_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ def test_build_listener_executor_has_16_workers(monkeypatch):
app_kwargs = {}
monkeypatch.setenv("NEMO_BOT_TOKEN", "xoxb-test")
monkeypatch.setattr(nemo_app, "App", lambda **kwargs: app_kwargs.update(kwargs) or object())
for module in (nemo_app.handlers, nemo_app.command, nemo_app.surface):
for module in (nemo_app.handlers, nemo_app.command, nemo_app.publicize, nemo_app.surface):
monkeypatch.setattr(module, "register", lambda *args: None)

nemo_app.build()
Expand Down
141 changes: 141 additions & 0 deletions pipeline/tests/test_publicize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import contextlib

import pytest

from bot.core import privileged
from bot.nemo import publicize

CHANNEL = "C1"
USER = "U1"


class Proxy:
def __init__(self, info=None, managers=(), fail=(), found=()):
self.info = info
self.found = list(found)
self.managers = list(managers)
self.fail = set(fail)
self.calls = []

def call(self, method, params, **_):
self.calls.append(method)
if method in self.fail:
raise RuntimeError(f"{method} failed: channel_not_found")
if method == "conversations.info":
return {"channel": self.info}
if method == "admin.conversations.search":
return {"conversations": self.found}
if method == "admin.roles.listAssignments":
return {"role_assignments": [{"entity_id": params["entity_ids"], "user_id": user}
for user in self.managers]}
return {"ok": True}


class Db:
def __init__(self, cached):
self.cached = cached
self.sql = []

def execute(self, sql, params=()):
self.sql.append((sql, params))
row = (list(self.cached),) if self.cached is not None and "SELECT" in sql else None
return type("Result", (), {"fetchone": lambda _self: row})()


@pytest.fixture
def setup(monkeypatch):
audited = []

def build(info=None, managers=(), admin=False, fail=(), found=(), cached=None):
proxy = Proxy(info, managers, fail, found)
db = Db(cached)

@contextlib.contextmanager
def session():
yield db

monkeypatch.setattr(privileged, "proxy", lambda: proxy)
monkeypatch.setattr(privileged, "profile", lambda user_id: {"is_admin": admin})
monkeypatch.setattr(publicize, "session", session)
monkeypatch.setattr(publicize.audit, "record", lambda *args, **kwargs: audited.append(args))
return proxy, audited

return build


def converted(proxy):
return "admin.conversations.convertToPublic" in proxy.calls


def test_already_public_does_nothing(setup):
proxy, _ = setup(info={"is_private": False})
assert publicize.publicize(USER, CHANNEL) == publicize.ALREADY_PUBLIC
assert not converted(proxy)


def test_admin_converts_and_is_audited(setup):
proxy, audited = setup(info={"is_private": True}, admin=True)
assert publicize.publicize(USER, CHANNEL) == publicize.DONE
assert converted(proxy)
assert audited[0][1:5] == ("channel", 0, "publicized", USER)


def test_channel_manager_converts(setup):
proxy, _ = setup(info={"is_private": True, "creator": "U2"}, managers=[USER])
assert publicize.publicize(USER, CHANNEL) == publicize.DONE
assert converted(proxy)


def test_creator_refused_when_channel_has_other_managers(setup):
proxy, _ = setup(info={"is_private": True, "creator": USER}, managers=["U2"])
assert publicize.publicize(USER, CHANNEL) == publicize.REFUSED
assert not converted(proxy)


def test_creator_converts_when_no_managers(setup):
proxy, _ = setup(info={"is_private": True, "creator": USER})
assert publicize.publicize(USER, CHANNEL) == publicize.DONE


def test_member_refused(setup):
proxy, _ = setup(info={"is_private": True, "creator": "U2"})
assert publicize.publicize(USER, CHANNEL) == publicize.REFUSED
assert not converted(proxy)


def test_unreadable_channel_uses_admin_search_for_creator(setup):
found = [{"id": "C9", "is_private": True, "creator_id": "U9"},
{"id": CHANNEL, "is_private": True, "creator_id": USER}]
proxy, _ = setup(fail={"conversations.info"}, found=found)
assert publicize.publicize(USER, CHANNEL) == publicize.DONE
assert converted(proxy)


def test_unreadable_public_channel_found_by_admin_search(setup):
proxy, _ = setup(fail={"conversations.info"}, found=[{"id": CHANNEL, "is_private": False}])
assert publicize.publicize(USER, CHANNEL) == publicize.ALREADY_PUBLIC
assert not converted(proxy)


def test_unsearchable_channel_is_treated_as_private(setup):
proxy, _ = setup(admin=True, fail={"conversations.info", "admin.conversations.search"})
assert publicize.publicize(USER, CHANNEL) == publicize.DONE
assert converted(proxy)


def test_convert_failure_is_reported(setup):
_, audited = setup(info={"is_private": True}, admin=True, fail={"admin.conversations.convertToPublic"})
assert publicize.publicize(USER, CHANNEL) == publicize.FAILED
assert not audited


def test_fresh_cached_managers_skip_slack(setup):
proxy, _ = setup(info={"is_private": True, "creator": "U2"}, cached=[USER])
assert publicize.publicize(USER, CHANNEL) == publicize.DONE
assert "admin.roles.listAssignments" not in proxy.calls


def test_cached_empty_managers_fall_back_to_creator(setup):
proxy, _ = setup(info={"is_private": True, "creator": USER}, managers=["U2"], cached=[])
assert publicize.publicize(USER, CHANNEL) == publicize.DONE
assert "admin.roles.listAssignments" not in proxy.calls
8 changes: 7 additions & 1 deletion proxy/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
"conversations.kick",
"admin.users.session.reset",
"admin.users.assign",
"admin.conversations.convertToPublic",
"users.info",
}
| set(SCIM_METHODS)
Expand All @@ -92,10 +93,15 @@
PURGE_READ_METHODS = {
"admin": frozenset({"conversations.history", "conversations.replies", "search.messages"})
}
PUBLICIZE_READ_METHODS = {
"admin": frozenset(
{"conversations.info", "admin.conversations.search", "admin.roles.listAssignments"}
)
}
WEB_FILE_METHODS = FILE_READ_METHODS

NEMO_METHODS = {
"admin": WRITE_METHODS["admin"] | PURGE_READ_METHODS["admin"],
"admin": WRITE_METHODS["admin"] | PURGE_READ_METHODS["admin"] | PUBLICIZE_READ_METHODS["admin"],
"internal": ACTIVITY_METHODS["internal"],
}
WEB_METHODS["internal"] = WEB_METHODS["internal"] | ACTIVITY_METHODS["internal"]
Expand Down
1 change: 1 addition & 0 deletions proxy/budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
("nemo", "admin", "conversations.replies"): (TIER3, 0),
("nemo", "admin", "search.messages"): (TIER2, 0),
("nemo", "admin", "users.info"): (TIER4, 0),
("nemo", "admin", "admin.conversations.convertToPublic"): (TIER2, 0),
("nemo", "admin"): (TIER3, 60),
("nemo", "internal"): (TIER2, 20),
("pipeline", "admin"): (TIER4, 500),
Expand Down
6 changes: 4 additions & 2 deletions proxy/test_clients.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@ def test_conversations_history_not_in_writes():
assert "conversations.history" not in app.WRITES


def test_nemo_admin_reads_limited_to_purge_methods():
def test_nemo_admin_reads_limited_to_purge_and_publicize_methods():
reads = app.NEMO_METHODS["admin"] - app.WRITE_METHODS["admin"]

assert reads == {"conversations.history", "conversations.replies", "search.messages"}
assert reads == {"conversations.history", "conversations.replies", "search.messages",
"conversations.info", "admin.conversations.search",
"admin.roles.listAssignments"}
assert not reads & app.WRITES


Expand Down
Loading
Loading