diff --git a/.github/scripts/forge_release.py b/.github/scripts/forge_release.py index e41647b5d..e875f4795 100644 --- a/.github/scripts/forge_release.py +++ b/.github/scripts/forge_release.py @@ -168,20 +168,37 @@ def diff(old, new): return result +# Where a pending Forge update is accepted. Jira's own Manage apps page has no +# Update for it, so it is never named as the place. +ADMIN_PATH = ( + "Atlassian Administration (admin.atlassian.com): Apps, Sites, choose the site, " + "Connected apps, Coderhelm, View app details, Update" +) + + +def admin_steps(install_url=""): + """The admin's steps, with the installation link first when there is one.""" + if install_url: + return (f"An Atlassian site admin opens the app's installation link ({install_url}), " + f"chooses the site and clicks Update, or uses {ADMIN_PATH}.") + return f"An Atlassian site admin accepts the update in {ADMIN_PATH}." + + def summary_markdown(result): """The run summary text. Holds manifest facts only, never site names.""" lines = ["## Jira app permissions", ""] if result["needs_admin"]: lines += [ - "**A site admin must accept this update in Jira.** The new version asks for:", + "**An Atlassian site admin must accept this update.** The new version asks for:", "", *[f"- {r}" for r in result["reasons"]], "", "Forge rolls out code-only changes by itself, but not new access. On each site,", - "an admin opens **Jira settings (gear) → Apps → Manage apps**, finds **Coderhelm**", - "and clicks **Update**. Until then the site keeps running the previous major version.", + admin_steps() + " Until then the site keeps running the previous major version.", "The workflow also runs `forge install --upgrade` itself; that succeeds only on", - "sites where the Forge token's account is a site admin.", + "sites where the Forge token's account is a site admin. Its refusals elsewhere", + "(\"insufficient permissions\", or a suggestion to install for another product) are", + "about the token's account, not something the site is missing.", ] else: lines.append("No new access. Every site gets this version automatically; no one needs to do anything.") @@ -242,13 +259,24 @@ def latest_version(versions): return ".".join(map(str, max(found))) if found else None -def latest_pointer(versions, manifest, commit="", published_at=""): - """The pointer CoderHelm reads; None when no version is known.""" +INSTALL_LINK = re.compile(r"^https://developer\.atlassian\.com/console/install/[^\s]+$") + + +def latest_pointer(versions, manifest, commit="", published_at="", install_url=""): + """The pointer CoderHelm reads; None when no version is known. + + `install_url` is the app's installation link from the developer console + (Distribution); CoderHelm offers it to site admins as the one-click update. + Anything else is left out. + """ version = latest_version(versions) if not version: return None app_id = str(((manifest or {}).get("app") or {}).get("id") or "") - return {"version": version, "appId": app_id, "commit": commit, "publishedAt": published_at} + out = {"version": version, "appId": app_id, "commit": commit, "publishedAt": published_at} + if install_url and INSTALL_LINK.match(install_url.strip()): + out["installUrl"] = install_url.strip() + return out def load_features(path): @@ -282,8 +310,8 @@ def behind_report(lines, latest, features): return "", "" latest_text = f"latest {latest}" if latest else "latest unknown" md = ["", "## Sites still behind", ""] - md.append("Each one runs an older Coderhelm app until its Jira admin accepts the update:") - md.append("Jira Settings, Apps, Manage apps, Coderhelm, Update. CoderHelm shows the same on the team's Integrations page.") + md.append("Each one runs an older Coderhelm app until a site admin accepts the update.") + md.append(admin_steps() + " CoderHelm shows the same on the team's Integrations page.") md.append("") lacking = [] for i, (major, product) in enumerate(rows, 1): @@ -295,7 +323,7 @@ def behind_report(lines, latest, features): what = f" They lack: {', '.join(lacking)}." if lacking else "" warning = ( f"{len(rows)} installation(s) still run an older Coderhelm app ({latest_text}).{what}" - " A Jira admin on each site must accept the update: Jira Settings, Apps, Manage apps, Coderhelm, Update." + " " + admin_steps() ) return "\n".join(md) + "\n", warning @@ -327,6 +355,7 @@ def main(argv=None): la.add_argument("--manifest", required=True) la.add_argument("--commit", default="") la.add_argument("--published-at", default="") + la.add_argument("--install-url", default="", help="the app's installation link (developer console, Distribution)") be = sub.add_parser("behind", help="summary and warning for installations still behind") be.add_argument("--failed", required=True, help='"majorproduct" lines') @@ -357,7 +386,7 @@ def main(argv=None): if args.cmd == "latest": with open(args.versions, encoding="utf-8") as f: versions = json.load(f) - pointer = latest_pointer(versions, load_manifest(args.manifest), args.commit, args.published_at) + pointer = latest_pointer(versions, load_manifest(args.manifest), args.commit, args.published_at, args.install_url) if not pointer: print("no production version found", file=sys.stderr) return 1 diff --git a/.github/scripts/test_forge_release.py b/.github/scripts/test_forge_release.py index cfde3d71e..55b03f8eb 100644 --- a/.github/scripts/test_forge_release.py +++ b/.github/scripts/test_forge_release.py @@ -58,8 +58,9 @@ def test_widened_scopes_need_admin(self): self.assertTrue(r["needs_admin"]) self.assertEqual(r["scopes_added"], ["write:jira-work"]) md = fr.summary_markdown(r) - self.assertIn("A site admin must accept", md) - self.assertIn("Apps → Manage apps", md) + self.assertIn("An Atlassian site admin must accept", md) + self.assertIn("Atlassian Administration (admin.atlassian.com): Apps, Sites, choose the site, Connected apps, Coderhelm, View app details, Update", md) + self.assertNotIn("Manage apps", md) self.assertIn("write:jira-work", md) def test_removed_scope_still_needs_admin(self): @@ -141,7 +142,9 @@ def test_diff_dry_run_writes_summary_and_json(self): with open(out) as f: self.assertEqual(json.load(f)["scopes_added"], ["read:me"]) with open(summary) as f: - self.assertIn("Manage apps", f.read()) + text = f.read() + self.assertIn("Connected apps", text) + self.assertNotIn("Manage apps", text) def test_summary_from_saved_result(self): with tempfile.TemporaryDirectory() as d: @@ -151,7 +154,7 @@ def test_summary_from_saved_result(self): with open(out, "w") as f: json.dump(r, f) text = self.run_cli("summary", "--json", out) - self.assertIn("A site admin must accept", text) + self.assertIn("An Atlassian site admin must accept", text) self.assertNotIn("no one needs to do anything", text) def test_diff_missing_old_file(self): @@ -170,6 +173,15 @@ def test_pending_lists_only_behind_production_installs(self): self.assertEqual(self.run_cli("pending", "--installs", path), "a.example.net\tjira\t5\n") self.assertEqual(self.run_cli("pending", "--installs", path, "--environment", "staging"), "c.example.net\tjira\t1\n") + def test_the_installation_link_rides_on_the_pointer_and_the_steps(self): + link = "https://developer.atlassian.com/console/install/00000000-0000-0000-0000-000000000002?signature=abc&product=jira" + p = fr.latest_pointer([{"version": "7.0.0"}], {"app": {"id": "ari:x"}}, install_url=link) + self.assertEqual(p["installUrl"], link) + self.assertNotIn("installUrl", fr.latest_pointer([{"version": "7.0.0"}], {}, install_url="https://example.com/x")) + self.assertIn(link, fr.admin_steps(link)) + self.assertIn("Connected apps", fr.admin_steps(link)) + self.assertNotIn("Manage apps", fr.admin_steps() + fr.admin_steps(link)) + def test_latest_pointer_is_the_highest_production_version(self): versions = [{"version": "5.20.0"}, {"version": "6.11.0"}, {"version": "6.9.0"}, {"version": "soon"}] manifest = {"app": {"id": "ari:cloud:ecosystem::app/00000000-0000-0000-0000-000000000001"}} @@ -197,7 +209,8 @@ def test_behind_lists_each_site_by_number_with_what_it_lacks(self): self.assertIn("threaded replies", md) self.assertNotIn("example", md) self.assertTrue(warning.startswith("2 installation(s) still run an older Coderhelm app (latest 6.11.0). They lack: ")) - self.assertIn("Jira Settings, Apps, Manage apps, Coderhelm, Update.", warning) + self.assertIn("Connected apps, Coderhelm, View app details, Update.", warning) + self.assertNotIn("Manage apps", warning + md) self.assertEqual(fr.behind_report([], "6.11.0", features), ("", "")) self.assertEqual(fr.parse_version("6.10"), (6, 10, 0)) self.assertIsNone(fr.parse_version("6.x")) diff --git a/.github/workflows/jira-app-release.yml b/.github/workflows/jira-app-release.yml index f56a34b54..80300be51 100644 --- a/.github/workflows/jira-app-release.yml +++ b/.github/workflows/jira-app-release.yml @@ -178,10 +178,16 @@ jobs: # numbers each deploy, so the version is read back from Forge. - name: Read the released version id: version + env: + # The app's installation link (developer console, Distribution), + # kept as a repository variable: site admins get it as the + # one-click update. + FORGE_INSTALL_URL: ${{ vars.FORGE_INSTALL_URL }} run: | if forge version list --environment production --non-interactive --json > "$RUNNER_TEMP/versions.json" 2> "$RUNNER_TEMP/versions.err" \ && python3 "$RUNNER_TEMP/forge_release.py" latest --versions "$RUNNER_TEMP/versions.json" --manifest manifest.yml \ - --commit "$(git rev-parse HEAD)" --published-at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$RUNNER_TEMP/jira-app.json"; then + --commit "$(git rev-parse HEAD)" --published-at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + --install-url "${FORGE_INSTALL_URL}" > "$RUNNER_TEMP/jira-app.json"; then version=$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["version"])' "$RUNNER_TEMP/jira-app.json") echo "Released version: $version" echo "version=$version" >> "$GITHUB_OUTPUT" @@ -221,7 +227,7 @@ jobs: # Minor versions reach every site by themselves. Installations still # on an older major version are upgraded here; that works on sites # where the token's account is a site admin, and elsewhere waits for - # that site's admin to accept the update in Jira. + # that site's admin to accept the update in Atlassian Administration. forge install list --json > "$RUNNER_TEMP/installs.json" 2> "$RUNNER_TEMP/installs.err" || { echo "::warning::Could not list installations"; echo "listed=false" >> "$GITHUB_OUTPUT"; exit 0; } python3 "$RUNNER_TEMP/forge_release.py" pending --installs "$RUNNER_TEMP/installs.json" > "$RUNNER_TEMP/pending.tsv" @@ -234,10 +240,15 @@ jobs: while IFS=$'\t' read -r site product major; do [ -n "$site" ] || continue echo "::add-mask::$site" + # The CLI's own refusal (insufficient permissions, or advice to + # install for another product) is about the token's account, not + # the site: it stays in the log, quietly, and the summary says + # what the site's admin does. if forge install --upgrade --site "$site" --product "$product" \ - --environment production --non-interactive --confirm-scopes; then + --environment production --non-interactive --confirm-scopes > "$RUNNER_TEMP/upgrade.log" 2>&1; then upgraded=$((upgraded + 1)) else + echo "Not upgraded from CI (the Forge token's account isn't an admin on this site); its admin accepts the update." failed=$((failed + 1)) printf '%s\t%s\n' "$major" "$product" >> "$RUNNER_TEMP/behind.tsv" fi @@ -269,6 +280,7 @@ jobs: RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} FAILED: ${{ steps.upgrade.outputs.failed || '0' }} BEHIND: ${{ steps.upgrade.outputs.warning }} + FORGE_INSTALL_URL: ${{ vars.FORGE_INSTALL_URL }} run: | # The issue holds counts and manifest facts only, never site names. title="Jira app update needs a site admin" @@ -278,7 +290,7 @@ jobs: "$reasons" \ "Installations not upgraded from CI: ${FAILED}." \ "${BEHIND}" \ - "On each site, a Jira admin accepts the update: Jira Settings, Apps, Manage apps, Coderhelm, Update." \ + "$(python3 -c 'import sys;sys.path.insert(0,sys.argv[1]);import forge_release as f;print(f.admin_steps(sys.argv[2]))' "$RUNNER_TEMP" "${FORGE_INSTALL_URL}")" \ "Run: ${RUN_URL}") existing=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open --search "in:title \"$title\"" --json number --jq '.[0].number // empty') if [ -n "$existing" ]; then diff --git a/coderhelm-jira/manifest.yml b/coderhelm-jira/manifest.yml index 12b8d5514..0eaedb8fa 100644 --- a/coderhelm-jira/manifest.yml +++ b/coderhelm-jira/manifest.yml @@ -21,12 +21,8 @@ modules: function: addCommentHandler - key: get-site-url-trigger function: getSiteUrlHandler - - key: publish-release-trigger - function: publishReleaseHandler - key: get-issues-trigger function: getIssuesHandler - - key: confluence-trigger - function: confluenceHandler jira:adminPage: - key: coderhelm-admin-page resource: adminPage @@ -46,12 +42,8 @@ modules: handler: index.addCommentHandler - key: getSiteUrlHandler handler: index.getSiteUrlHandler - - key: publishReleaseHandler - handler: release.publishReleaseHandler - key: getIssuesHandler handler: release.getIssuesHandler - - key: confluenceHandler - handler: confluence.confluenceHandler - key: lifecycleHandler handler: register.lifecycleHandler resources: @@ -63,9 +55,6 @@ permissions: - write:jira-work - storage:app - read:attachment:jira - - read:page:confluence - - read:space:confluence - - write:page:confluence external: fetch: backend: diff --git a/coderhelm-jira/src/confluence-rules.js b/coderhelm-jira/src/confluence-rules.js deleted file mode 100644 index c612f7a5e..000000000 --- a/coderhelm-jira/src/confluence-rules.js +++ /dev/null @@ -1,72 +0,0 @@ -// Pure rules for the Confluence web trigger (no Forge imports, so they can be -// tested with plain Node): which requests are accepted, and how an append -// becomes a page update. - -/** The most markup one append may add (CoderHelm caps the text at 10k chars). */ -const MAX_APPEND_MARKUP = 60000; -/** The longest CQL accepted (CoderHelm's own searches are far shorter). */ -const MAX_CQL = 1000; - -/** A Confluence id: digits only, at most 20 of them. */ -function isId(v) { - return /^\d{1,20}$/.test(String(v === undefined || v === null ? "" : v)); -} - -/** - * Checks one request body and says which Confluence call it maps to, or why - * it is refused. Returns { error } or { op, ... } with only checked values. - */ -function parseRequest(body) { - const op = String(body.op || ""); - switch (op) { - case "whoami": - return { op }; - case "page": - case "space": - case "children": - if (!isId(body.id)) return { error: "id must be a Confluence id (digits)" }; - return { op, id: String(body.id) }; - case "search": { - const cql = typeof body.cql === "string" ? body.cql.trim() : ""; - // Only page searches: CoderHelm always starts its CQL this way. - if (!cql || cql.length > MAX_CQL || !cql.startsWith("type = page")) { - return { error: "cql must be a page search (type = page ...)" }; - } - return { op, cql }; - } - case "append": { - if (!isId(body.id)) return { error: "id must be a Confluence id (digits)" }; - const html = typeof body.html === "string" ? body.html : ""; - if (!html.trim() || html.length > MAX_APPEND_MARKUP) { - return { error: `html must be 1 to ${MAX_APPEND_MARKUP} characters` }; - } - const version = Number(body.version); - if (!Number.isInteger(version) || version < 1) { - return { error: "version must be the page version that was read" }; - } - return { op, id: String(body.id), html, version }; - } - default: - return { error: "unknown op" }; - } -} - -/** - * The page update for an append: the current body with `html` added at the - * end, as the next version. Refuses (returns null) when the page moved past - * the version CoderHelm read, so someone else's newer edit is never lost. - */ -function appendUpdate(page, html, readVersion) { - const current = page && page.version && Number(page.version.number); - if (!current || current !== readVersion) return null; - const old = (page.body && page.body.storage && page.body.storage.value) || ""; - return { - id: String(page.id), - status: "current", - title: page.title, - body: { representation: "storage", value: old + html }, - version: { number: current + 1, message: "Added by Coderhelm" }, - }; -} - -module.exports = { isId, parseRequest, appendUpdate, MAX_APPEND_MARKUP, MAX_CQL }; diff --git a/coderhelm-jira/src/confluence.js b/coderhelm-jira/src/confluence.js deleted file mode 100644 index 62481f842..000000000 --- a/coderhelm-jira/src/confluence.js +++ /dev/null @@ -1,88 +0,0 @@ -// Confluence reads (and one guarded write) for CoderHelm agents, through this -// app's own Confluence access on the site it is installed on. -// -// The CoderHelm backend calls this web trigger with the shared secret the -// admin saved on the settings page (the same check as the release-notes -// triggers). It mirrors exactly what CoderHelm's Confluence connection may do -// with an API token, and nothing more: -// -// whoami - who the app signs in as (the connection check) -// page - one page by id, with its storage body -// space - one space by id (so CoderHelm can check its key) -// search - a CQL search for pages (CoderHelm builds and checks the CQL) -// children - the pages directly under a page -// append - add markup to the END of one page, only when the page is -// still at the version CoderHelm read; never replaces, creates, -// moves or deletes a page -// -// Which pages may be appended to (the team's write switch and page list) is -// decided by CoderHelm before it calls; this trigger adds the version check -// and the "append only" rule on its side. - -const api = require("@forge/api"); -const { route } = api; -const { authorized, json } = require("./release"); -const { parseRequest, appendUpdate } = require("./confluence-rules"); - -// ── Confluence calls ───────────────────────────────────────────────────────── - -/** One Confluence call; returns { status, data } whatever the status. */ -async function call(path, init) { - const res = await api.asApp().requestConfluence(path, init); - const text = await res.text(); - let data = null; - try { - data = text ? JSON.parse(text) : null; - } catch (_) { - data = { message: text.slice(0, 500) }; - } - return { status: res.status, data }; -} - -/** Passes Confluence's answer back with its own status, so CoderHelm can explain it. */ -const answer = ({ status, data }) => json(status, data === null ? {} : data); - -/** - * POST { forge_secret, op, ... } → Confluence's answer (same status and JSON - * as Confluence's REST API gives for that call). - */ -exports.confluenceHandler = async (request) => { - try { - const body = JSON.parse(request.body || "{}"); - // 401, not 403: a 403 means "Confluence won't show the app this page". - if (!(await authorized(body))) return json(401, { error: "forbidden" }); - const req = parseRequest(body); - if (req.error) return json(400, { error: req.error }); - - switch (req.op) { - case "whoami": - return answer(await call(route`/wiki/rest/api/user/current`)); - case "page": - return answer(await call(route`/wiki/api/v2/pages/${req.id}?body-format=storage`)); - case "space": - return answer(await call(route`/wiki/api/v2/spaces/${req.id}`)); - case "children": - return answer(await call(route`/wiki/api/v2/pages/${req.id}/children?limit=50`)); - case "search": - return answer(await call(route`/wiki/rest/api/search?limit=15&cql=${req.cql}`)); - case "append": { - const read = await call(route`/wiki/api/v2/pages/${req.id}?body-format=storage`); - if (read.status < 200 || read.status > 299) return answer(read); - const update = appendUpdate(read.data, req.html, req.version); - if (!update) return json(409, { error: "the page changed since it was read" }); - return answer( - await call(route`/wiki/api/v2/pages/${req.id}`, { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(update), - }) - ); - } - default: - return json(400, { error: "unknown op" }); - } - } catch (e) { - console.error("confluence trigger error:", e); - return json(502, { error: String(e.message || e) }); - } -}; diff --git a/coderhelm-jira/src/register.js b/coderhelm-jira/src/register.js index a77f50170..9dcffb07a 100644 --- a/coderhelm-jira/src/register.js +++ b/coderhelm-jira/src/register.js @@ -26,21 +26,6 @@ async function siteUrl() { return ""; } -/** - * Whether this site has Confluence the app can read. Only then does the - * Confluence trigger get registered, so CoderHelm shows Confluence as - * connected only on sites that have it. - */ -async function hasConfluence() { - try { - const res = await api.asApp().requestConfluence(route`/wiki/api/v2/spaces?limit=1`); - return res.ok; - } catch (e) { - console.log("Confluence isn't reachable on this site:", e); - return false; - } -} - /** * Sends every trigger URL to the gateway for `config` ({ teamId, forgeSecret }). * Returns { urlsRegistered, urlError? }. @@ -53,9 +38,12 @@ async function registerWithGateway(config) { list_projects_url: await webTrigger.getUrl("list-projects-trigger"), create_ticket_url: await webTrigger.getUrl("create-ticket-trigger"), add_comment_url: await webTrigger.getUrl("add-comment-trigger"), - publish_release_url: await webTrigger.getUrl("publish-release-trigger"), + // The app is Jira-only: Confluence (pages for agents, release notes) + // goes through the Atlassian connection in CoderHelm. Empty addresses + // tell CoderHelm this site's app no longer does either. + publish_release_url: "", get_issues_url: await webTrigger.getUrl("get-issues-trigger"), - confluence_trigger_url: (await hasConfluence()) ? await webTrigger.getUrl("confluence-trigger") : "", + confluence_trigger_url: "", site_url: await siteUrl(), // The version that registers: after an accepted update, CoderHelm // knows the site caught up at once. diff --git a/coderhelm-jira/src/release.js b/coderhelm-jira/src/release.js index 7d1eeae95..ed610d9b6 100644 --- a/coderhelm-jira/src/release.js +++ b/coderhelm-jira/src/release.js @@ -1,6 +1,7 @@ -// Release notes: Confluence publishing + Jira lookups for CoderHelm. +// Jira issue lookups for CoderHelm (release notes and Chat). Release notes +// reach Confluence through the Atlassian connection in CoderHelm, not this app. // -// Both web triggers are called by the CoderHelm backend and require the +// The web trigger is called by the CoderHelm backend and require the // shared secret the admin saved on the settings page (same secret the gateway // verifies on forge-register). @@ -19,149 +20,6 @@ async function authorized(body) { return Boolean(config && config.forgeSecret && body.forge_secret === config.forgeSecret); } -// ── Pure helpers (exported for tests) ──────────────────────────────────────── - -/** Anchor macro that marks one CoderHelm entry, so a re-publish replaces it. */ -function anchorFor(entryKey) { - const slug = `coderhelm-${String(entryKey).replace(/[^A-Za-z0-9._-]+/g, "-")}`; - return `${slug}`; -} - -/** - * Put `entryHtml` (marked with its anchor) at the top of the year page — right - * after the page's first

when there is one — or, when the page already has - * this entry, replace it in place. An entry runs from its anchor to the next - * anchor or the next

after its own heading. - */ -function upsertEntry(pageHtml, entryKey, entryHtml) { - const anchor = anchorFor(entryKey); - const block = anchor + entryHtml; - const at = pageHtml.indexOf(anchor); - if (at >= 0) { - const afterAnchor = at + anchor.length; - const ownHeading = pageHtml.indexOf("', afterAnchor); - const nextHeading = ownHeading >= 0 ? pageHtml.indexOf(" i >= 0); - const end = ends.length ? Math.min(...ends) : pageHtml.length; - return pageHtml.slice(0, at) + block + pageHtml.slice(end); - } - const h1 = pageHtml.indexOf("

"); - if (h1 >= 0) { - const cut = h1 + "".length; - return pageHtml.slice(0, cut) + block + pageHtml.slice(cut); - } - return block + pageHtml; -} - -// ── Confluence calls ───────────────────────────────────────────────────────── - -async function confluence(path, init) { - const res = await api.asApp().requestConfluence(path, init); - const text = await res.text(); - let data = null; - try { - data = text ? JSON.parse(text) : null; - } catch (_) { - data = text; - } - if (!res.ok) { - throw new Error(`Confluence ${res.status}: ${typeof data === "string" ? data : JSON.stringify(data)}`.slice(0, 600)); - } - return data; -} - -async function childByTitle(parentId, title) { - let cursor = ""; - for (let i = 0; i < 20; i++) { - const page = await confluence( - cursor - ? route`/wiki/api/v2/pages/${parentId}/children?limit=250&cursor=${cursor}` - : route`/wiki/api/v2/pages/${parentId}/children?limit=250` - ); - const hit = (page.results || []).find((p) => p.title === title); - if (hit) return hit; - const next = page._links && page._links.next; - if (!next) return null; - const m = /cursor=([^&]+)/.exec(next); - if (!m) return null; - cursor = decodeURIComponent(m[1]); - } - return null; -} - -async function findOrCreateChild(spaceId, parentId, title, seedHtml) { - const existing = await childByTitle(parentId, title); - if (existing) return existing.id; - const created = await confluence(route`/wiki/api/v2/pages`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - spaceId, - status: "current", - title, - parentId, - body: { representation: "storage", value: seedHtml }, - }), - }); - return created.id; -} - -/** - * POST { forge_secret, parentId, containerTitle, year, entryKey, entryHtml } - * → { url }. Parent → container ("Changelog") → year page; entry upserted at top. - */ -exports.publishReleaseHandler = async (request) => { - try { - const body = JSON.parse(request.body || "{}"); - if (!(await authorized(body))) return json(403, { error: "forbidden" }); - const { parentId, containerTitle, year, entryKey, entryHtml } = body; - if (!/^\d+$/.test(String(parentId || "")) || !year || !entryKey || !entryHtml) { - return json(400, { error: "parentId, year, entryKey and entryHtml are required" }); - } - const parent = await confluence(route`/wiki/api/v2/pages/${parentId}`); - const spaceId = parent.spaceId; - const container = containerTitle || "Changelog"; - const containerId = await findOrCreateChild( - spaceId, - parentId, - container, - `

${container}

Release notes published by CoderHelm, one page per year.

` - ); - const yearTitle = String(year); - const yearId = await findOrCreateChild(spaceId, containerId, yearTitle, `

${yearTitle}

`); - - // Read → upsert → write, retrying once on a version conflict. - for (let attempt = 0; attempt < 2; attempt++) { - const page = await confluence(route`/wiki/api/v2/pages/${yearId}?body-format=storage`); - const current = (page.body && page.body.storage && page.body.storage.value) || ""; - const next = upsertEntry(current, entryKey, entryHtml); - try { - await confluence(route`/wiki/api/v2/pages/${yearId}`, { - method: "PUT", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - id: yearId, - status: "current", - title: page.title, - body: { representation: "storage", value: next }, - version: { number: page.version.number + 1, message: `Release notes: ${entryKey}` }, - }), - }); - const base = (page._links && page._links.base) || ""; - const webui = (page._links && page._links.webui) || ""; - return json(200, { url: base && webui ? base + webui : "", pageId: yearId }); - } catch (e) { - if (attempt === 1 || !String(e.message).includes("409")) throw e; - } - } - return json(500, { error: "unreachable" }); - } catch (e) { - console.error("publishRelease error:", e); - return json(502, { error: String(e.message || e) }); - } -}; - // ── Issue lookups (release notes and CoderHelm's Chat) ─────────────────────── /** One issue with its remote links; null when it can't be read. */ @@ -224,5 +82,3 @@ exports.getIssuesHandler = async (request) => { exports.authorized = authorized; exports.json = json; -exports.upsertEntry = upsertEntry; -exports.anchorFor = anchorFor; diff --git a/coderhelm-jira/test/confluence-rules.test.js b/coderhelm-jira/test/confluence-rules.test.js deleted file mode 100644 index 1c0d3a899..000000000 --- a/coderhelm-jira/test/confluence-rules.test.js +++ /dev/null @@ -1,61 +0,0 @@ -// Run with `npm test` (plain Node; no Forge runtime needed). -const test = require("node:test"); -const assert = require("node:assert/strict"); -const { parseRequest, appendUpdate, MAX_APPEND_MARKUP } = require("../src/confluence-rules"); - -test("reads take only numeric ids", () => { - assert.deepEqual(parseRequest({ op: "page", id: "42" }), { op: "page", id: "42" }); - assert.deepEqual(parseRequest({ op: "children", id: 42 }), { op: "children", id: "42" }); - assert.ok(parseRequest({ op: "page", id: "42/../1" }).error); - assert.ok(parseRequest({ op: "space", id: "" }).error); - assert.ok(parseRequest({ op: "page" }).error); -}); - -test("searches must be page searches", () => { - const cql = 'type = page AND text ~ "deploy" ORDER BY lastmodified DESC'; - assert.deepEqual(parseRequest({ op: "search", cql }), { op: "search", cql }); - assert.ok(parseRequest({ op: "search", cql: "type = attachment" }).error); - assert.ok(parseRequest({ op: "search", cql: "type = page " + "x".repeat(2000) }).error); - assert.ok(parseRequest({ op: "search" }).error); -}); - -test("only the listed operations exist", () => { - for (const op of ["create", "delete", "move", "update", "", undefined]) { - assert.ok(parseRequest({ op, id: "42" }).error, `op ${op}`); - } -}); - -test("an append needs markup and the version that was read", () => { - assert.deepEqual(parseRequest({ op: "append", id: "42", html: "

x

", version: 3 }), { - op: "append", - id: "42", - html: "

x

", - version: 3, - }); - assert.ok(parseRequest({ op: "append", id: "42", html: "", version: 3 }).error); - assert.ok(parseRequest({ op: "append", id: "42", html: "

x

" }).error); - assert.ok(parseRequest({ op: "append", id: "42", html: "

x

", version: 0 }).error); - assert.ok( - parseRequest({ op: "append", id: "42", html: "x".repeat(MAX_APPEND_MARKUP + 1), version: 3 }).error - ); -}); - -const PAGE = { - id: "42", - title: "Lessons", - version: { number: 3 }, - body: { storage: { value: "

Lessons

one

" } }, -}; - -test("an append keeps the page and adds to its end as the next version", () => { - const u = appendUpdate(PAGE, "

two

", 3); - assert.equal(u.body.value, "

Lessons

one

two

"); - assert.equal(u.version.number, 4); - assert.equal(u.title, "Lessons"); - assert.equal(u.id, "42"); -}); - -test("an append to a page that changed since it was read is refused", () => { - assert.equal(appendUpdate(PAGE, "

two

", 2), null); - assert.equal(appendUpdate({ ...PAGE, version: undefined }, "

two

", 3), null); -}); diff --git a/coderhelm-jira/test/manifest.test.js b/coderhelm-jira/test/manifest.test.js new file mode 100644 index 000000000..00641eaec --- /dev/null +++ b/coderhelm-jira/test/manifest.test.js @@ -0,0 +1,27 @@ +// The Jira app is Jira-only: no Confluence scope, module or call. Confluence +// goes through the Atlassian connection in CoderHelm, so a release of this +// app never asks an admin for access to a second Atlassian product. + +const test = require("node:test"); +const assert = require("node:assert"); +const fs = require("node:fs"); +const path = require("node:path"); + +const root = path.join(__dirname, ".."); +const manifest = fs.readFileSync(path.join(root, "manifest.yml"), "utf8"); + +test("the manifest asks for no Confluence scope", () => { + assert.doesNotMatch(manifest, /confluence/i); + const scopes = manifest.split("scopes:")[1].split("external:")[0]; + assert.deepStrictEqual( + scopes.split("\n").map((l) => l.trim()).filter((l) => l.startsWith("- ")).map((l) => l.slice(2)), + ["read:jira-work", "write:jira-work", "storage:app", "read:attachment:jira"], + ); +}); + +test("no source file calls Confluence", () => { + for (const f of fs.readdirSync(path.join(root, "src"))) { + if (!f.endsWith(".js")) continue; + assert.doesNotMatch(fs.readFileSync(path.join(root, "src", f), "utf8"), /requestConfluence/, f); + } +}); diff --git a/docs/jira-app-release.md b/docs/jira-app-release.md index 6ff9fbbbf..e6c399eb5 100644 --- a/docs/jira-app-release.md +++ b/docs/jira-app-release.md @@ -48,13 +48,15 @@ A major version still deploys. The run then: - runs `forge install --upgrade` itself, which succeeds only on sites where the token's account is a site admin - opens an issue titled "Jira app update needs a site admin" in this repo, or comments on the open one, so GitHub notifies the repo's watchers. The issue gives counts and the changed permissions, never site names. -On every other site, an admin must accept the update. In Jira, they open **Settings (gear) → Apps → Manage apps**, find **Coderhelm** and click **Update**. CI cannot do this for them. When the update is accepted, the app's lifecycle trigger sends the site's web trigger URLs to CoderHelm again, so nobody has to re-save the settings page. +On every other site, an Atlassian site admin must accept the update. Jira's own Manage apps page does not show it. They open **Atlassian Administration** (admin.atlassian.com), then **Apps**, **Sites**, choose the site, **Connected apps**, **Coderhelm**, **View app details** and **Update**. Or, faster, they open the app's installation link (developer console, the app, **Distribution**), choose the site and click **Update**: the release workflow publishes that link when the repository variable `FORGE_INSTALL_URL` holds it, and CoderHelm shows it on the Integrations page. CI cannot do this for them. When the CLI's own upgrade is refused ("insufficient permissions", or advice to install for another product), that is about the Forge token's account, not something the site lacks. + +The app is Jira-only: it asks for `read:jira-work`, `write:jira-work`, `storage:app` and `read:attachment:jira`, and nothing in Confluence (`coderhelm-jira/test/manifest.test.js` holds it to that). Confluence pages for agents, Knowledge and release notes go through the Confluence part of the Atlassian connection in CoderHelm. A release that only changes code is a minor version, which Forge rolls out to every site by itself. When the update is accepted, the app's lifecycle trigger sends the site's web trigger URLs to CoderHelm again, so nobody has to re-save the settings page. ## Which version each site runs The app sends its own version (Forge's `appVersion`) and app id with every Jira event and every trigger registration. The gateway keeps the latest seen per site in the team's `JIRA#config` (`app_version`, `app_version_seen_at`, `app_id`) and compares it with `launch/jira-app.json`, read without credentials and kept for ten minutes. A site is behind when its version is older, or when its events carry no version at all (builds from before the app reported one). -When a site is behind, the Integrations page's Jira row says which version it runs, the latest, what it lacks and how its admin accepts the update, with a link to the site's Manage apps page; a run on a ticket from that site says its comments may be incomplete. Both go away with the next event or registration from the updated app (accepting an update sends a registration at once). +When a site is behind, the Integrations page's Jira row says which version it runs, the latest, what it lacks and how its admin accepts the update, with a link to Atlassian Administration and the installation link when one is published; a run on a ticket from that site says its comments may be incomplete. Both go away with the next event or registration from the updated app (accepting an update sends a registration at once). What each version lacks comes from `services/common/src/jira_app_features.json`: the first released version with each feature, from the app's git history and the version each release run deployed. Add a row when a release adds something a team would miss on an older site. The run summary reads the same table. diff --git a/docs/oauth.md b/docs/oauth.md index 1d5bdd1f5..4f4593074 100644 --- a/docs/oauth.md +++ b/docs/oauth.md @@ -58,13 +58,17 @@ Servers are added by address. CoderHelm discovers their authorization server (RF Every authorize and token request names the server as `resource` (RFC 8707). `iss` (RFC 9207) is checked when the server advertises it. +How a server signs in is never written down: each sign-in reads it from the server first (its `401` and `resource_metadata`, then its authorization server's RFC 8414 or OpenID metadata), reusing what was read in the last five minutes and reading again once when a start fails. A server whose sign-in moves is followed, with a new client on the new authorization server. Before anyone is sent to the sign-in page, CoderHelm asks it once: a `5xx` (or no answer) means the provider's sign-in is down, and the page says so with the status instead of sending the person to an error page. + +The redirect is the install's own callback (`/settings/integrations/mcp-callback/`) for every server CoderHelm registers with by metadata document or dynamic registration: each install registers itself, so the provider sends people straight back to it. Only CoderHelm's own pre-registered apps (Notion, Atlassian 3LO, Google Drive and Figma through hybrid) use the hosted callback on `app.coderhelm.com`, because those apps have one fixed redirect. + | Server | Registration it accepts | Notes | |---|---|---| | Linear `mcp.linear.app` | metadata document or dynamic | | | Sentry `mcp.sentry.dev` | metadata document or dynamic | | | Vercel `mcp.vercel.com` | metadata document, or clients Vercel approved | A self-host install needs its metadata document (an https address). | | Stripe `mcp.stripe.com` | dynamic | An agent API key works too. | -| Atlassian Rovo `mcp.atlassian.com` | dynamic | An Atlassian organization admin may need to allow the redirect domain under Atlassian Administration, Rovo, Rovo MCP server ("Your organization admin must authorize access from this redirect URL"). | +| Atlassian Rovo `mcp.atlassian.com/v2/mcp` | metadata document or dynamic, on `auth.atlassian.com` | The agent tools part of the one Atlassian connection. The server's `401` names its protected resource metadata, which names the sign-in server; CoderHelm reads it at every sign-in, so nothing about it is written down. The retired `v1/mcp` address (whose sign-in page answers 500 to every request) is moved to `v2/mcp` at the next sign-in. An Atlassian organization admin may need to allow the redirect domain under Atlassian Administration, Rovo, Rovo MCP server ("Your organization admin must authorize access from this redirect URL"). | | Figma `mcp.figma.com` | only clients Figma approved | Use a Figma OAuth app instead: the team's own, or CoderHelm's through hybrid. Scopes `current_user:read` and `file_content:read`; redirect as above. | ## Integrations @@ -79,7 +83,7 @@ Every authorize and token request names the server as `resource` (RFC 8707). `is - Asking an organization owner to approve the app returns `setup_action=request`; the page says the request was sent. - Connect GitHub to link returns `?github_link=` with what linking did: `linked`, `not_admin`, `owned_elsewhere` or `none_visible`. - Cancelling GitHub's sign-in during a hybrid link goes back to the install with `hybrid_github=declined`. The token used to check a hybrid link is revoked as soon as the check is done. -- **Jira (Forge app):** no OAuth. The app registers its web triggers with `POST /integrations/jira/forge-register`. Every trigger must be a Forge web trigger (https on `*.atlassian-dev.net`, no port or credentials), or the registration is refused. +- **Atlassian, the Jira app (Forge):** no OAuth. The app registers its web triggers with `POST /integrations/jira/forge-register`. Every trigger must be a Forge web trigger (https on `*.atlassian-dev.net`, no port or credentials), or the registration is refused. - **Slack and Microsoft Teams:** no OAuth. Slack uses a slash command with the app's signing secret, and Teams an incoming webhook or an outgoing webhook token ([integrations](./self-host/integrations.md)). ## Signing in to CoderHelm diff --git a/docs/self-host/hybrid.md b/docs/self-host/hybrid.md index c13b4bc5d..fc0252e44 100644 --- a/docs/self-host/hybrid.md +++ b/docs/self-host/hybrid.md @@ -11,7 +11,7 @@ A **hybrid** install runs entirely in your AWS account, like any self-hosted Cod | **A CoderHelm address**, `yourname.coderhelm.com` | buying a domain and adding DNS records | a real address with HTTPS in a few minutes, set up end to end | | **CoderHelm's GitHub App**, through the event relay | creating and keeping your own GitHub App | install one app on your organization; events and tokens arrive at your install | | **CoderHelm's Jira app**, through the event relay | setting up your own Jira app | link your Jira site once; its events arrive at your install, without the app's secret | -| **CoderHelm's integration apps** (Notion, Confluence, Google Drive, Figma, and any CoderHelm adds later) | registering an app with each provider | sign in with one click, as on coderhelm.com | +| **CoderHelm's integration apps** (Atlassian's Confluence sign-in, Notion, Google Drive, Figma, and any CoderHelm adds later) | registering an app with each provider | sign in with one click, as on coderhelm.com | Each part is a separate choice, at install time (the [install guide](/self-host/install/)) or later in **Settings, System, Hybrid**. **Fully private** (your own domain or the AWS address, your own GitHub App and apps) sends nothing to CoderHelm and needs no registration. @@ -150,7 +150,7 @@ The Setup checks show the link as `hybrid_jira` (in Settings, Setup and the inst **Settings, System, Hybrid, Other apps** is one choice for the whole install. The install guide offers the same choice under **What CoderHelm sets up for you** and applies it when the install registers. -- **Use Coderhelm's apps (easiest)** is the default. Every tool CoderHelm has an app for uses it: today Jira, Notion, Confluence, Google Drive and Figma. A tool CoderHelm adds in a later release is on as soon as your install runs that release, with nothing more to choose. +- **Use Coderhelm's apps (easiest)** is the default. Every tool CoderHelm has an app for uses it: today Atlassian (the Jira app and the Confluence sign-in), Notion, Google Drive and Figma. A tool CoderHelm adds in a later release is on as soon as your install runs that release, with nothing more to choose. - **Fully private** means no tool signs in or sends events through CoderHelm. Each tool uses your team's own app, which you set up on that tool's card in **Settings, Integrations**. GitHub is not part of this choice: it keeps its own, under **GitHub** on the same page. @@ -168,7 +168,7 @@ An install that chose per tool in an earlier release moves to this choice once, | Integration | Through CoderHelm's app | Notes | |---|---|---| | GitHub | yes | relay and token broker | -| Jira (Forge app) | yes | install CoderHelm's Jira app and enter your install id as the team id, or link a hosted team's site ([Jira through CoderHelm](#jira-through-coderhelm)) | +| Atlassian: the Jira app | yes | install CoderHelm's Jira app and enter your install id as the team id, or link a hosted team's site ([Jira through CoderHelm](#jira-through-coderhelm)) | | Notion, Confluence, Google Drive | yes | one-click sign-in through CoderHelm; tokens brokered | | Figma | yes | one-click sign-in through CoderHelm's public Figma app (read-only); tokens brokered, your install calls Figma's API | | Slack and Teams notifications | not needed | your install posts to the incoming webhook you paste | diff --git a/docs/self-host/integrations.md b/docs/self-host/integrations.md index fb9012446..09689bdde 100644 --- a/docs/self-host/integrations.md +++ b/docs/self-host/integrations.md @@ -87,7 +87,9 @@ Two ways. A team picks one in **Settings, Integrations, Jira**. ## Monitoring and data sources -New Relic, Confluence, OpenSearch, REST APIs, SQL databases, CloudWatch metrics and Airflow connect from **Settings, Integrations** or **Data sources** with keys or the AWS role. None needs an app of its own or a URL of CoderHelm's. A team signed in to Confluence for Knowledge needs no token for runs: its Confluence card on Settings, Integrations reads Connected, and Use in runs too lets agents read pages with the same sign-in (reading only). +New Relic, Confluence, OpenSearch, REST APIs, SQL databases, CloudWatch metrics and Airflow connect from **Settings, Integrations** or **Data sources** with keys or the AWS role. None needs an app of its own or a URL of CoderHelm's. A team signed in to Confluence for Knowledge needs no token for runs: the Confluence part of the Atlassian row on Settings, Integrations reads Connected, and Use in runs too lets agents read pages with the same sign-in (reading only). + +**Atlassian is one connection.** Settings, Integrations has one Atlassian row with three parts: Jira (CoderHelm's Jira app, or a webhook: ticket events, comments and ticket writes), Confluence (pages for runs and Knowledge: an Atlassian sign-in, an API token, or the Jira app) and agent tools (Atlassian's own MCP server). Connect signs in for Confluence, then agent tools; the Jira app is installed by a Jira admin from the Jira page. Connections made before keep working unchanged. - **New Relic**\ A user API key, and the US or EU region. diff --git a/docs/self-host/knowledge-sources.md b/docs/self-host/knowledge-sources.md index 07864ed38..62ef43616 100644 --- a/docs/self-host/knowledge-sources.md +++ b/docs/self-host/knowledge-sources.md @@ -36,7 +36,7 @@ The token path stays as the second choice in the add flow ("Use an API token ins ### Notion and Confluence sign-ins -Notion (`mcp.notion.com`) and Atlassian (`mcp.atlassian.com`) also run remote MCP servers with dynamic registration, but their tools can't keep a knowledge base in sync yet: Notion's can't list a page's children or give an edit time without reading each whole page, and cuts long pages short; Atlassian's doesn't publish its tools' arguments or answers. Their sources keep using the OAuth apps below, or the keys saved on the Integrations page. Agents can still use both servers through Connected apps. +Notion (`mcp.notion.com`) and Atlassian (`mcp.atlassian.com/v2/mcp`, the agent tools part of the one Atlassian connection) also run remote MCP servers with dynamic registration, but their tools can't keep a knowledge base in sync yet: Notion's can't list a page's children or give an edit time without reading each whole page, and cuts long pages short; Atlassian's doesn't publish its tools' arguments or answers. Their sources keep using the OAuth apps below, or the keys saved on the Integrations page. Agents can still use both servers through Connected apps. ## Without a sign-in app: tokens in the add flow @@ -84,7 +84,9 @@ People pick which pages to share on Notion's own consent screen; CoderHelm sees Events are checked with `X-Notion-Signature` (HMAC-SHA256 with that token). An event only starts a sync; what changed is always read back with the team's own connection. Without it, Notion sources sync every hour. -## Confluence (Atlassian) +## Atlassian: the Confluence sign-in + +This is the Confluence part of the one Atlassian connection (Settings, Integrations, Atlassian). 1. Open and create an **OAuth 2.0 integration**. 2. Under **Permissions**, add the Confluence API, then add exactly the scopes CoderHelm asks for. A scope the sign-in asks for but the app doesn't have makes Atlassian's consent page fail. diff --git a/services/common/src/hybrid/integrations.rs b/services/common/src/hybrid/integrations.rs index a47434440..9c16b3bda 100644 --- a/services/common/src/hybrid/integrations.rs +++ b/services/common/src/hybrid/integrations.rs @@ -36,6 +36,22 @@ pub struct Entry { /// For `Unavailable`: why, and what to do instead. #[serde(skip_serializing_if = "str::is_empty")] pub reason: &'static str, + /// The pieces one entry covers, by the ids an install's choices, the + /// relay and the broker use (Atlassian: the Jira app's events and the + /// Confluence sign-in). Empty: the entry is one piece, its own id. + #[serde(skip_serializing_if = "<[&str]>::is_empty")] + pub parts: &'static [&'static str], +} + +impl Entry { + /// The ids this entry stands for: its parts, or itself. + pub fn ids(&self) -> &[&'static str] { + if self.parts.is_empty() { + std::slice::from_ref(&self.id) + } else { + self.parts + } + } } /// Every integration, in the order the pages list them. @@ -47,14 +63,16 @@ pub const CATALOG: &[Entry] = &[ through_coderhelm: "GitHub sends the app's events to CoderHelm, which checks GitHub's signature and forwards each one to your install, re-signed. Short-lived installation tokens are minted for your install only, for the repositories you chose.", stays_with_you: "Your code, branches, runs and reviews. CoderHelm stores no code; an event's payload is held only while its forward is retried (at most 24 hours), and delivery records (ids, types, status) are kept for 14 days.", reason: "", + parts: &[], }, Entry { - id: "jira", - name: "Jira (Forge app)", + id: "atlassian", + name: "Atlassian (Jira and Confluence)", mode: Mode::Hosted, - through_coderhelm: "CoderHelm's Jira app sends issue events to CoderHelm, which forwards them to your install unchanged and re-signed. The app's own secret is checked by your install, so CoderHelm can't forge an event.", - stays_with_you: "Tickets, plans and runs. Your install calls Jira through the app's own web triggers directly.", + through_coderhelm: "CoderHelm's Jira app sends issue events to CoderHelm, which forwards them to your install unchanged and re-signed; the app's own secret is checked by your install, so CoderHelm can't forge an event. For Confluence you sign in through CoderHelm's Atlassian app: CoderHelm keeps the sign-in (encrypted) and hands your install access tokens that expire within the hour.", + stays_with_you: "Tickets, plans and runs, the Confluence pages your install reads and the index it builds. Your install calls Jira through the app's own web triggers directly, and agents reach Atlassian's own MCP server from your install with its own sign-in.", reason: "", + parts: &["jira", "confluence"], }, Entry { id: "notion", @@ -63,14 +81,7 @@ pub const CATALOG: &[Entry] = &[ through_coderhelm: "You sign in through CoderHelm's Notion integration. CoderHelm keeps the sign-in (encrypted) and hands your install an access token when it syncs.", stays_with_you: "The pages your install reads and the index it builds. Notion's tokens don't expire by themselves: disconnecting revokes the grant at CoderHelm, and Notion's page lets you remove access completely.", reason: "", - }, - Entry { - id: "confluence", - name: "Confluence (Atlassian)", - mode: Mode::Hosted, - through_coderhelm: "You sign in through CoderHelm's Atlassian app. CoderHelm keeps the sign-in (encrypted) and hands your install access tokens that expire within the hour.", - stays_with_you: "The pages your install reads and the index it builds.", - reason: "", + parts: &[], }, Entry { id: "google_drive", @@ -79,6 +90,7 @@ pub const CATALOG: &[Entry] = &[ through_coderhelm: "You sign in through CoderHelm's Google app (read-only Drive access). CoderHelm keeps the sign-in (encrypted) and hands your install access tokens that expire within the hour.", stays_with_you: "The files your install reads and the index it builds.", reason: "", + parts: &[], }, Entry { id: "figma", @@ -87,6 +99,7 @@ pub const CATALOG: &[Entry] = &[ through_coderhelm: "You sign in through CoderHelm's Figma app (read-only: your profile and file contents). CoderHelm keeps the sign-in (encrypted) and hands your install access tokens that expire within ten minutes.", stays_with_you: "The designs your install reads. Agents call Figma's API from your install with those tokens.", reason: "", + parts: &[], }, Entry { id: "slack_notifications", @@ -95,6 +108,7 @@ pub const CATALOG: &[Entry] = &[ through_coderhelm: "Nothing: notifications go from your install to the incoming webhook you paste.", stays_with_you: "Everything. No app from CoderHelm or anyone else is needed.", reason: "", + parts: &[], }, Entry { id: "mcp_apps", @@ -103,6 +117,7 @@ pub const CATALOG: &[Entry] = &[ through_coderhelm: "Nothing: your install registers itself with each provider's sign-in server and keeps its own tokens.", stays_with_you: "Everything.", reason: "", + parts: &[], }, Entry { id: "slack_commands", @@ -111,6 +126,7 @@ pub const CATALOG: &[Entry] = &[ through_coderhelm: "", stays_with_you: "", reason: "CoderHelm has no shared Slack or Teams app: each team connects its own app's signing secret in Plugins settings, so there is nothing to relay. That keeps working the same way on a hybrid install.", + parts: &[], }, Entry { id: "github_sign_in", @@ -119,20 +135,33 @@ pub const CATALOG: &[Entry] = &[ through_coderhelm: "Without a GitHub OAuth client of your own, GitHub's sign-in page is CoderHelm's GitHub App: CoderHelm passes GitHub's one-time code to your install, exchanges it when your install asks (with a secret only your install holds), and revokes the token at GitHub seconds later. It stores neither and doesn't ask GitHub who signed in.", stays_with_you: "Who signs in: your install asks GitHub itself whose account it is, then applies its own rules (team members and invites, two-factor). CoderHelm can't start a session on your install or choose who signs in.", reason: "", + parts: &[], }, ]; -/// One entry by id. +/// One entry by its id or by the id of a piece it covers (`jira` and +/// `confluence` are both Atlassian's). pub fn entry(id: &str) -> Option<&'static Entry> { - CATALOG.iter().find(|e| e.id == id) + CATALOG.iter().find(|e| e.id == id || e.parts.contains(&id)) } -/// The ids an install may opt in to (the hosted ones). +/// The ids an install may opt in to (the hosted pieces). These are what +/// installs saved, and what the relay and the broker check, so an entry that +/// covers several pieces keeps every choice made before it covered them. pub fn hosted_ids() -> impl Iterator { CATALOG .iter() .filter(|e| e.mode == Mode::Hosted) - .map(|e| e.id) + .flat_map(|e| e.ids().iter().copied()) +} + +/// The piece ids an id from a page names: an entry's own id (`atlassian`) +/// stands for its pieces, anything else for itself. +pub fn expand(id: &str) -> Vec { + match CATALOG.iter().find(|e| e.id == id && !e.parts.is_empty()) { + Some(e) => e.parts.iter().map(|p| p.to_string()).collect(), + None => vec![id.to_string()], + } } /// The tools the install-wide Other apps choice covers (Settings, System, @@ -173,17 +202,31 @@ mod tests { vec![ "github", "jira", - "notion", "confluence", + "notion", "google_drive", "figma" ] ); assert_eq!( app_choice_ids().collect::>(), - vec!["jira", "notion", "confluence", "google_drive", "figma"] + vec!["jira", "confluence", "notion", "google_drive", "figma"] ); assert!(entry("github").is_some() && entry("nope").is_none()); + // One Atlassian entry; the pieces installs chose before keep their ids. + assert_eq!(entry("jira").unwrap().id, "atlassian"); + assert_eq!(entry("confluence").unwrap().id, "atlassian"); + assert_eq!( + CATALOG + .iter() + .filter(|e| e.name.contains("Atlassian") || e.name.contains("Jira")) + .count(), + 1 + ); + assert_eq!(expand("atlassian"), vec!["jira", "confluence"]); + assert_eq!(expand("notion"), vec!["notion"]); + let a = serde_json::to_value(entry("atlassian").unwrap()).unwrap(); + assert_eq!(a["parts"], serde_json::json!(["jira", "confluence"])); let j = serde_json::to_value(entry("slack_commands").unwrap()).unwrap(); assert_eq!(j["mode"], "unavailable"); assert!(serde_json::to_value(entry("github").unwrap()) diff --git a/services/common/src/jira_app_version.rs b/services/common/src/jira_app_version.rs index 0ed6e5f07..1597455bb 100644 --- a/services/common/src/jira_app_version.rs +++ b/services/common/src/jira_app_version.rs @@ -119,6 +119,10 @@ pub struct Latest { /// The Forge app it belongs to; a site running another app (a /// self-hosted copy) is never compared with it. pub app_id: String, + /// The app's installation link from the developer console (Distribution), + /// when the release workflow publishes one: an admin who opens it updates + /// the app on their site in one step. Empty when none is published. + pub install_url: String, } impl Latest { @@ -133,6 +137,13 @@ impl Latest { .unwrap_or("") .trim() .to_string(), + install_url: v + .get("installUrl") + .and_then(Value::as_str) + .map(str::trim) + .filter(|u| is_install_link(u)) + .unwrap_or("") + .to_string(), }) } } @@ -219,8 +230,14 @@ pub struct Behind { pub latest: String, /// What the site's version lacks, from the table. pub missing: Vec, - /// The site's Manage apps page, where its admin accepts the update. + /// Atlassian Administration, where a site admin accepts the update + /// (Apps, Sites, the site, Connected apps). Named `manage_url` for + /// dashboards from before; it never points at Jira's Manage apps, which + /// doesn't list a pending Forge update. pub manage_url: String, + /// The app's installation link, which updates it in one step; empty + /// when none is published. + pub install_url: String, /// When the site was last heard from. pub seen_at: String, /// The Integrations page's notice. @@ -229,17 +246,31 @@ pub struct Behind { pub run_note: String, } -/// The site's Manage apps page (Jira settings, Apps, Manage apps), or empty -/// when the site isn't an Atlassian Cloud address. -pub fn manage_apps_url(site: &str) -> String { - crate::live::confluence::check_site(site) - .map(|s| format!("{s}/plugins/servlet/upm")) - .unwrap_or_default() +/// Atlassian Administration, where a pending Forge update is accepted. +pub const ADMIN_URL: &str = "https://admin.atlassian.com/"; + +/// An installation link from Atlassian's developer console (Distribution). +pub fn is_install_link(u: &str) -> bool { + reqwest::Url::parse(u).is_ok_and(|p| { + p.scheme() == "https" + && p.host_str() == Some("developer.atlassian.com") + && p.path().starts_with("/console/install/") + }) } -/// The admin's steps in Jira, said the same way everywhere. -pub const ADMIN_STEPS: &str = - "A Jira admin needs to accept the update: Jira Settings, Apps, Manage apps, Coderhelm, Update."; +/// The admin's steps, said the same way everywhere. A Forge update that asks +/// for new access is accepted in Atlassian Administration, not in Jira: Jira's +/// Manage apps page has no Update for it. +pub const ADMIN_STEPS: &str = "An Atlassian site admin accepts the update in Atlassian Administration (admin.atlassian.com): Apps, Sites, choose the site, Connected apps, Coderhelm, View app details, Update. Jira's own Manage apps page doesn't list it."; + +/// The steps, with the one-click way first when there is an installation link. +pub fn admin_steps(install_url: &str) -> String { + if install_url.is_empty() { + ADMIN_STEPS.to_string() + } else { + format!("An Atlassian site admin can open the app's installation link ({install_url}), choose the site and Update, or accept it in Atlassian Administration (admin.atlassian.com): Apps, Sites, choose the site, Connected apps, Coderhelm, View app details, Update.") + } +} fn running(version: &str, latest: &str) -> String { let v = if version.is_empty() { @@ -257,7 +288,7 @@ fn running(version: &str, latest: &str) -> String { /// Whether the site is behind, from what it last reported and the latest /// release. `None` when it is current, never seen, runs another app than /// the published one, or reports a version that can't be compared. -pub fn assess(seen: Option<&Seen>, latest: Option<&Latest>, site: &str) -> Option { +pub fn assess(seen: Option<&Seen>, latest: Option<&Latest>, _site: &str) -> Option { let seen = seen?; let reported = Version::parse(&seen.version); let missing = match reported { @@ -274,6 +305,7 @@ pub fn assess(seen: Option<&Seen>, latest: Option<&Latest>, site: &str) -> Optio } }; let version = reported.map(|v| v.to_string()).unwrap_or_default(); + let install_url = latest.map(|l| l.install_url.clone()).unwrap_or_default(); let latest = latest.map(|l| l.version.to_string()).unwrap_or_default(); let what = running(&version, &latest); let lacks = if missing.is_empty() { @@ -281,15 +313,17 @@ pub fn assess(seen: Option<&Seen>, latest: Option<&Latest>, site: &str) -> Optio } else { format!(" Missing: {}.", missing.join(", ")) }; - let message = - format!("Your Jira site runs an older Coderhelm app {what}.{lacks} {ADMIN_STEPS}"); + let message = format!( + "Your Jira site runs an older Coderhelm app {what}.{lacks} {}", + admin_steps(&install_url) + ); let run_note = if missing.is_empty() { format!( - "Comments on this ticket may be incomplete: its Jira site runs an older Coderhelm app {what}. A Jira admin can accept the update in Manage apps." + "Comments on this ticket may be incomplete: its Jira site runs an older Coderhelm app {what}. An Atlassian site admin can accept the update in Atlassian Administration, Connected apps." ) } else { format!( - "Comments on this ticket may be incomplete: its Jira site runs an older Coderhelm app {what} without {}. A Jira admin can accept the update in Manage apps.", + "Comments on this ticket may be incomplete: its Jira site runs an older Coderhelm app {what} without {}. An Atlassian site admin can accept the update in Atlassian Administration, Connected apps.", missing.join(", ") ) }; @@ -297,7 +331,8 @@ pub fn assess(seen: Option<&Seen>, latest: Option<&Latest>, site: &str) -> Optio version, latest, missing, - manage_url: manage_apps_url(site), + manage_url: ADMIN_URL.to_string(), + install_url, seen_at: seen.seen_at.clone(), message, run_note, @@ -325,6 +360,7 @@ mod tests { Latest { version: Version::parse(v).unwrap(), app_id: APP.into(), + install_url: String::new(), } } @@ -401,17 +437,19 @@ mod tests { let b = assess(Some(&seen("6.8.0")), Some(&latest("6.11.0")), SITE).unwrap(); assert_eq!(b.version, "6.8.0"); assert_eq!(b.latest, "6.11.0"); - assert_eq!( - b.manage_url, - "https://yourcompany.atlassian.net/plugins/servlet/upm" - ); + // Atlassian Administration, never Jira's Manage apps (no Update there). + assert_eq!(b.manage_url, "https://admin.atlassian.com/"); + assert_eq!(b.install_url, ""); assert!(b.message.starts_with( "Your Jira site runs an older Coderhelm app (version 6.8.0, latest 6.11.0). Missing: " )); assert!(b.message.contains("threaded replies")); - assert!(b.message.ends_with( - "A Jira admin needs to accept the update: Jira Settings, Apps, Manage apps, Coderhelm, Update." - )); + assert!(b.message.ends_with(ADMIN_STEPS)); + assert!(b.message.contains("Atlassian Administration (admin.atlassian.com): Apps, Sites, choose the site, Connected apps, Coderhelm, View app details, Update.")); + assert!(!b.run_note.contains("Manage apps")); + assert!(b + .run_note + .contains("Atlassian Administration, Connected apps")); assert!(b .run_note .starts_with("Comments on this ticket may be incomplete")); @@ -516,12 +554,32 @@ mod tests { } #[test] - fn manage_apps_is_on_the_site_only() { - assert_eq!( - manage_apps_url("https://YourCompany.atlassian.net/"), - "https://yourcompany.atlassian.net/plugins/servlet/upm" - ); - assert_eq!(manage_apps_url("https://example.com"), ""); - assert_eq!(manage_apps_url(""), ""); + fn the_installation_link_is_the_one_click_way_when_published() { + let link = "https://developer.atlassian.com/console/install/00000000-0000-0000-0000-000000000002?signature=abc&product=jira"; + let l = Latest::parse(&format!( + r#"{{"version": "6.12.0", "appId": "{APP}", "installUrl": "{link}"}}"# + )) + .unwrap(); + assert_eq!(l.install_url, link); + let b = assess(Some(&seen("6.8.0")), Some(&l), SITE).unwrap(); + assert_eq!(b.install_url, link); + assert!(b.message.contains(&format!("installation link ({link})"))); + assert!(b.message.contains("Connected apps")); + // Only a developer console installation link is passed on. + for bad in [ + "https://example.com/console/install/x", + "http://developer.atlassian.com/console/install/x", + "https://developer.atlassian.com/apps/x", + ] { + let l = Latest::parse(&format!( + r#"{{"version": "6.12.0", "installUrl": "{bad}"}}"# + )) + .unwrap(); + assert_eq!(l.install_url, "", "{bad}"); + } + // Nowhere says Manage apps is where the update is. + for text in [ADMIN_STEPS.to_string(), admin_steps(link)] { + assert!(!text.contains("Manage apps, Coderhelm"), "{text}"); + } } } diff --git a/services/common/src/knowledge/sources/oauth.rs b/services/common/src/knowledge/sources/oauth.rs index 8d53579b8..8c90d064e 100644 --- a/services/common/src/knowledge/sources/oauth.rs +++ b/services/common/src/knowledge/sources/oauth.rs @@ -308,6 +308,7 @@ pub fn connection_record( .collect(), token_body_json: p.json_body, refresh_endpoint: String::new(), + discovered_at: 0, }); s } @@ -352,6 +353,7 @@ pub fn brokered_connection_record( extra_authorize: vec![], token_body_json: false, refresh_endpoint: String::new(), + discovered_at: 0, }); s } diff --git a/services/common/src/live/confluence.rs b/services/common/src/live/confluence.rs index 5bab66e5f..c82908a6e 100644 --- a/services/common/src/live/confluence.rs +++ b/services/common/src/live/confluence.rs @@ -259,7 +259,7 @@ impl Confluence<'_> { if matches!(op, Op::Append { .. }) { return Err(refused( "The Atlassian sign-in only reads Confluence.", - "To add text to pages, connect Confluence with an API token or the Jira app.", + "To add text to pages, save an API token in Settings, Integrations, Atlassian, Confluence.", )); } (base.trim_end_matches('/').to_string(), bearer.to_string()) @@ -327,7 +327,7 @@ impl Confluence<'_> { return Err(StepError::new( "reach", "The Coderhelm app in Jira hasn't shared its Confluence address.", - "Update the app in Jira, then open Coderhelm Settings there and save.", + "The Jira app no longer reads Confluence. Connect Confluence in Settings, Integrations, Atlassian (an Atlassian sign-in, or an API token).", )); } let mut body = match op { @@ -537,7 +537,7 @@ impl Confluence<'_> { if matches!(self.access, Access::SignIn { .. }) { return Err(refused( "The Atlassian sign-in only reads Confluence.", - "To add text to pages, connect Confluence with an API token or the Jira app. Put the text in your reply for a person to add.", + "To add text to pages, save an API token in Settings, Integrations, Atlassian, Confluence. Put the text in your reply for a person to add.", )); } if !self.conn.may_write_page(id) { @@ -921,7 +921,7 @@ mod tests { // An append is refused before anything is sent: the sign-in only reads. let e = cf.append("42", "note").await.unwrap_err(); assert!(e.is_refusal(), "{e:?}"); - assert!(e.fix.contains("API token or the Jira app"), "{e:?}"); + assert!(e.fix.contains("save an API token"), "{e:?}"); // A sign-in Confluence refuses says where to sign in again. let e = cf.page("42").await.unwrap_err(); assert!(e.message.contains("Atlassian sign-in"), "{e:?}"); diff --git a/services/common/src/live/confluence_changelog.rs b/services/common/src/live/confluence_changelog.rs new file mode 100644 index 000000000..62b93caee --- /dev/null +++ b/services/common/src/live/confluence_changelog.rs @@ -0,0 +1,323 @@ +//! Release notes into a Confluence changelog, through the Confluence part of +//! the team's Atlassian connection (its email and API token), not through the +//! Jira app. +//! +//! The Jira app used to do this with its own Confluence scopes, which made +//! every Jira app release one an Atlassian site admin had to accept, across +//! two Atlassian products. The Jira app is Jira-only now; this does the same +//! steps from CoderHelm: under the parent page, a container page +//! ("Changelog"), under it one page per year, and the release's entry +//! upserted at the top of the year page (found again by its anchor, so a +//! regenerated entry replaces itself). + +use base64::{engine::general_purpose::STANDARD, Engine}; +use serde_json::{json, Value}; + +use super::confluence::{check_page_id, check_site}; +use super::http::{Method, Request, Transport}; + +/// Where and what to publish. +#[derive(Debug, Clone)] +pub struct Entry<'a> { + pub parent_id: &'a str, + /// The container page's title; empty is "Changelog". + pub container: &'a str, + pub year: &'a str, + /// `owner/repo@tag`: the anchor that finds this entry again. + pub key: &'a str, + /// The entry, in Confluence storage format. + pub html: &'a str, +} + +/// The anchor macro that marks an entry, from its key. The same as the Jira +/// app's (`coderhelm-jira`, before it was Jira-only), so entries it published +/// are found and replaced, not repeated. +pub fn anchor_for(key: &str) -> String { + let mut slug = String::from("coderhelm-"); + let mut run = false; + for c in key.chars() { + if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { + slug.push(c); + run = false; + } else if !run { + slug.push('-'); + run = true; + } + } + format!( + "{slug}" + ) +} + +/// The year page with the entry for `key` put in: in place of its earlier +/// copy, else right after the page's heading, else at the top. +pub fn upsert_entry(page: &str, key: &str, html: &str) -> String { + let anchor = anchor_for(key); + let block = format!("{anchor}{html}"); + if let Some(at) = page.find(&anchor) { + let after = at + anchor.len(); + let own_heading = page[after..].find("") + .map(|i| after + i); + let next_heading = own_heading.and_then(|h| page[h + 3..].find("") { + let cut = h1 + "".len(); + return format!("{}{block}{}", &page[..cut], &page[cut..]); + } + format!("{block}{page}") +} + +/// A Confluence site reached with an account's email and API token. +pub struct Site<'a> { + pub site: &'a str, + pub email: &'a str, + pub token: &'a str, + pub http: &'a dyn Transport, +} + +impl Site<'_> { + async fn call(&self, method: Method, path: &str, body: Option) -> Result { + let root = check_site(self.site).map_err(|e| e.to_string())?; + let auth = format!( + "Basic {}", + STANDARD.encode(format!("{}:{}", self.email, self.token)) + ); + let reply = self + .http + .send(Request { + method, + url: format!("{root}{path}"), + headers: vec![ + ("Authorization".into(), auth), + ("Accept".into(), "application/json".into()), + ], + body, + }) + .await + .map_err(|e| e.to_string())?; + match reply.status { + 200..=299 => Ok(reply.json().unwrap_or(Value::Null)), + 401 => Err("Confluence didn't accept the email and API token saved for the Atlassian connection.".into()), + 403 => Err("The Atlassian account whose token is saved can't edit pages under that parent page.".into()), + 404 => Err("Confluence has no page with that parent id (or the account can't see it).".into()), + 409 => Err("409".into()), + s => Err(format!("Confluence answered {s}.")), + } + } + + async fn child_by_title(&self, parent: &str, title: &str) -> Result, String> { + let mut cursor = String::new(); + for _ in 0..20 { + let path = if cursor.is_empty() { + format!("/wiki/api/v2/pages/{parent}/children?limit=250") + } else { + format!("/wiki/api/v2/pages/{parent}/children?limit=250&cursor={cursor}") + }; + let page = self.call(Method::Get, &path, None).await?; + if let Some(hit) = page["results"] + .as_array() + .into_iter() + .flatten() + .find(|p| p["title"].as_str() == Some(title)) + { + return Ok(hit["id"].as_str().map(str::to_string)); + } + let next = page["_links"]["next"].as_str().unwrap_or(""); + match next.split("cursor=").nth(1) { + Some(c) => { + cursor = c.split('&').next().unwrap_or("").to_string(); + if cursor.is_empty() { + return Ok(None); + } + } + None => return Ok(None), + } + } + Ok(None) + } + + async fn child( + &self, + space: &str, + parent: &str, + title: &str, + seed: &str, + ) -> Result { + if let Some(id) = self.child_by_title(parent, title).await? { + return Ok(id); + } + let made = self + .call( + Method::Post, + "/wiki/api/v2/pages", + Some(json!({ + "spaceId": space, + "status": "current", + "title": title, + "parentId": parent, + "body": { "representation": "storage", "value": seed }, + })), + ) + .await?; + made["id"] + .as_str() + .map(str::to_string) + .ok_or_else(|| "Confluence made the page but sent no id.".to_string()) + } + + /// Publishes the entry; returns the year page's address. + pub async fn publish(&self, e: &Entry<'_>) -> Result { + let parent = check_page_id(e.parent_id).map_err(|e| e.to_string())?; + if e.year.is_empty() || e.key.is_empty() || e.html.is_empty() { + return Err("A release entry needs its year, key and text.".into()); + } + let p = self + .call(Method::Get, &format!("/wiki/api/v2/pages/{parent}"), None) + .await?; + let space = p["spaceId"].as_str().unwrap_or("").to_string(); + let container = if e.container.trim().is_empty() { + "Changelog" + } else { + e.container.trim() + }; + let container_id = self + .child( + &space, + parent, + container, + &format!("

{container}

Release notes published by CoderHelm, one page per year.

"), + ) + .await?; + let year_id = self + .child( + &space, + &container_id, + e.year, + &format!("

{}

", e.year), + ) + .await?; + for attempt in 0..2 { + let page = self + .call( + Method::Get, + &format!("/wiki/api/v2/pages/{year_id}?body-format=storage"), + None, + ) + .await?; + let current = page["body"]["storage"]["value"].as_str().unwrap_or(""); + let next = upsert_entry(current, e.key, e.html); + let version = page["version"]["number"].as_i64().unwrap_or(0); + match self + .call( + Method::Put, + &format!("/wiki/api/v2/pages/{year_id}"), + Some(json!({ + "id": year_id, + "status": "current", + "title": page["title"], + "body": { "representation": "storage", "value": next }, + "version": { "number": version + 1, "message": format!("Release notes: {}", e.key) }, + })), + ) + .await + { + Ok(_) => { + let base = page["_links"]["base"].as_str().unwrap_or(""); + let webui = page["_links"]["webui"].as_str().unwrap_or(""); + return Ok(if base.is_empty() || webui.is_empty() { + "published".into() + } else { + format!("{base}{webui}") + }); + } + Err(m) if m == "409" && attempt == 0 => continue, + Err(m) if m == "409" => { + return Err("Someone edited the year page at the same moment twice. Publish again.".into()) + } + Err(m) => return Err(m), + } + } + Err("The year page couldn't be updated.".into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::live::http::fake::Fake; + + #[test] + fn an_entry_goes_under_the_heading_and_replaces_itself() { + let page = "

2026

old

"; + let once = upsert_entry(page, "acme/web@v1", "

v1

a

"); + assert!(once.starts_with("

2026

v1

a

old

")); + let again = upsert_entry(&once, "acme/web@v1", "

v1

b

"); + assert_eq!(again.matches("coderhelm-acme-web-v1").count(), 1); + // The Jira app's own anchor for the same key. + assert!(anchor_for("acme/web@v1 x").contains(">coderhelm-acme-web-v1-x<")); + assert!(again.contains("

b

") && !again.contains("

a

")); + let two = upsert_entry(&again, "acme/web@v2", "

v2

"); + assert!( + two.find("v2").unwrap() < two.find("

v1").unwrap(), + "newest first" + ); + assert_eq!( + upsert_entry("", "k", "

x

"), + format!("{}

x

", anchor_for("k")) + ); + } + + #[tokio::test] + async fn publishing_makes_the_container_and_year_and_writes_the_entry() { + let root = "https://example.atlassian.net"; + let year = json!({"id": "300", "title": "2026", "version": {"number": 1}, "body": {"storage": {"value": "

2026

"}}, "_links": {"base": format!("{root}/wiki"), "webui": "/spaces/X/pages/300"}}).to_string(); + let f = Fake::answering(vec![ + (200, r#"{"id": "100", "spaceId": "7"}"#), + (200, r#"{"results": [{"id": "200", "title": "Changelog"}]}"#), + (200, r#"{"results": []}"#), + (200, r#"{"id": "300"}"#), + (200, &year), + (200, "{}"), + ]); + let s = Site { + site: root, + email: "bot@example.com", + token: "t", + http: &f, + }; + let url = s + .publish(&Entry { + parent_id: "100", + container: "", + year: "2026", + key: "acme/web@v1", + html: "

v1

", + }) + .await + .unwrap(); + assert_eq!(url, format!("{root}/wiki/spaces/X/pages/300")); + let sent = f.sent(); + let made = sent.iter().find(|r| r.method == Method::Post).unwrap(); + assert_eq!(made.body.as_ref().unwrap()["parentId"], "200"); + assert_eq!(made.body.as_ref().unwrap()["title"], "2026"); + let put = sent.iter().find(|r| r.method == Method::Put).unwrap(); + assert_eq!(put.body.as_ref().unwrap()["version"]["number"], 2); + assert!(put.body.as_ref().unwrap()["body"]["value"] + .as_str() + .unwrap() + .contains("

v1

")); + assert!(sent.iter().all(|r| r + .headers + .iter() + .any(|(k, v)| k == "Authorization" && v.starts_with("Basic ")))); + } +} diff --git a/services/common/src/live/jira_app.rs b/services/common/src/live/jira_app.rs index fbc4c6864..8cbb034e2 100644 --- a/services/common/src/live/jira_app.rs +++ b/services/common/src/live/jira_app.rs @@ -121,7 +121,7 @@ pub fn with_jira_app(mut saved: Vec, app: Option<&JiraApp>) -> Vec c.site = a.site.clone(), None => { c.status = "error".into(); - c.status_message = "The Coderhelm app in Jira can't reach Confluence. Update the app in Jira, then open Coderhelm Settings there and save.".into(); + c.status_message = "The Coderhelm app in Jira can't reach Confluence. The Jira app no longer reads Confluence. Connect Confluence in Settings, Integrations, Atlassian (an Atlassian sign-in, or an API token).".into(); } }, Some(_) => {} diff --git a/services/common/src/live/mod.rs b/services/common/src/live/mod.rs index a7478e14c..9665cc4c2 100644 --- a/services/common/src/live/mod.rs +++ b/services/common/src/live/mod.rs @@ -30,6 +30,7 @@ pub mod aws_account; pub mod aws_settings; pub mod catalog; pub mod confluence; +pub mod confluence_changelog; pub mod connectors; pub mod db; pub mod dialect; diff --git a/services/common/src/mcp_catalog.rs b/services/common/src/mcp_catalog.rs index caba2f03e..c730d91e2 100644 --- a/services/common/src/mcp_catalog.rs +++ b/services/common/src/mcp_catalog.rs @@ -518,7 +518,7 @@ pub const CATALOG: &[McpServerDef] = &[ McpServerDef { id: "atlassian", name: "Atlassian", - description: "Search and read Jira issues and Confluence pages through Atlassian's remote MCP server.", + description: "Agent tools for Jira issues and Confluence pages, through Atlassian's own remote MCP server (Rovo). Part of the one Atlassian connection.", category: "Project Management", tier: 2, icon: "atlassian", @@ -529,7 +529,10 @@ pub const CATALOG: &[McpServerDef] = &[ recommended_permissions: "Sign in with an account that can read the projects and spaces agents need", npx_package: "", env_mapping: &[], - remote_url: "https://mcp.atlassian.com/v1/mcp", + // The current server. Its 401 names its protected resource metadata, + // and that names the sign-in server, so nothing about the sign-in is + // written down here (v1's sign-in page answers 500 to everyone). + remote_url: "https://mcp.atlassian.com/v2/mcp", remote_key: false, key_unavailable: "", }, @@ -540,6 +543,19 @@ pub fn find(id: &str) -> Option<&'static McpServerDef> { CATALOG.iter().find(|p| p.id == id) } +/// The address a catalog server's saved record should use now: the +/// catalog's, when the record was made from the catalog (its id is the +/// catalog id) and the vendor has since moved its server. `None` when +/// nothing changed or the record isn't a catalog one. +pub fn moved_remote_url(record_id: &str, catalog_id: &str, url: &str) -> Option<&'static str> { + if record_id != catalog_id { + return None; + } + let p = find(catalog_id)?; + let now = p.remote_url; + (!now.is_empty() && now.trim_end_matches('/') != url.trim_end_matches('/')).then_some(now) +} + /// Where a person creates the key for a catalog server, in plain words, for /// when its sign-in can't be used. Falls back to the server's API docs. pub fn key_help(id: &str) -> Option { diff --git a/services/common/src/mcp_remote/runtime.rs b/services/common/src/mcp_remote/runtime.rs index c70700cc1..643f02836 100644 --- a/services/common/src/mcp_remote/runtime.rs +++ b/services/common/src/mcp_remote/runtime.rs @@ -28,8 +28,8 @@ use super::discovery::{self, OAuthPlan}; use super::http::Http; use super::oauth::{self, Client, ClientAuth, Registration, TokenSet}; use super::store::{ - AuthKind, LogEntry, Owner, PendingAuth, ServerRecord, Status, Store, TokenRecord, - PENDING_TTL_SECS, + AuthKind, LogEntry, OAuthSettings, Owner, PendingAuth, ServerRecord, Status, Store, + TokenRecord, PENDING_TTL_SECS, }; use super::tools; use crate::mcp_credentials::Cipher; @@ -168,6 +168,49 @@ pub async fn detect(http: &dyn Http, url: &str) -> Result { } } +/// How long a server's sign-in metadata is trusted before a sign-in reads +/// it again. Short: a vendor that moves its sign-in server (Atlassian +/// moved from `mcp.atlassian.com/v1` to `auth.atlassian.com`) is followed +/// within minutes, with no record to fix by hand. +pub const DISCOVERY_TTL_SECS: i64 = 300; + +/// Whether a record's sign-in settings came from the server's own metadata +/// (a remote MCP server), and so are read again before each sign-in. A +/// provider's own API with addresses fixed in code (a knowledge source, a +/// catalog server's app, the hybrid broker) is not. +pub fn discovers(s: &ServerRecord) -> bool { + let Some(o) = &s.oauth else { return false }; + s.auth == AuthKind::OAuth + && !(super::store::is_token_only(&s.catalog_id) + && o.registration == Registration::Manual.as_str()) +} + +/// The words for a sign-in page that is failing on the provider's side. +pub fn provider_down(name: &str, status: u16) -> String { + format!( + "{name}'s sign-in page is failing on {name}'s side (HTTP {status}), so Coderhelm didn't send you there. Nothing on your side needs changing. Try again in a few minutes." + ) +} + +/// Asks the authorization page once before a person is sent to it. A `5xx` +/// (or no answer) means the provider's sign-in is down: the person gets +/// that in plain words instead of the provider's error page. Any other +/// answer (a login page, a redirect, a `4xx` about the request) is left for +/// the browser. +pub async fn probe_authorize(http: &dyn Http, name: &str, url: &str) -> Result<(), String> { + let mut req = super::http::HttpRequest::get(url); + req.headers + .retain(|(k, _)| !k.eq_ignore_ascii_case("accept")); + req.headers.push(("Accept".into(), "text/html".into())); + match http.send(req).await { + Ok(r) if r.status >= 500 => Err(provider_down(name, r.status)), + Ok(_) | Err(super::http::HttpError::Refused(_)) => Ok(()), + Err(super::http::HttpError::Unreachable(m)) => Err(format!( + "Coderhelm couldn't reach {name}'s sign-in page ({m}). Try again in a few minutes." + )), + } +} + pub type Clock = Arc i64 + Send + Sync>; pub fn system_clock() -> Clock { @@ -873,6 +916,125 @@ impl Runtime { return_to: &str, ) -> Result { let flow = flow.unwrap_or_else(|| self.flow_of(s)); + let discovered = discovers(s); + if discovered { + self.rediscover(s, false).await?; + } + match self + .start_once( + s, + owner, + user_sub, + user_email, + redirect_uri, + metadata_document_url, + flow, + return_to, + discovered, + ) + .await + { + // Settings read a few minutes ago may already be out of date: + // read them again, once, and try with what the server says now. + Err(e) if discovered && !self.just_discovered(s) => { + if self.rediscover(s, true).await.is_err() { + return Err(e); + } + self.start_once( + s, + owner, + user_sub, + user_email, + redirect_uri, + metadata_document_url, + flow, + return_to, + discovered, + ) + .await + } + r => r, + } + } + + fn just_discovered(&self, s: &ServerRecord) -> bool { + s.oauth + .as_ref() + .is_some_and(|o| o.discovered_at >= self.now()) + } + + /// Reads a remote MCP server's sign-in settings again from its own + /// metadata (its `401`, its protected resource metadata, its + /// authorization server's metadata) unless they were read less than + /// [`DISCOVERY_TTL_SECS`] ago (`force` reads them anyway). A catalog + /// server the vendor moved gets the catalog's new address first. The + /// client Coderhelm has on the authorization server is kept while the + /// issuer is the same; a new issuer gets a new client. Saved when + /// anything changed. When the server can't be asked, the saved settings + /// stand (the sign-in itself then says what is wrong). + pub async fn rediscover(&self, s: &mut ServerRecord, force: bool) -> Result<(), String> { + let now = self.now(); + let mut changed = false; + if let Some(url) = crate::mcp_catalog::moved_remote_url(&s.id, &s.catalog_id, &s.url) { + s.url = url.to_string(); + changed = true; + } + let Some(old) = s.oauth.clone() else { + return Ok(()); + }; + let fresh = old.discovered_at > 0 && now - old.discovered_at < DISCOVERY_TTL_SECS; + if fresh && !force && !changed { + return Ok(()); + } + let plan = match detect(self.http.as_ref(), &s.url).await { + Ok(Detected::OAuth(plan)) => plan, + Err(e) if changed => return Err(e), + other => { + let why = match other { + Err(e) => e, + Ok(_) => "the server didn't ask for a sign-in".into(), + }; + tracing::warn!(team = %self.team, server = %s.id, error = %why, "Sign-in settings could not be read again; using the saved ones"); + return Ok(()); + } + }; + let mut o = OAuthSettings::from_plan(&plan); + o.discovered_at = now; + if o.issuer == old.issuer { + o.client_id = old.client_id.clone(); + o.client_auth = old.client_auth; + o.client_secret_sealed = old.client_secret_sealed.clone(); + o.registration = old.registration.clone(); + } else if old.registration == Registration::Manual.as_str() && !old.client_id.is_empty() { + return Err(format!( + "{} now signs in through {}, where the client id you pasted isn't registered. Register an OAuth app there and paste its client id.", + display_name(s), + o.issuer + )); + } + o.extra_authorize = old.extra_authorize.clone(); + o.token_body_json = old.token_body_json; + o.refresh_endpoint = old.refresh_endpoint.clone(); + if o.issuer != old.issuer || o.resource != old.resource { + tracing::info!(team = %self.team, server = %s.id, from = %old.issuer, to = %o.issuer, resource = %o.resource, "A server's sign-in moved; following it"); + } + s.oauth = Some(o); + self.store.put_server(&self.team, s).await + } + + #[allow(clippy::too_many_arguments)] + async fn start_once( + &self, + s: &mut ServerRecord, + owner: &Owner, + user_sub: &str, + user_email: &str, + redirect_uri: &str, + metadata_document_url: Option<&str>, + flow: oauth::Flow, + return_to: &str, + probe: bool, + ) -> Result { let mut o = s .oauth .clone() @@ -922,6 +1084,21 @@ impl Runtime { self.end_pending(&s.id, Some(owner), Some(user_sub)).await; let pkce = oauth::Pkce::new(); let state = oauth::new_state_for(flow); + let url = oauth::authorize_url( + &o.auth_server(), + &o.client_id, + redirect_uri, + &pkce, + &state, + &scopes, + &o.resource, + )?; + let url = oauth::with_extra_params(&url, &o.extra_authorize)?; + // Nobody is sent to a sign-in page that is down; nothing is + // recorded for a sign-in that can't start. + if probe { + probe_authorize(self.http.as_ref(), &display_name(s), &url).await?; + } self.store .put_pending( &self.team, @@ -940,16 +1117,7 @@ impl Runtime { }, ) .await?; - let url = oauth::authorize_url( - &o.auth_server(), - &o.client_id, - redirect_uri, - &pkce, - &state, - &scopes, - &o.resource, - )?; - oauth::with_extra_params(&url, &o.extra_authorize) + Ok(url) } /// Ends the team's sign-ins in progress for `server_id` (for one owner @@ -2065,7 +2233,213 @@ mod tests { .await .unwrap(); assert!(url.contains(&format!("client_id={}", urlencoding_like(doc)))); - assert!(r.http.sent().is_empty(), "no registration request"); + assert!( + r.http + .sent_to("https://auth.example.com/register") + .is_empty(), + "no registration request" + ); + } + + const PRM: &str = "https://mcp.example.com/.well-known/oauth-protected-resource/mcp"; + const NEW_AS: &str = "https://login.example.net/t1"; + const NEW_AUTHORIZE: &str = "https://login.example.net/authorize"; + + /// A server that moved its sign-in: its `401` names its protected + /// resource metadata, which names a new authorization server. + fn moved_server(f: &Fake, authorize_status: u16) { + f.with(|r| { + (r.url == MCP && r.method == Method::Post).then(|| { + resp( + 401, + &[( + "www-authenticate", + &format!("Bearer resource_metadata=\"{PRM}\""), + )], + "", + ) + }) + }); + f.on( + Method::Get, + PRM, + fjson( + 200, + json!({"resource": MCP, "authorization_servers": [NEW_AS], "scopes_supported": ["read:docs", "offline_access"]}), + ), + ); + f.on( + Method::Get, + "https://login.example.net/.well-known/oauth-authorization-server/t1", + fjson( + 200, + json!({ + "issuer": NEW_AS, + "authorization_endpoint": NEW_AUTHORIZE, + "token_endpoint": "https://login.example.net/oauth/token", + "registration_endpoint": "https://login.example.net/t1/register", + "code_challenge_methods_supported": ["S256"], + "token_endpoint_auth_methods_supported": ["none"], + }), + ), + ); + f.on( + Method::Post, + "https://login.example.net/t1/register", + fjson( + 201, + json!({"client_id": "fresh", "token_endpoint_auth_method": "none"}), + ), + ); + f.with(move |r| { + r.url + .starts_with(NEW_AUTHORIZE) + .then(|| resp(authorize_status, &[], "")) + }); + } + + /// The sign-in starts from what the server says now (its `401`, its + /// protected resource metadata, its authorization server's metadata), + /// not from addresses saved when it was added: a vendor that moves its + /// sign-in server is followed, with a new client there. + #[tokio::test] + async fn a_sign_in_starts_from_the_servers_current_metadata() { + let r = rig("TEAM#a"); + moved_server(&r.http, 302); + let mut s = server(); + r.store.put_server("TEAM#a", &s).await.unwrap(); + let url = + r.rt.start_sign_in( + &mut s, + &Owner::Team, + "USER#1", + "a@x.com", + "https://app.example.com/cb/", + None, + ) + .await + .unwrap(); + assert!(url.starts_with(NEW_AUTHORIZE), "{url}"); + let q: HashMap = reqwest::Url::parse(&url) + .unwrap() + .query_pairs() + .into_owned() + .collect(); + assert_eq!(q["client_id"], "fresh"); + assert_eq!(q["resource"], MCP); + assert_eq!(q["code_challenge_method"], "S256"); + assert_eq!(q["scope"], "read:docs offline_access"); + let saved = r.store.get_server("TEAM#a", "docs").await.unwrap().unwrap(); + let o = saved.oauth.unwrap(); + assert_eq!(o.issuer, NEW_AS); + assert_eq!(o.client_id, "fresh"); + assert_eq!(o.discovered_at, 1_000_000); + // Within a few minutes the saved settings are used as they are. + let before = r.http.sent_to(PRM).len(); + let mut s = r.store.get_server("TEAM#a", "docs").await.unwrap().unwrap(); + r.rt.start_sign_in( + &mut s, + &Owner::Team, + "USER#1", + "a@x.com", + "https://app.example.com/cb/", + None, + ) + .await + .unwrap(); + assert_eq!(r.http.sent_to(PRM).len(), before); + // After that they are read again. + r.now.fetch_add(DISCOVERY_TTL_SECS + 1, Ordering::SeqCst); + r.rt.start_sign_in( + &mut s, + &Owner::Team, + "USER#1", + "a@x.com", + "https://app.example.com/cb/", + None, + ) + .await + .unwrap(); + assert_eq!(r.http.sent_to(PRM).len(), before + 1); + } + + /// A sign-in page that answers 5xx is never where a person is sent: the + /// start says the provider's sign-in is failing on its side, with the + /// status, and leaves nothing waiting. + #[tokio::test] + async fn a_sign_in_page_that_is_down_is_said_plainly() { + let r = rig("TEAM#a"); + moved_server(&r.http, 500); + let mut s = server(); + s.name = "Atlassian".into(); + r.store.put_server("TEAM#a", &s).await.unwrap(); + let e = + r.rt.start_sign_in( + &mut s, + &Owner::Team, + "USER#1", + "a@x.com", + "https://app.example.com/cb/", + None, + ) + .await + .unwrap_err(); + assert_eq!(e, provider_down("Atlassian", 500)); + assert!(e.contains("failing on Atlassian's side (HTTP 500)"), "{e}"); + assert!(r.store.list_pending("TEAM#a").await.unwrap().is_empty()); + // It was asked once with fresh settings, and once more after reading + // them again: never more. + assert!( + r.http + .sent() + .iter() + .filter(|q| q.url.starts_with(NEW_AUTHORIZE)) + .count() + <= 2 + ); + // A provider's own API with fixed addresses (a knowledge source) is + // neither read again nor probed. + let mut k = server(); + k.id = "ks-notion".into(); + k.catalog_id = "source:notion".into(); + k.oauth.as_mut().unwrap().registration = "manual".into(); + assert!(!discovers(&k)); + assert!(discovers(&server())); + } + + /// A catalog server whose vendor moved it (Atlassian's v1 address to + /// v2) is moved on its next sign-in, with nothing to fix by hand. + #[test] + fn a_catalog_server_follows_the_catalogs_address() { + assert_eq!( + crate::mcp_catalog::moved_remote_url( + "atlassian", + "atlassian", + "https://mcp.atlassian.com/v1/mcp" + ), + Some("https://mcp.atlassian.com/v2/mcp") + ); + assert_eq!( + crate::mcp_catalog::moved_remote_url( + "atlassian", + "atlassian", + "https://mcp.atlassian.com/v2/mcp/" + ), + None + ); + // A server added by address, or another record, keeps its own. + assert_eq!( + crate::mcp_catalog::moved_remote_url("wiki", "", "https://mcp.example.com/mcp"), + None + ); + assert_eq!( + crate::mcp_catalog::moved_remote_url( + "ks-x", + "atlassian", + "https://mcp.atlassian.com/v1/mcp" + ), + None + ); } fn urlencoding_like(s: &str) -> String { diff --git a/services/common/src/mcp_remote/store.rs b/services/common/src/mcp_remote/store.rs index bc0ac0588..694de8dd0 100644 --- a/services/common/src/mcp_remote/store.rs +++ b/services/common/src/mcp_remote/store.rs @@ -165,6 +165,11 @@ pub struct OAuthSettings { /// Where a refresh token is exchanged, when the provider uses its own /// address for that (Figma). Empty means the token endpoint. pub refresh_endpoint: String, + /// Unix seconds when the settings above were last read from the + /// server's own metadata (0: never, or a provider whose addresses are + /// fixed). A sign-in starts from metadata at most + /// [`super::runtime::DISCOVERY_TTL_SECS`] old. + pub discovered_at: i64, } impl OAuthSettings { @@ -182,6 +187,7 @@ impl OAuthSettings { resource: p.resource.clone(), scopes: p.scopes.clone(), legacy: p.legacy, + discovered_at: chrono::Utc::now().timestamp(), ..Default::default() } } @@ -220,6 +226,7 @@ impl OAuthSettings { "extra_authorize": self.extra_authorize, "token_body_json": self.token_body_json, "refresh_endpoint": self.refresh_endpoint, + "discovered_at": self.discovered_at, }) } @@ -255,6 +262,7 @@ impl OAuthSettings { .unwrap_or_default(), token_body_json: v["token_body_json"].as_bool().unwrap_or(false), refresh_endpoint: st("refresh_endpoint"), + discovered_at: v["discovered_at"].as_i64().unwrap_or(0), } } } diff --git a/services/gateway/src/routes/connectors.rs b/services/gateway/src/routes/connectors.rs index 73695e154..805bba435 100644 --- a/services/gateway/src/routes/connectors.rs +++ b/services/gateway/src/routes/connectors.rs @@ -262,7 +262,7 @@ fn confluence_access<'a>( StepError::new( "reach", "The Coderhelm app in Jira can't reach Confluence.", - "Update the app in Jira, then open Coderhelm Settings there and save.", + "The Jira app no longer reads Confluence. Connect Confluence in Settings, Integrations, Atlassian (an Atlassian sign-in, or an API token).", ) })?; Ok(Access::JiraApp { @@ -651,7 +651,7 @@ pub async fn save( if c.write_enabled { return Err(fail( StatusCode::BAD_REQUEST, - "The Atlassian sign-in only reads Confluence. To add text to pages, connect Confluence with an API token or the Jira app.", + "The Atlassian sign-in only reads Confluence. To add text to pages, save an API token in Settings, Integrations, Atlassian, Confluence.", )); } } @@ -659,7 +659,7 @@ pub async fn save( let Some(a) = &app else { return Err(fail( StatusCode::BAD_REQUEST, - "The Coderhelm app in Jira can't reach Confluence yet. Update the app in Jira, then open Coderhelm Settings there and save.", + "The Coderhelm app in Jira can't reach Confluence. The Jira app no longer reads Confluence. Connect Confluence in Settings, Integrations, Atlassian (an Atlassian sign-in, or an API token).", )); }; c.site = a.site.clone(); diff --git a/services/gateway/src/routes/hybrid_install.rs b/services/gateway/src/routes/hybrid_install.rs index be151e883..b7d2b383f 100644 --- a/services/gateway/src/routes/hybrid_install.rs +++ b/services/gateway/src/routes/hybrid_install.rs @@ -633,13 +633,20 @@ pub fn apply_settings(l: &mut Local, b: &SettingsBody) -> Result<(), &'static st } if let Some(list) = &b.integrations { let allowed: Vec<&str> = integrations::hosted_ids().collect(); - if list.iter().any(|i| !allowed.contains(&i.as_str())) { + if expanded(list) + .iter() + .any(|i| !allowed.contains(&i.as_str())) + { return Err("an integration that can't use CoderHelm's app"); } } if let Some(apps) = &b.apps { for (id, v) in apps { - if !integrations::app_choice_ids().any(|x| x == id) { + // An entry's own id (`atlassian`) stands for its pieces. + if !integrations::expand(id) + .iter() + .all(|p| integrations::app_choice_ids().any(|x| x == p)) + { return Err("an integration that can't use CoderHelm's app"); } if v != "coderhelm" && v != "own" { @@ -700,6 +707,12 @@ async fn do_settings( Ok(l) } +/// A page's list of integration ids as the pieces installs store +/// (`atlassian` as `jira` and `confluence`). +fn expanded(list: &[String]) -> Vec { + list.iter().flat_map(|i| integrations::expand(i)).collect() +} + /// A JSON array of strings, if it is one. fn strings(v: &Value) -> Option> { v.as_array().map(|a| { @@ -744,9 +757,10 @@ pub fn legacy_apps_mode(b: &SettingsBody) -> Option<&'static str> { if let Some(apps) = b.apps.as_ref().filter(|a| !a.is_empty()) { return Some(pick(apps.values().any(|v| v == "coderhelm"))); } - b.integrations - .as_ref() - .map(|list| pick(integrations::app_choice_ids().any(|id| list.iter().any(|i| i == id)))) + b.integrations.as_ref().map(|list| { + let list = expanded(list); + pick(integrations::app_choice_ids().any(|id| list.iter().any(|i| i == id))) + }) } /// The integrations to ask CoderHelm for: GitHub when its mode is hosted, @@ -1070,20 +1084,28 @@ async fn status_value(state: &AppState, deep: bool) -> Value { .map(|e| { let mut v = serde_json::to_value(e).unwrap_or_default(); // Registered: what CoderHelm holds. Not yet: what registering applies. + // An entry that covers several pieces (Atlassian: the Jira + // app and the Confluence sign-in) is on when any of them is. + let ids = e.ids(); let uses = if creds.is_some() { - l.integrations.iter().any(|i| i == e.id) + l.integrations.iter().any(|i| ids.contains(&i.as_str())) } else { wanted_integrations(&l, |id| own_app_set(state, id)) .iter() - .any(|i| i == e.id) + .any(|i| ids.contains(&i.as_str())) }; v["uses_coderhelm"] = json!(uses); // The install's own app for this tool, which it uses whichever // Other apps choice was made. - if integrations::app_choice_ids().any(|id| id == e.id) { - v["own_app"] = json!(own_app_set(state, e.id)); + if ids + .iter() + .any(|p| integrations::app_choice_ids().any(|id| id == *p)) + { + v["own_app"] = json!(ids.iter().any(|p| own_app_set(state, p))); } - v["offered"] = json!(offered.as_ref().is_none_or(|o| o.iter().any(|i| i == e.id))); + v["offered"] = json!(offered + .as_ref() + .is_none_or(|o| o.iter().any(|i| ids.contains(&i.as_str())))); v }) .collect(); @@ -2432,7 +2454,7 @@ mod tests { l.github_mode = "hosted".into(); assert_eq!( wanted_integrations(&l, own_figma), - vec!["github", "jira", "notion", "confluence", "google_drive"] + vec!["github", "jira", "confluence", "notion", "google_drive"] ); // Fully private: no app through CoderHelm; GitHub keeps its own choice. l.apps_mode = "private".into(); @@ -2453,7 +2475,7 @@ mod tests { let hosted: Vec<&str> = integrations::CATALOG .iter() .filter(|e| e.mode == integrations::Mode::Hosted && e.id != "github") - .map(|e| e.id) + .flat_map(|e| e.ids().iter().copied()) .collect(); assert_eq!(wanted_integrations(&l, no_own_apps), hosted); // A record migrated by an earlier release, before an entry was added @@ -2598,6 +2620,15 @@ mod tests { assert!(apply_settings(&mut l, &apps(&[("github", "own")])).is_err()); assert!(apply_settings(&mut l, &apps(&[("slack_commands", "coderhelm")])).is_err()); assert!(apply_settings(&mut l, &apps(&[("notion", "both")])).is_err()); + // The one Atlassian entry stands for the Jira app and the Confluence + // sign-in an install chose before. + apply_settings(&mut l, &apps(&[("atlassian", "coderhelm")])).unwrap(); + let listed = SettingsBody { + integrations: Some(vec!["atlassian".into()]), + ..Default::default() + }; + assert_eq!(legacy_apps_mode(&listed), Some("coderhelm")); + apply_settings(&mut l, &listed).unwrap(); // The guide's body takes the same fields. let g = guide_body(br#"{"setup_token":"t","apps_mode":"private","apps":{"confluence":"own"}}"#); diff --git a/services/gateway/src/routes/integrations.rs b/services/gateway/src/routes/integrations.rs index 75eac3fb0..8158afce1 100644 --- a/services/gateway/src/routes/integrations.rs +++ b/services/gateway/src/routes/integrations.rs @@ -388,6 +388,139 @@ fn product_card( v } +/// The one Atlassian card's pieces, in the order the card lists them, with +/// what each does in a person's words. Each piece keeps its own record and +/// its own card JSON (it is set up and fixed where it always was); the page +/// shows one Atlassian. +pub const ATLASSIAN_PARTS: [(&str, &str, &str); 3] = [ + ( + "jira", + "Jira", + "Coderhelm's Jira app (Forge): tickets start work, and their status and comments follow the pull request.", + ), + ( + "confluence", + "Confluence", + "Agents read pages during runs and reviews, and Knowledge syncs the spaces you pick.", + ), + ( + "agent_tools", + "Agent tools", + "Atlassian's own server (Rovo MCP): agents search and read Jira issues and Confluence pages with the tools you allow.", + ), +]; + +/// The one Atlassian card's state, from its pieces' cards: a piece that +/// needs something comes first (named), then what is connected, then +/// nothing set up. +pub fn atlassian_state(parts: &[(&str, &Value)]) -> CardState { + fn name_of(id: &str) -> &str { + ATLASSIAN_PARTS + .iter() + .find(|p| p.0 == id) + .map(|p| p.1) + .unwrap_or(id) + } + let status = |v: &Value| v["status"].as_str().unwrap_or("not_connected").to_string(); + if let Some((id, v)) = parts.iter().find(|(_, v)| { + matches!( + status(v).as_str(), + "needs_reconnect" | "needs_credentials" | "error" + ) + }) { + let st: &'static str = match status(v).as_str() { + "needs_reconnect" => "needs_reconnect", + "needs_credentials" => "needs_credentials", + _ => "error", + }; + let action: &'static str = match v["action"].as_str().unwrap_or("") { + "reconnect" => "reconnect", + "add_credentials" => "add_credentials", + _ => "check_again", + }; + let why = v["reason"].as_str().unwrap_or("").trim().to_string(); + let why = if why.is_empty() { + "needs attention.".to_string() + } else { + why + }; + return cs(st, format!("{}: {why}", name_of(id)), action); + } + let names = |want: bool| -> Vec<&str> { + parts + .iter() + .filter(|(_, v)| (status(v) == "connected") == want) + .map(|(id, _)| name_of(id)) + .collect() + }; + let on = names(true); + if on.is_empty() { + return cs("not_connected", "", "connect"); + } + let off = names(false); + let verb = |n: &[&str], one: &'static str, many: &'static str| { + if n.len() == 1 { + one + } else { + many + } + }; + let mut reason = format!("{} {} connected.", join_and(&on), verb(&on, "is", "are")); + if !off.is_empty() { + reason.push_str(&format!( + " {} {} set up.", + join_and(&off), + verb(&off, "isn't", "aren't") + )); + } + cs("connected", reason, "manage") +} + +/// "a", "a and b", "a, b and c". +fn join_and(words: &[&str]) -> String { + match words { + [] => String::new(), + [one] => one.to_string(), + [rest @ .., last] => format!("{} and {last}", rest.join(", ")), + } +} + +/// The one Atlassian card: the Jira app, Confluence and Atlassian's own +/// server as pieces of one connection. Each piece's card is kept whole +/// under `detail.parts`, so its panel works as before. +pub fn atlassian_card(jira: Value, confluence: Value, agent_tools: Value) -> Value { + let parts = [ + ("jira", &jira), + ("confluence", &confluence), + ("agent_tools", &agent_tools), + ]; + let st = atlassian_state(&parts); + let first_on = parts.iter().map(|(_, v)| *v).find(|v| { + v["status"] == "connected" && !v["connected_by"].as_str().unwrap_or("").is_empty() + }); + let app_update = jira["detail"]["app_update"].clone(); + let mut v = card( + "atlassian", + "Atlassian", + "Jira and Confluence in one connection: tickets start work and follow the pull request, agents read Confluence pages and Knowledge syncs them, and agents can use Atlassian's own tools.", + st, + "", + "", + json!({ + "app_update": app_update, + "parts": parts.iter().map(|(id, item)| { + let (_, name, what) = ATLASSIAN_PARTS.iter().find(|p| p.0 == *id).copied().unwrap_or((id, id, "")); + json!({ "id": id, "name": name, "what": what, "item": item }) + }).collect::>(), + }), + ); + if let Some(p) = first_on { + v["connected_by"] = p["connected_by"].clone(); + v["connected_at"] = p["connected_at"].clone(); + } + v +} + /// The sign-in a team (or, for Sanity, this person) made so Knowledge can /// sync a product: its record and its connection, when someone signed in. #[derive(Debug, Clone)] @@ -530,7 +663,7 @@ pub fn confluence_product( } let needs = [Need { for_use: Use::Knowledge, - detail: "Syncing pages into Knowledge needs an Atlassian sign-in or an API token: the Jira app only reads pages during runs.".into(), + detail: "Syncing pages into Knowledge needs an Atlassian sign-in or an API token. The Jira app is Jira-only: sites that still read pages through it keep that until their app updates.".into(), action: Some(Action::link("Connect in Knowledge", KNOWLEDGE_HREF)), }]; product_state(&[Use::Runs, Use::Knowledge], &ways, &needs) @@ -962,7 +1095,9 @@ pub async fn list( } else { None }; - items.push(card( + // Jira, Confluence and Atlassian's own server are one Atlassian card: + // each piece is worked out as before and kept under it. + let jira_part = card( "jira", "Jira", "Starts work from Jira tickets and keeps their status in step with the pull request.", @@ -974,7 +1109,9 @@ pub async fn list( "", "/settings/integrations/jira", json!({ "app": forge, "app_update": app_update }), - )); + ); + let mut confluence_part = Value::Null; + let mut agent_tools_part = Value::Null; // AWS accounts: one card each (or one to connect the first). if accounts.is_empty() { @@ -1043,7 +1180,7 @@ pub async fn list( let p = confluence_product(c, k, sources_of(&sources, SourceKind::Confluence)); let mut detail = detail; detail["knowledge"] = json!(k.map(KnowledgeSignIn::json)); - items.push(product_card( + confluence_part = product_card( &id, &name, does, @@ -1051,7 +1188,7 @@ pub async fn list( c.map(|c| c.updated_at.as_str()).unwrap_or(""), "", detail, - )); + ); continue; } items.push(card( @@ -1196,7 +1333,7 @@ pub async fn list( "knowledge": k.map(KnowledgeSignIn::json), "unused": unused, }); - items.push(product_card( + let item = product_card( &id, p["name"].as_str().unwrap_or(&id), p["description"].as_str().unwrap_or(""), @@ -1204,8 +1341,14 @@ pub async fn list( &tested_at, "", detail, - )); + ); + if id == "atlassian" { + agent_tools_part = item; + } else { + items.push(item); + } } + items.push(atlassian_card(jira_part, confluence_part, agent_tools_part)); // Google Drive is only ever synced into Knowledge: it has a card here // once the team signed in, so the sign-in is seen where sign-ins are. @@ -1546,6 +1689,85 @@ mod tests { a } + fn part(id: &str, status: &str, reason: &str, action: &str) -> Value { + let mut v = card( + id, + id, + "", + cs("not_connected", "", "connect"), + "", + "", + json!({}), + ); + v["status"] = json!(status); + v["reason"] = json!(reason); + v["action"] = json!(action); + v + } + + #[test] + fn atlassian_is_one_card_over_its_three_pieces() { + // Nothing set up: one card to connect. + let off = |id| part(id, "not_connected", "", "connect"); + let c = atlassian_card(off("jira"), off("confluence"), off("atlassian")); + assert_eq!(c["id"], "atlassian"); + assert_eq!(c["name"], "Atlassian"); + assert_eq!(c["section"], "code"); + assert_eq!(c["status"], "not_connected"); + assert_eq!(c["action"], "connect"); + let parts = c["detail"]["parts"].as_array().unwrap(); + let ids: Vec<_> = parts.iter().map(|p| p["id"].as_str().unwrap()).collect(); + assert_eq!(ids, vec!["jira", "confluence", "agent_tools"]); + // Each piece's own card is kept whole, so its panel works as before. + assert_eq!(parts[1]["item"]["id"], "confluence"); + assert_eq!(parts[2]["item"]["id"], "atlassian"); + assert!(parts + .iter() + .all(|p| p["what"].as_str().unwrap().ends_with('.'))); + + // An existing Jira app and Confluence sign-in: connected, saying which. + let mut jira = part("jira", "connected", "", "manage"); + jira["connected_by"] = json!("admin@example.com"); + jira["detail"]["app_update"] = json!({ "message": "Update the app." }); + let c = atlassian_card( + jira, + part("confluence", "connected", "", "manage"), + off("atlassian"), + ); + assert_eq!(c["status"], "connected"); + assert_eq!( + c["reason"], + "Jira and Confluence are connected. Agent tools isn't set up." + ); + assert_eq!(c["connected_by"], "admin@example.com"); + // The Jira app's update notice still shows under the one row. + assert_eq!(c["detail"]["app_update"]["message"], "Update the app."); + + // A piece that needs something comes first, named. + let c = atlassian_card( + part("jira", "connected", "", "manage"), + part( + "confluence", + "needs_reconnect", + "The sign-in has to be renewed.", + "reconnect", + ), + part("atlassian", "connected", "", "manage"), + ); + assert_eq!(c["status"], "needs_reconnect"); + assert_eq!(c["action"], "reconnect"); + assert_eq!(c["reason"], "Confluence: The sign-in has to be renewed."); + let all = atlassian_state(&[ + ("jira", &part("jira", "connected", "", "manage")), + ("confluence", &part("confluence", "connected", "", "manage")), + ("agent_tools", &part("atlassian", "connected", "", "manage")), + ]); + assert_eq!( + all.reason, + "Jira, Confluence and Agent tools are connected." + ); + } + #[test] fn sections_follow_the_page() { assert_eq!(section_of("github"), "code"); diff --git a/services/gateway/src/routes/jira_app_status.rs b/services/gateway/src/routes/jira_app_status.rs index 6775f9bd2..1a2dd568d 100644 --- a/services/gateway/src/routes/jira_app_status.rs +++ b/services/gateway/src/routes/jira_app_status.rs @@ -145,7 +145,8 @@ pub async fn for_team(state: &AppState, team_id: &str) -> Option { /// GET /api/integrations/jira/app: `{ "behind": null }` when the team's /// Jira site runs the latest app (or nothing is known), otherwise what it -/// runs, what it lacks and the Manage apps page. +/// runs, what it lacks, where a site admin accepts the update (Atlassian +/// Administration, Connected apps) and the installation link when published. pub async fn get_status( State(state): State>, Extension(claims): Extension, diff --git a/services/worker/src/passes/release_notes.rs b/services/worker/src/passes/release_notes.rs index 33a454b70..862cd35d0 100644 --- a/services/worker/src/passes/release_notes.rs +++ b/services/worker/src/passes/release_notes.rs @@ -420,6 +420,34 @@ async fn jira_summaries( } /// A registered Forge web trigger URL (by field) + the shared secret. +/// What release notes say when nothing can publish to Confluence. +pub const CONFLUENCE_NOT_CONNECTED: &str = "Confluence publishing needs the Confluence part of the Atlassian connection with an API token: Settings, Integrations, Atlassian, Confluence, Use an API token. The account needs edit access under the parent page."; + +/// The team's Confluence connection with a saved email and API token, and +/// the token opened. `None` when the team has none (or it can't be opened). +async fn confluence_token( + state: &WorkerState, + team_id: &str, +) -> Option<(common::live::connectors::Connector, String)> { + use common::live::connectors::{self, ConnKind}; + let list = connectors::list(&state.dynamo, &state.config.settings_table_name, team_id) + .await + .ok()?; + let conn = list.into_iter().find(|c| { + c.kind() == ConnKind::Confluence + && !c.via_jira_app() + && !c.via_sign_in() + && !c.key_sealed.is_empty() + })?; + match common::live::secret::open(&state.kms, team_id, &conn.key_sealed).await { + Ok(k) => Some((conn, k)), + Err(e) => { + warn!(error = %e, "Could not open the Confluence token for release notes"); + None + } + } +} + async fn forge_trigger( state: &WorkerState, team_id: &str, @@ -861,32 +889,54 @@ async fn run_locked( if !cfg.confluence_parent_id.trim().is_empty() && (regenerate || rec.get("confluence_url").is_none_or(|s| s.is_empty())) { - let (url, secret) = forge_trigger(state, &msg.team_id, "publish_release_url") + let entry_html = to_storage(&entry); + let key = format!("{owner}/{repo}@{tag}"); + // The Confluence part of the team's Atlassian connection (its saved + // email and API token) publishes. A site whose Jira app still has + // Confluence access keeps publishing through it until the team saves + // a token; the Jira app no longer asks for Confluence access. + let url = if let Some((conn, token)) = confluence_token(state, &msg.team_id).await { + common::live::confluence_changelog::Site { + site: &conn.site, + email: &conn.email, + token: &token, + http: &common::live::http::Https, + } + .publish(&common::live::confluence_changelog::Entry { + parent_id: cfg.confluence_parent_id.trim(), + container: cfg.confluence_container.trim(), + year: &date[..4], + key: &key, + html: &entry_html, + }) .await - .ok_or("Confluence publishing isn't connected — update the CoderHelm app in Jira and reconnect it in Settings under Integrations")?; - let resp = state - .http - .post(&url) - .json(&json!({ - "forge_secret": secret, - "spaceKey": cfg.confluence_space.trim(), - "parentId": cfg.confluence_parent_id.trim(), - "containerTitle": cfg.confluence_container.trim(), - "year": &date[..4], - "entryKey": format!("{owner}/{repo}@{tag}"), - "entryHtml": to_storage(&entry), - })) - .send() - .await?; - let status = resp.status(); - let body: Value = resp.json().await.unwrap_or(Value::Null); - if !status.is_success() { - return Err(format!("Confluence publish failed ({status}): {body}").into()); - } - rec.insert( - "confluence_url".into(), - body["url"].as_str().unwrap_or("published").to_string(), - ); + .map_err(|e| format!("Confluence publish failed: {e}"))? + } else { + let (url, secret) = forge_trigger(state, &msg.team_id, "publish_release_url") + .await + .ok_or(CONFLUENCE_NOT_CONNECTED)?; + let resp = state + .http + .post(&url) + .json(&json!({ + "forge_secret": secret, + "spaceKey": cfg.confluence_space.trim(), + "parentId": cfg.confluence_parent_id.trim(), + "containerTitle": cfg.confluence_container.trim(), + "year": &date[..4], + "entryKey": key, + "entryHtml": entry_html, + })) + .send() + .await?; + let status = resp.status(); + let body: Value = resp.json().await.unwrap_or(Value::Null); + if !status.is_success() { + return Err(format!("Confluence publish failed ({status}): {body}").into()); + } + body["url"].as_str().unwrap_or("published").to_string() + }; + rec.insert("confluence_url".into(), url); save_record(state, &msg.team_id, &record_sk, tag, &rec).await; }