diff --git a/coderhelm-jira/src/index.js b/coderhelm-jira/src/index.js index d2daf3b23..90e76ee8f 100644 --- a/coderhelm-jira/src/index.js +++ b/coderhelm-jira/src/index.js @@ -8,6 +8,7 @@ const { existingComments } = require("./comments"); const { postReply, parentIdOf } = require("./thread-reply"); const { versionFields } = require("./version"); const { relatedTickets } = require("./related"); +const { registerIfVersionChanged, registerAgainReply } = require("./register"); /** Jira's comment calls as the app, for a threaded reply (see thread-reply.js). */ const jiraComments = { @@ -190,6 +191,7 @@ exports.handler = async (event, context) => { }); console.log(`Forwarded comment on ${issue.key} → gateway (${response.status})`); + await registerIfVersionChanged(config); return; } @@ -268,11 +270,24 @@ exports.handler = async (event, context) => { }); console.log(`Forwarded ${issue.key} → gateway (${response.status})`); + // A new version (a minor one arrives with no lifecycle event) may have + // new web triggers: CoderHelm learns them now. + await registerIfVersionChanged(config); }; // ── Web trigger: list Jira projects ────────────────────────────────────────── exports.listProjectsHandler = async (request) => { try { + // CoderHelm asking for every trigger link again (one was missing). + let asked = null; + try { + asked = JSON.parse((request && request.body) || "{}"); + } catch (e) { + asked = null; + } + if (asked && asked.register_again === true) { + return await registerAgainReply(asked, await storage.get("coderhelm-config")); + } const res = await api.asApp().requestJira(route`/rest/api/3/project?expand=lead`); if (!res.ok) { return { statusCode: res.status, body: JSON.stringify({ error: "Failed to fetch projects" }) }; diff --git a/coderhelm-jira/src/register.js b/coderhelm-jira/src/register.js index 9dcffb07a..24c9fcf8f 100644 --- a/coderhelm-jira/src/register.js +++ b/coderhelm-jira/src/register.js @@ -1,21 +1,39 @@ // Tells the CoderHelm gateway where this installation's web triggers are. // // Web trigger URLs belong to one installation, so CoderHelm only learns them -// when the app sends them. That happens when an admin saves the settings page -// and again, on its own, whenever the app is installed or upgraded to a new -// major version (a version that adds a web trigger is one). So a site that -// accepts an update gets the new abilities without anyone re-saving settings. +// when the app sends them. That happens when an admin saves the settings page, +// when the app is installed or upgraded to a new major version, on the first +// event after the running version changes (Forge rolls a minor version out +// to every site without any lifecycle event, and a minor version can add a +// web trigger), and whenever CoderHelm finds a link missing and asks for +// them again through the project-list trigger. So a site gets new abilities +// without anyone re-saving settings. -const api = require("@forge/api"); -const { storage, webTrigger, route } = api; +/** The Forge SDK, loaded when first used, so this file (and its tests) load without it. */ +function forge() { + return require("@forge/api"); +} const { GATEWAY_URL } = require("./gateway"); -const { versionFields } = require("./version"); +const { versionFields, appInfo } = require("./version"); + +/** Where the version that last registered is kept. */ +const REGISTERED_VERSION_KEY = "coderhelm-registered-version"; + +/** One trigger's URL, or "" when this version of the app doesn't have it. */ +async function triggerUrl(key, getUrl = (k) => forge().webTrigger.getUrl(k)) { + try { + return (await getUrl(key)) || ""; + } catch (e) { + console.log(`No web trigger ${key} in this version: ${e}`); + return ""; + } +} /** The site's address (e.g. https://yourcompany.atlassian.net), or "". */ async function siteUrl() { try { - const res = await api.asApp().requestJira(route`/rest/api/3/serverInfo`); + const res = await forge().asApp().requestJira(forge().route`/rest/api/3/serverInfo`); if (res.ok) { const info = await res.json(); return info.baseUrl || ""; @@ -35,21 +53,21 @@ async function registerWithGateway(config) { const body = { team_id: config.teamId, forge_secret: config.forgeSecret, - 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"), + list_projects_url: await triggerUrl("list-projects-trigger"), + create_ticket_url: await triggerUrl("create-ticket-trigger"), + add_comment_url: await triggerUrl("add-comment-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"), + get_issues_url: await triggerUrl("get-issues-trigger"), confluence_trigger_url: "", site_url: await siteUrl(), // The version that registers: after an accepted update, CoderHelm // knows the site caught up at once. ...versionFields(), }; - const res = await api.fetch(`${GATEWAY_URL}/integrations/jira/forge-register`, { + const res = await forge().fetch(`${GATEWAY_URL}/integrations/jira/forge-register`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), @@ -67,7 +85,7 @@ async function registerWithGateway(config) { * triggers reach CoderHelm without an admin re-saving the settings page. */ exports.lifecycleHandler = async (event) => { - const config = await storage.get("coderhelm-config"); + const config = await forge().storage.get("coderhelm-config"); if (!config || !config.teamId || !config.forgeSecret) { console.log(`Lifecycle ${event && event.eventType}: not configured yet, nothing to register`); return; @@ -78,4 +96,51 @@ exports.lifecycleHandler = async (event) => { ); }; +/** + * Registers again when the running version isn't the one that last + * registered (`store` and `register` are stand-ins in tests). Returns true + * when it registered. + */ +async function registerIfVersionChanged(config, deps = {}) { + const store = deps.store || forge().storage; + const register = deps.register || registerWithGateway; + const version = (deps.appInfo || appInfo)().appVersion; + if (!version || !config || !config.teamId || !config.forgeSecret) return false; + if ((await store.get(REGISTERED_VERSION_KEY)) === version) return false; + const r = await register(config); + if (r.urlsRegistered) await store.set(REGISTERED_VERSION_KEY, version); + console.log(`Version ${version}: trigger URLs ${r.urlsRegistered ? "registered" : `not registered (${r.urlError})`}`); + return r.urlsRegistered; +} + +/** Same length and same bytes, without leaking how much matched. */ +function sameSecret(a, b) { + const crypto = require("node:crypto"); + const x = Buffer.from(String(a || "")); + const y = Buffer.from(String(b || "")); + return x.length > 0 && x.length === y.length && crypto.timingSafeEqual(x, y); +} + +/** + * A request to the project-list trigger that asks the app to register all of + * its links again (`{ register_again: true, forge_secret }`): CoderHelm found + * one missing. Answers the trigger's reply, or null for any other request. + */ +async function registerAgainReply(body, config, register = registerWithGateway) { + if (!body || body.register_again !== true) return null; + if (!config || !config.teamId || !sameSecret(body.forge_secret, config.forgeSecret)) { + return { statusCode: 403, body: JSON.stringify({ error: "Wrong secret." }) }; + } + const r = await register(config); + return { + statusCode: r.urlsRegistered ? 200 : 502, + headers: { "Content-Type": ["application/json"] }, + body: JSON.stringify({ registered: r.urlsRegistered, error: r.urlError }), + }; +} + exports.registerWithGateway = registerWithGateway; +exports.registerIfVersionChanged = registerIfVersionChanged; +exports.registerAgainReply = registerAgainReply; +exports.triggerUrl = triggerUrl; +exports.REGISTERED_VERSION_KEY = REGISTERED_VERSION_KEY; diff --git a/coderhelm-jira/test/register.test.js b/coderhelm-jira/test/register.test.js new file mode 100644 index 000000000..83ce6190d --- /dev/null +++ b/coderhelm-jira/test/register.test.js @@ -0,0 +1,97 @@ +// A site whose app gained a web trigger after it registered (a minor +// version arrives with no lifecycle event) sends CoderHelm the new link by +// itself: on the first event after the version changes, and whenever +// CoderHelm asks through the project-list trigger. + +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const { + registerIfVersionChanged, + registerAgainReply, + triggerUrl, + REGISTERED_VERSION_KEY, +} = require("../src/register"); + +const CONFIG = { teamId: "TEAM#1", forgeSecret: "secret-1" }; + +function memoryStore(initial = {}) { + const m = new Map(Object.entries(initial)); + return { get: async (k) => m.get(k), set: async (k, v) => m.set(k, v), m }; +} + +test("a version change registers once; the same version again doesn't", async () => { + const store = memoryStore({ [REGISTERED_VERSION_KEY]: "7.2.0" }); + let calls = 0; + const register = async () => { + calls += 1; + return { urlsRegistered: true }; + }; + const appInfo = () => ({ appVersion: "7.3.0" }); + assert.equal(await registerIfVersionChanged(CONFIG, { store, register, appInfo }), true); + assert.equal(store.m.get(REGISTERED_VERSION_KEY), "7.3.0"); + assert.equal(await registerIfVersionChanged(CONFIG, { store, register, appInfo }), false); + assert.equal(calls, 1); +}); + +test("a site that never stored a version registers on its next event", async () => { + const store = memoryStore(); + const register = async () => ({ urlsRegistered: true }); + const appInfo = () => ({ appVersion: "7.3.0" }); + assert.equal(await registerIfVersionChanged(CONFIG, { store, register, appInfo }), true); +}); + +test("a failed registration is tried again on the next event", async () => { + const store = memoryStore(); + let ok = false; + const register = async () => ({ urlsRegistered: ok, urlError: "Gateway returned 503" }); + const appInfo = () => ({ appVersion: "7.3.0" }); + assert.equal(await registerIfVersionChanged(CONFIG, { store, register, appInfo }), false); + assert.equal(store.m.get(REGISTERED_VERSION_KEY), undefined); + ok = true; + assert.equal(await registerIfVersionChanged(CONFIG, { store, register, appInfo }), true); +}); + +test("an unconfigured site or an unknown version registers nothing", async () => { + const store = memoryStore(); + const register = async () => assert.fail("must not register"); + assert.equal(await registerIfVersionChanged({ teamId: "" }, { store, register, appInfo: () => ({ appVersion: "7.3.0" }) }), false); + assert.equal(await registerIfVersionChanged(CONFIG, { store, register, appInfo: () => ({ appVersion: "" }) }), false); +}); + +test("CoderHelm's request to register again is checked against the site's secret", async () => { + let calls = 0; + const register = async () => { + calls += 1; + return { urlsRegistered: true }; + }; + assert.equal(await registerAgainReply({}, CONFIG, register), null); + const wrong = await registerAgainReply({ register_again: true, forge_secret: "nope-123" }, CONFIG, register); + assert.equal(wrong.statusCode, 403); + const none = await registerAgainReply({ register_again: true }, CONFIG, register); + assert.equal(none.statusCode, 403); + assert.equal(calls, 0); + const ok = await registerAgainReply({ register_again: true, forge_secret: "secret-1" }, CONFIG, register); + assert.equal(ok.statusCode, 200); + assert.deepEqual(JSON.parse(ok.body), { registered: true }); + assert.equal(calls, 1); +}); + +test("a trigger this version lacks is sent empty, never failing the others", async () => { + const getUrl = async (k) => { + if (k === "get-issues-trigger") throw new Error("no such trigger"); + return `https://x.hello.atlassian-dev.net/x1/${k}`; + }; + assert.equal(await triggerUrl("get-issues-trigger", getUrl), ""); + assert.match(await triggerUrl("add-comment-trigger", getUrl), /add-comment-trigger$/); +}); + +test("both event paths register again after a version change, and the project list answers the request", () => { + const index = fs.readFileSync(path.join(__dirname, "..", "src", "index.js"), "utf8"); + assert.equal(index.split("await registerIfVersionChanged(config)").length - 1, 2); + const lp = index.split("exports.listProjectsHandler")[1].split("exports.")[0]; + assert.match(lp, /registerAgainReply/); + const manifest = fs.readFileSync(path.join(__dirname, "..", "manifest.yml"), "utf8"); + assert.match(manifest, /key: get-issues-trigger/); +}); diff --git a/docs/incidents/jc_jira_connected_in_chat.md b/docs/incidents/jc_jira_connected_in_chat.md new file mode 100644 index 000000000..e787046aa --- /dev/null +++ b/docs/incidents/jc_jira_connected_in_chat.md @@ -0,0 +1,7 @@ +# jc. `jc_jira_connected_in_chat` + +**What happened:** A new user on a self-hosted install asked chat what was waiting on him. Chat answered that Jira wasn't connected to Coderhelm, while Settings, Integrations showed Atlassian connected and runs from Jira tickets worked. The install had linked its Jira site through CoderHelm before the Jira app had its ticket lookup, and copied the hosted links once. The app gained the lookup in a minor version, which Forge rolls out with no lifecycle event, so the app never registered the new link, and the install never copied again. Chat counted "no lookup link" as "not connected", a different test from the one the integrations page used. + +**The guarantee:** One answer to "is Jira connected" for every reader: the app registered with its secret, or a plain Jira webhook. A missing ability is named as that ability ("Jira is connected, but the app hasn't registered its ticket lookup yet"), never as "not connected". The system puts it right by itself: the app registers again on the first event after any version change, CoderHelm asks the app to register again through its project-list link whenever a link the app always registers is missing, and a linked install copies the hosted settings again whenever the triggers the site registered on CoderHelm change. Until then, tickets are answered from what Coderhelm's runs know. + +**Where it's enforced:** `common::jira_connection::{Connection, Gap, missing_registrations, registered, copy_is_stale}`; in the gateway, `chat_work_tickets::{Jira, load}`, `jira_heal::heal`, `hybrid_install::{jira_sync_plan, refresh_jira_copy}`, `hybrid_jira::linked_triggers`, and the integrations page; in the Jira app, `register.js` (`registerIfVersionChanged`, `registerAgainReply`). diff --git a/docs/jira-app-release.md b/docs/jira-app-release.md index e6c399eb5..44cdb9555 100644 --- a/docs/jira-app-release.md +++ b/docs/jira-app-release.md @@ -50,7 +50,7 @@ A major version still deploys. The run then: 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. +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. A minor version reaches a site with no lifecycle event, so the app also sends the site's web trigger URLs to CoderHelm again on its first event after any version change, and CoderHelm asks for them through the project-list trigger whenever a link the app always registers is missing (`common::jira_connection`). When a major update is accepted, the lifecycle trigger sends them as well. Nobody has to re-save the settings page, and a self-hosted install linked through CoderHelm copies the links again when the site's registered triggers change. ## Which version each site runs diff --git a/services/common/src/jira_connection.rs b/services/common/src/jira_connection.rs new file mode 100644 index 000000000..bec67b955 --- /dev/null +++ b/services/common/src/jira_connection.rs @@ -0,0 +1,348 @@ +//! One answer to "is Jira connected", and to "which of its abilities can be +//! used right now", from the team's `JIRA#config` record. +//! +//! The integrations page, chat and the runs all read the same record, and +//! used to ask it different questions: the page counted the Jira app as +//! connected once it had registered its comment trigger, while chat counted +//! Jira as connected only when the ticket lookup trigger was there too. A +//! site whose app gained the lookup after it registered (Forge rolls a new +//! minor version out to every site without telling the app) showed as +//! connected on the page and ran tickets, while chat told people Jira +//! wasn't connected at all. +//! +//! So here: +//! +//! - [`Connection::connected`] is the only test of "connected", for every +//! reader: the app registered with its secret, or a plain Jira webhook. +//! - [`Connection::ticket_reads`] says whether tickets can be read on +//! demand, and when not, exactly which ability is missing and why +//! ([`Gap`], [`Gap::words`]): never "not connected" for a connected team. +//! - [`missing_registrations`] names the triggers the current app always +//! registers that the record lacks, so the caller asks the app to register +//! again by itself ([`REGISTER_AGAIN`]) instead of telling a person. +//! - [`registered`] lists the triggers a record holds, so a self-hosted +//! install linked through CoderHelm knows when the hosted record gained one +//! and copies it again. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; + +type Item = HashMap; + +/// The Jira app's triggers: the `JIRA#config` field that holds each, and the +/// trigger's name (as the hybrid proxy path names it). +pub const TRIGGERS: &[(&str, &str)] = &[ + ("list_projects_url", "list_projects"), + ("create_ticket_url", "create_ticket"), + ("add_comment_url", "add_comment"), + ("publish_release_url", "publish_release"), + ("get_issues_url", "get_issues"), + ("confluence_trigger_url", "confluence"), +]; + +/// The triggers the current app registers on every site +/// (`coderhelm-jira/src/register.js`). The release and Confluence triggers +/// are left empty by the app on purpose (Confluence goes through the +/// Atlassian connection), so their absence is never a gap. +pub const ALWAYS_REGISTERED: &[&str] = &[ + "list_projects_url", + "create_ticket_url", + "add_comment_url", + "get_issues_url", +]; + +/// The body that asks the app, through its project-list trigger, to send +/// all of its trigger links to CoderHelm again (`coderhelm-jira`'s +/// `listProjectsHandler`). The app checks `forge_secret` against its own. +pub const REGISTER_AGAIN: &str = "register_again"; + +/// Words for a team with no Jira connection at all. +pub const NOT_CONNECTED: &str = "Jira isn't connected to Coderhelm"; + +fn text(item: &Item, k: &str) -> String { + item.get(k) + .and_then(|v| v.as_s().ok()) + .map(|v| v.trim().to_string()) + .unwrap_or_default() +} + +/// A trigger link the code may call: https only. +fn link(item: &Item, k: &str) -> Option { + Some(text(item, k)).filter(|u| u.starts_with("https://")) +} + +/// The team's Jira connection, as every reader sees it. +#[derive(Clone, Default, PartialEq, Eq)] +pub struct Connection { + /// The Coderhelm app registered on a site: its comment trigger and the + /// shared secret are kept. + pub app: bool, + /// A plain Jira webhook is set up (the `JIRA_SECRET` record). + pub webhook: bool, + /// `https://.atlassian.net`, when known. + pub site: String, + secret: String, + issues_url: Option, + list_projects_url: Option, +} + +// By hand, so the secret never reaches a log. +impl std::fmt::Debug for Connection { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Connection") + .field("app", &self.app) + .field("webhook", &self.webhook) + .field("site", &self.site) + .finish_non_exhaustive() + } +} + +/// Why tickets can't be read on demand from a connected team's Jira. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Gap { + /// No Jira connection at all. + NotConnected, + /// The app is connected but hasn't registered its ticket lookup with + /// Coderhelm yet (it gained it after it registered). + LookupNotRegistered, + /// Only a plain Jira webhook is set up: it sends events, it can't be + /// asked for tickets. + WebhookOnly, +} + +impl Gap { + /// The plain sentence for the answer. + pub fn words(self) -> &'static str { + match self { + Gap::NotConnected => NOT_CONNECTED, + Gap::LookupNotRegistered => "Jira is connected, but the Coderhelm app on the Jira site hasn't registered its ticket lookup with Coderhelm yet, so tickets can't be looked up on demand right now (Coderhelm has asked the app to register it again, which usually takes a minute)", + Gap::WebhookOnly => "Jira is connected through a Jira webhook, which sends Coderhelm ticket events but can't be asked for tickets (the Coderhelm app in Jira adds ticket lookups)", + } + } +} + +/// What a ticket lookup can use. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TicketReads { + /// The app's lookup trigger, its secret and the site. + Ready { + issues_url: String, + secret: String, + site: String, + }, + /// Not available, and why. + Off(Gap), +} + +impl Connection { + /// From the team's `JIRA#config` (if any) and whether a plain Jira + /// webhook is set up. + pub fn from_config(item: Option<&Item>, webhook: bool) -> Connection { + let Some(item) = item else { + return Connection { + webhook, + ..Connection::default() + }; + }; + let secret = text(item, "forge_secret"); + Connection { + // The same test the integrations page always made, plus the + // secret every call to the app needs. + app: !text(item, "add_comment_url").is_empty() && !secret.is_empty(), + webhook, + site: Some(text(item, "site_url")) + .filter(|u| u.starts_with("https://")) + .unwrap_or_default(), + secret, + issues_url: link(item, "get_issues_url"), + list_projects_url: link(item, "list_projects_url"), + } + } + + /// Whether Jira is connected: the app or a plain webhook. + pub fn connected(&self) -> bool { + self.app || self.webhook + } + + /// Whether tickets can be read on demand, and if not, why. + pub fn ticket_reads(&self) -> TicketReads { + match (&self.issues_url, self.app) { + (Some(u), true) => TicketReads::Ready { + issues_url: u.clone(), + secret: self.secret.clone(), + site: self.site.clone(), + }, + (_, true) => TicketReads::Off(Gap::LookupNotRegistered), + (_, false) if self.webhook => TicketReads::Off(Gap::WebhookOnly), + _ => TicketReads::Off(Gap::NotConnected), + } + } + + /// Where to ask the app to register again, and the body to send, when it + /// is connected but lacks a trigger it always registers. `None` when + /// nothing is missing or the app can't be reached. + pub fn register_again(&self, item: Option<&Item>) -> Option<(String, serde_json::Value)> { + if !self.app + || item + .map(missing_registrations) + .unwrap_or_default() + .is_empty() + { + return None; + } + let url = self.list_projects_url.clone()?; + Some(( + url, + serde_json::json!({ REGISTER_AGAIN: true, "forge_secret": self.secret }), + )) + } +} + +/// The triggers the current app always registers that the record lacks +/// (empty for a record without the app). +pub fn missing_registrations(item: &Item) -> Vec<&'static str> { + if text(item, "add_comment_url").is_empty() || text(item, "forge_secret").is_empty() { + return Vec::new(); + } + ALWAYS_REGISTERED + .iter() + .copied() + .filter(|k| text(item, k).is_empty()) + .collect() +} + +/// The trigger names a record holds a link for, in [`TRIGGERS`] order. +pub fn registered(item: &Item) -> Vec<&'static str> { + TRIGGERS + .iter() + .filter(|(field, _)| !text(item, field).is_empty()) + .map(|(_, name)| *name) + .collect() +} + +/// Whether a self-hosted install's copy of a linked site's settings is out +/// of date: the hosted record names triggers (`hosted`, from +/// [`registered`]) that differ from the ones last copied. `None` from a +/// hosted side that doesn't send the list (then only a relink copies). +pub fn copy_is_stale(hosted: Option<&[String]>, copied: &[String]) -> bool { + hosted.is_some_and(|h| { + let mut a: Vec<&str> = h.iter().map(String::as_str).collect(); + let mut b: Vec<&str> = copied.iter().map(String::as_str).collect(); + a.sort_unstable(); + b.sort_unstable(); + a != b + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn item(pairs: &[(&str, &str)]) -> Item { + pairs + .iter() + .map(|(k, v)| (k.to_string(), AttributeValue::S(v.to_string()))) + .collect() + } + + /// The app registered before it had the ticket lookup. + fn before_lookup() -> Item { + item(&[ + ( + "list_projects_url", + "https://x.hello.atlassian-dev.net/x1/lp", + ), + ( + "create_ticket_url", + "https://x.hello.atlassian-dev.net/x1/ct", + ), + ("add_comment_url", "https://x.hello.atlassian-dev.net/x1/ac"), + ("publish_release_url", ""), + ("get_issues_url", ""), + ("confluence_trigger_url", ""), + ("forge_secret", "secret-1"), + ("site_url", "https://example.atlassian.net"), + ]) + } + + #[test] + fn an_app_without_the_lookup_is_connected_and_names_the_missing_ability() { + let i = before_lookup(); + let c = Connection::from_config(Some(&i), false); + assert!(c.connected()); + assert_eq!(c.ticket_reads(), TicketReads::Off(Gap::LookupNotRegistered)); + assert!(!Gap::LookupNotRegistered.words().contains("isn't connected")); + assert_eq!(missing_registrations(&i), vec!["get_issues_url"]); + let (url, body) = c.register_again(Some(&i)).unwrap(); + assert!(url.ends_with("/lp")); + assert_eq!(body[REGISTER_AGAIN], true); + assert_eq!(body["forge_secret"], "secret-1"); + // The secret never reaches a log. + assert!(!format!("{c:?}").contains("secret-1")); + } + + #[test] + fn a_full_registration_is_ready_and_asks_nothing() { + let mut i = before_lookup(); + i.insert( + "get_issues_url".into(), + AttributeValue::S("https://x.hello.atlassian-dev.net/x1/gi".into()), + ); + let c = Connection::from_config(Some(&i), false); + assert!( + matches!(c.ticket_reads(), TicketReads::Ready { ref issues_url, .. } if issues_url.ends_with("/gi")) + ); + assert!(missing_registrations(&i).is_empty()); + assert!(c.register_again(Some(&i)).is_none()); + assert_eq!( + registered(&i), + vec![ + "list_projects", + "create_ticket", + "add_comment", + "get_issues" + ] + ); + } + + #[test] + fn only_no_connection_at_all_is_not_connected() { + let none = Connection::from_config(None, false); + assert!(!none.connected()); + assert_eq!(none.ticket_reads(), TicketReads::Off(Gap::NotConnected)); + let hook = Connection::from_config(None, true); + assert!(hook.connected()); + assert_eq!(hook.ticket_reads(), TicketReads::Off(Gap::WebhookOnly)); + assert!(!Gap::WebhookOnly.words().contains("isn't connected")); + // A record without the app's secret isn't the app. + let mut i = before_lookup(); + i.remove("forge_secret"); + assert!(!Connection::from_config(Some(&i), false).connected()); + assert!(missing_registrations(&i).is_empty()); + } + + #[test] + fn a_copy_is_stale_when_the_hosted_triggers_differ() { + let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::>(); + let copied = s(&["list_projects", "create_ticket", "add_comment"]); + let hosted = s(&[ + "add_comment", + "create_ticket", + "get_issues", + "list_projects", + ]); + assert!(copy_is_stale(Some(&hosted), &copied)); + assert!(!copy_is_stale(Some(&hosted), &hosted)); + // Order doesn't matter. + let shuffled = s(&[ + "get_issues", + "list_projects", + "add_comment", + "create_ticket", + ]); + assert!(!copy_is_stale(Some(&hosted), &shuffled)); + // An older hosted side that sends no list: nothing to compare. + assert!(!copy_is_stale(None, &copied)); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index a7cb8339b..f34a3c3e9 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -116,6 +116,7 @@ pub mod instructions; /// The Jira app version each site runs, the latest release, and what an /// older version lacks. pub mod jira_app_version; +pub mod jira_connection; pub mod live; /// Log findings and the fix runs started from them. pub mod log_findings; diff --git a/services/gateway/src/mcp_lookups.rs b/services/gateway/src/mcp_lookups.rs index 6976bdc9e..c2369c46f 100644 --- a/services/gateway/src/mcp_lookups.rs +++ b/services/gateway/src/mcp_lookups.rs @@ -960,7 +960,7 @@ async fn connect( if tickets { crate::routes::chat_work_tickets::load(state, team).await } else { - None + crate::routes::chat_work_tickets::Jira::default() } }, async { diff --git a/services/gateway/src/routes/chat_eval.rs b/services/gateway/src/routes/chat_eval.rs index 267645f04..3fc55cdaf 100644 --- a/services/gateway/src/routes/chat_eval.rs +++ b/services/gateway/src/routes/chat_eval.rs @@ -614,6 +614,7 @@ impl WorkBox<'_> { store: &store, http: &http, jira: Some(&app), + jira_off: "", github: Some(fx::gh()), repos: &repos, readable: &self.readable, diff --git a/services/gateway/src/routes/chat_work.rs b/services/gateway/src/routes/chat_work.rs index 5fda5405b..8716ef1ba 100644 --- a/services/gateway/src/routes/chat_work.rs +++ b/services/gateway/src/routes/chat_work.rs @@ -463,7 +463,8 @@ pub struct Ctx { pub github_token: Option, /// The installation the token is for (its GitHub budget). pub installation_id: Option, - pub jira: Option, + /// The team's Jira for ticket reads, or why it can't be read. + pub jira: super::chat_work_tickets::Jira, /// Who its GitHub reads are counted under (`github_budget::caller`): /// Chat, or an AI tool on `/mcp`. pub caller: &'static str, @@ -699,7 +700,8 @@ async fn needs_me( team: &ctx.claims.team_id, store: &store, http: &http, - jira: ctx.jira.as_ref(), + jira: ctx.jira.app.as_ref(), + jira_off: ctx.jira.off_words(), github: ctx.github_token.as_ref().map(|t| needs::GitHub { auth: format!("Bearer {t}"), base: "https://api.github.com".into(), @@ -767,13 +769,14 @@ async fn tickets( }; let site = ctx .jira + .app .as_ref() .map(|j| j.site.clone()) .unwrap_or_default(); - let Some(app) = &ctx.jira else { + let Some(app) = &ctx.jira.app else { return register( reg, - t::from_runs(&found_runs, &site, "The team's Jira isn't connected to Coderhelm, so this is what Coderhelm's runs know."), + t::from_runs(&found_runs, &site, &t::off_note(ctx.jira.off_words())), "tickets", "", ); diff --git a/services/gateway/src/routes/chat_work_needs.rs b/services/gateway/src/routes/chat_work_needs.rs index 5f2389697..b05781eae 100644 --- a/services/gateway/src/routes/chat_work_needs.rs +++ b/services/gateway/src/routes/chat_work_needs.rs @@ -147,6 +147,8 @@ pub struct Sources<'a> { pub store: &'a dyn Store, pub http: &'a dyn Http, pub jira: Option<&'a JiraApp>, + /// Why `jira` is `None`, in words (`chat_work_tickets::Jira::off_words`). + pub jira_off: &'a str, pub github: Option, /// The team's repositories the person may read. pub repos: &'a [String], @@ -973,7 +975,11 @@ pub async fn gather(src: &Sources<'_>, mut me: Me, now: Time) -> Report { Vec::new(), Vec::new(), 0, - Read::Off("Jira isn't connected to Coderhelm".into()), + Read::Off(if src.jira_off.is_empty() { + common::jira_connection::NOT_CONNECTED.into() + } else { + src.jira_off.to_string() + }), ); }; let Some(account) = me.jira_id.clone() else { @@ -1165,7 +1171,7 @@ fn read_words(r: &Read) -> String { } /// How the answer is written. -pub const ANSWER_SHAPE: &str = "Write the answer in exactly this shape. First the count line. Then each group in the order given (skip an empty one), with its heading, and one line per item, most urgent first: a markdown link to the item named by what it is, then exactly what they need to do, then since when, and its citation. Under a run's line, keep its questions with their possible answers as a short nested list. Then, for every source that couldn't be read or wasn't checked, one plain sentence that says so (for example \"Jira isn't connected to Coderhelm, so your tickets aren't listed\"). Don't add items that aren't listed here."; +pub const ANSWER_SHAPE: &str = "Write the answer in exactly this shape. First the count line. Then each group in the order given (skip an empty one), with its heading, and one line per item, most urgent first: a markdown link to the item named by what it is, then exactly what they need to do, then since when, and its citation. Under a run's line, keep its questions with their possible answers as a short nested list. Then, for every source that couldn't be read or wasn't checked, one plain sentence that says so (for example \"GitHub couldn't be read, so your pull requests aren't listed\"), in that source's own words: never say a system isn't connected unless its line says exactly that. Don't add items that aren't listed here."; /// Registers each item as a citable source and writes what the model reads. /// Returns the text and the step's summary. @@ -1678,6 +1684,7 @@ pub(crate) mod tests { store, http: h, jira, + jira_off: "", github, repos: &repos, readable: &readable, @@ -1803,6 +1810,7 @@ pub(crate) mod tests { store: &s, http: &down, jira: None, + jira_off: "", github: Some(gh()), repos: &repos, readable: &readable, @@ -1816,6 +1824,21 @@ pub(crate) mod tests { ); assert!(text.contains("isn't linked to a GitHub account"), "{text}"); assert!(summary.contains("3 sources not read"), "{summary}"); + // Connected, but the app's lookup isn't registered: the answer names + // that ability, never "not connected", and the runs still answer. + let lacking = common::jira_connection::Gap::LookupNotRegistered.words(); + let src = Sources { + jira_off: lacking, + ..src + }; + let r = gather(&src, me(), now()).await; + let (text, _) = render(&r, &mut Default::default(), "2026-11-16 12:00 UTC"); + assert!( + text.contains("Jira: not checked: Jira is connected, but"), + "{text}" + ); + assert!(!text.contains("Jira isn't connected"), "{text}"); + assert!(!ANSWER_SHAPE.contains("Jira isn't connected")); // An old Jira app (no `mine` in its answer) is named as such. let old = fake(|_| (200, json!({"issues": []}))); let e = ask_jira_mine(&old, &app(), JIRA_ME).await.unwrap_err(); @@ -1845,6 +1868,7 @@ pub(crate) mod tests { store: &s, http: &Slow, jira: Some(&a), + jira_off: "", github: Some(gh()), repos: &repos, readable: &readable, diff --git a/services/gateway/src/routes/chat_work_tickets.rs b/services/gateway/src/routes/chat_work_tickets.rs index b60c0a25e..202ddd9c8 100644 --- a/services/gateway/src/routes/chat_work_tickets.rs +++ b/services/gateway/src/routes/chat_work_tickets.rs @@ -33,10 +33,64 @@ impl std::fmt::Debug for JiraApp { } } -/// The team's Jira app from its `JIRA#config` record (only the asker's team -/// is read), when it registered the get-issues trigger. -pub async fn load(state: &crate::AppState, team_id: &str) -> Option { - let item = state +/// What chat's ticket reads can use: the app's lookup, or exactly why not +/// (`common::jira_connection`, the same truth the integrations page shows). +#[derive(Debug, Clone, Default)] +pub struct Jira { + pub app: Option, + /// Why `app` is `None`, in words for the answer. + pub off: String, +} + +impl Jira { + /// From the team's `JIRA#config` and whether a plain webhook is set up + /// (pure; tested). + pub fn from_config( + item: Option<&std::collections::HashMap>, + webhook: bool, + ) -> Jira { + use common::jira_connection::{Connection, TicketReads}; + match Connection::from_config(item, webhook).ticket_reads() { + TicketReads::Ready { + issues_url, + secret, + site, + } => Jira { + app: Some(JiraApp { + issues_url, + secret, + site, + }), + off: String::new(), + }, + TicketReads::Off(gap) => Jira { + app: None, + off: gap.words().to_string(), + }, + } + } + + /// Why tickets can't be read, or the plain "not connected" when there's + /// no reason recorded. + pub fn off_words(&self) -> &str { + if self.off.is_empty() { + common::jira_connection::NOT_CONNECTED + } else { + &self.off + } + } +} + +/// The note on tickets answered from the runs because Jira can't be read. +pub fn off_note(why: &str) -> String { + format!("{why}, so this is what Coderhelm's runs know.") +} + +async fn read_config( + state: &crate::AppState, + team_id: &str, +) -> Option> { + state .dynamo .get_item() .table_name(&state.config.jira_config_table_name) @@ -53,20 +107,26 @@ pub async fn load(state: &crate::AppState, team_id: &str) -> Option { .send() .await .ok()? - .item?; - let get = |k: &str| { - item.get(k) - .and_then(|v| v.as_s().ok()) - .map(|v| v.trim().to_string()) - .filter(|v| !v.is_empty()) - }; - Some(JiraApp { - issues_url: get("get_issues_url").filter(|u| u.starts_with("https://"))?, - secret: get("forge_secret")?, - site: get("site_url") - .filter(|u| u.starts_with("https://")) - .unwrap_or_default(), - }) + .item +} + +/// The team's Jira as chat reads it (only the asker's team is read). When +/// the app is connected but lacks the lookup, the system puts it right +/// first (`jira_heal`: the app registers again, a linked install copies +/// again) and reads once more, so the answer usually has the tickets. +pub async fn load(state: &crate::AppState, team_id: &str) -> Jira { + let (item, hook) = tokio::join!( + read_config(state, team_id), + super::api::load_jira_secret(state, team_id), + ); + let first = Jira::from_config(item.as_ref(), hook.is_some()); + let lacks_lookup = first.app.is_none() + && common::jira_connection::Connection::from_config(item.as_ref(), false).app; + if !lacks_lookup || !super::jira_heal::heal(state, team_id, item.as_ref()).await { + return first; + } + let again = read_config(state, team_id).await; + Jira::from_config(again.as_ref(), hook.is_some()) } /// A ticket key as Jira writes them. @@ -265,6 +325,70 @@ mod tests { use crate::routes::chat_work_prs::tests::fake; use crate::routes::chat_work_runs::{record, tests::run}; + /// A linked install's record from before the app had its lookup: the + /// proxy links copied then, the secret, the site and a version seen + /// today, and no lookup link. + fn copied_before_lookup( + ) -> std::collections::HashMap { + let p = "https://api.example.com/hybrid/jira/trigger/ins_a"; + [ + ("list_projects_url", format!("{p}/list_projects/t")), + ("create_ticket_url", format!("{p}/create_ticket/t")), + ("add_comment_url", format!("{p}/add_comment/t")), + ("publish_release_url", String::new()), + ("get_issues_url", String::new()), + ("confluence_trigger_url", String::new()), + ("forge_secret", "token-for-install".into()), + ("site_url", "https://example.atlassian.net".into()), + ("app_version", "7.3.0".into()), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), aws_sdk_dynamodb::types::AttributeValue::S(v))) + .collect() + } + + #[test] + fn an_app_without_its_lookup_is_never_called_not_connected() { + let item = copied_before_lookup(); + let j = Jira::from_config(Some(&item), false); + assert!(j.app.is_none()); + assert!( + !j.off_words().contains("isn't connected"), + "{}", + j.off_words() + ); + assert!( + j.off_words().starts_with("Jira is connected, but"), + "{}", + j.off_words() + ); + assert!(j.off_words().contains("ticket lookup"), "{}", j.off_words()); + let note = off_note(j.off_words()); + assert!( + note.ends_with("so this is what Coderhelm's runs know."), + "{note}" + ); + // The lookup registered: ready, with the site for links. + let mut full = item.clone(); + full.insert( + "get_issues_url".into(), + aws_sdk_dynamodb::types::AttributeValue::S( + "https://api.example.com/hybrid/jira/trigger/ins_a/get_issues/t".into(), + ), + ); + let j = Jira::from_config(Some(&full), false); + let app = j.app.expect("ready"); + assert_eq!(app.site, "https://example.atlassian.net"); + // Only no connection at all is "not connected". + assert_eq!( + Jira::from_config(None, false).off_words(), + common::jira_connection::NOT_CONNECTED + ); + assert!(Jira::from_config(None, true) + .off_words() + .contains("Jira webhook")); + } + fn app() -> JiraApp { JiraApp { issues_url: "https://app.example.test/issues".into(), diff --git a/services/gateway/src/routes/hybrid.rs b/services/gateway/src/routes/hybrid.rs index 3e5ad1136..1a0ff7665 100644 --- a/services/gateway/src/routes/hybrid.rs +++ b/services/gateway/src/routes/hybrid.rs @@ -546,7 +546,16 @@ pub async fn status( let slug = crate::auth::github_app::app_slug(&state).await; let mut v = install.view(); v["github"] = json!({ "links": links, "app_slug": slug }); - v["jira"] = json!({ "link": super::hybrid_jira::jira_link(&state, &install.id).await }); + let jira_link = super::hybrid_jira::jira_link(&state, &install.id).await; + let mut link_v = json!(jira_link); + if let Some(l) = &jira_link { + // The triggers the site registered here: the install copies again + // when they change (an app update that adds one). + if let Some(t) = super::hybrid_jira::linked_triggers(&state, &l.team_id).await { + link_v["triggers"] = json!(t); + } + } + v["jira"] = json!({ "link": link_v }); v["offered"] = json!(offered_ids(&state)); v["name_check"] = name_check_view(&state, &install.name).await; Ok(Json(v)) diff --git a/services/gateway/src/routes/hybrid_install.rs b/services/gateway/src/routes/hybrid_install.rs index b7d2b383f..202e3615a 100644 --- a/services/gateway/src/routes/hybrid_install.rs +++ b/services/gateway/src/routes/hybrid_install.rs @@ -115,6 +115,11 @@ pub struct Local { pub jira_site: String, #[serde(default)] pub jira_synced_at: String, + /// The triggers the copied settings hold links for, by name: when the + /// linked site registers another (an app update that adds one), + /// CoderHelm's list differs and the settings are copied again. + #[serde(default)] + pub jira_synced_triggers: Vec, } static LOCAL: RwLock> = RwLock::new(None); @@ -1448,8 +1453,18 @@ pub enum JiraSync { pub fn jira_sync_plan(l: &Local, link: Option<&Value>) -> JiraSync { match link.filter(|v| v.is_object()) { Some(v) if l.jira_link => { + let hosted_triggers: Option> = v["triggers"].as_array().map(|a| { + a.iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect() + }); if v["linked_at"].as_str() == Some(l.jira_synced_at.as_str()) && !l.jira_synced_at.is_empty() + && !common::jira_connection::copy_is_stale( + hosted_triggers.as_deref(), + &l.jira_synced_triggers, + ) { JiraSync::Nothing } else { @@ -1461,6 +1476,42 @@ pub fn jira_sync_plan(l: &Local, link: Option<&Value>) -> JiraSync { } } +/// The trigger names CoderHelm's `/hybrid/jira/config` answer holds a link +/// for (it sends a link only for a trigger the site registered). +pub fn copied_triggers(cfg: &Value) -> Vec { + super::hybrid_jira::TRIGGERS + .iter() + .filter(|(field, _)| cfg[*field].as_str().is_some_and(|u| !u.is_empty())) + .map(|(_, name)| name.to_string()) + .collect() +} + +/// Copies the linked site's settings again now, whatever the last copy +/// was: for a reader (chat) that found the copy missing a trigger. True when +/// it copied. +pub async fn refresh_jira_copy(state: &AppState) -> bool { + if !super::setup_checks::self_hosted() { + return false; + } + let mut l = local(state).await; + if !l.jira_link { + return false; + } + let Some(c) = creds_now().await else { + return false; + }; + let Ok(hosted) = client::call(&state.http, &c, "GET", "/hybrid/status", None).await else { + return false; + }; + if !hosted["jira"]["link"].is_object() { + return false; + } + // Forgetting which link was copied (in memory only) makes the plan copy; + // the copy saves the new marks. + l.jira_synced_at.clear(); + sync_jira(state, &mut l, Some(&hosted)).await.is_ok() +} + /// Keeps this install's Jira settings in step with the link on CoderHelm: /// copies the linked site's Jira app settings to the install's team (so it /// checks the Forge secret on each event and can comment back), or forgets @@ -1529,6 +1580,7 @@ pub async fn sync_jira( let v = link.cloned().unwrap_or_default(); l.jira_site = v["site_url"].as_str().unwrap_or("").to_string(); l.jira_synced_at = v["linked_at"].as_str().unwrap_or("").to_string(); + l.jira_synced_triggers = copied_triggers(&cfg); save_local(state, l) .await .map_err(|_| "jira_link_unsynced")?; @@ -1581,6 +1633,7 @@ async fn forget_jira(state: &AppState, l: &mut Local) { } l.jira_site.clear(); l.jira_synced_at.clear(); + l.jira_synced_triggers.clear(); } /// The linked site's settings are copied here, fetching them now when they @@ -2009,6 +2062,17 @@ pub async fn intake( "This install has no team yet. Sign up first.", ) })?; + // The site's app runs another version than last seen, or + // the copy lacks a link the app always registers: copy + // CoderHelm's settings again (asking the app to register + // first when CoderHelm lacks it too). + let copy = team_jira_item(&state, &team).await; + let version = payload + .pointer("/coderhelm/app_version") + .and_then(Value::as_str); + if super::jira_heal::wants_heal(copy.as_ref(), version) { + Box::pin(super::jira_heal::heal(&state, &team, copy.as_ref())).await; + } return super::jira_webhook::process_relayed(&state, &team, &payload) .await .map_err(|code| { @@ -2822,6 +2886,61 @@ mod tests { assert_eq!(jira_sync_plan(&off, Some(&link)), JiraSync::Nothing); } + #[test] + fn a_trigger_the_site_registers_after_the_link_is_copied_again() { + // Linked and copied before the app had its ticket lookup. + let mut l = Local { + jira_link: true, + jira_synced_at: "2026-11-02T00:00:00Z".into(), + ..Default::default() + }; + let before = json!({ + "list_projects_url": "https://api.example.com/hybrid/jira/trigger/ins_a/list_projects/t", + "create_ticket_url": "https://api.example.com/hybrid/jira/trigger/ins_a/create_ticket/t", + "add_comment_url": "https://api.example.com/hybrid/jira/trigger/ins_a/add_comment/t", + "publish_release_url": "", + "get_issues_url": "", + "confluence_trigger_url": "", + }); + l.jira_synced_triggers = copied_triggers(&before); + assert_eq!( + l.jira_synced_triggers, + vec!["list_projects", "create_ticket", "add_comment"] + ); + let link = |triggers: &[&str]| json!({ "team_id": "TEAM#1", "linked_at": "2026-11-02T00:00:00Z", "triggers": triggers }); + // CoderHelm's record unchanged: nothing to copy. + assert_eq!( + jira_sync_plan( + &l, + Some(&link(&["list_projects", "create_ticket", "add_comment"])) + ), + JiraSync::Nothing + ); + // The site registered its lookup on CoderHelm: the same link, copied again. + assert_eq!( + jira_sync_plan( + &l, + Some(&link(&[ + "list_projects", + "create_ticket", + "add_comment", + "get_issues" + ])) + ), + JiraSync::Copy + ); + // An install copied before this change holds no list: it copies once. + let mut old = l.clone(); + old.jira_synced_triggers.clear(); + assert_eq!( + jira_sync_plan(&old, Some(&link(&["add_comment", "get_issues"]))), + JiraSync::Copy + ); + // A hosted side that sends no list: only a relink copies, as before. + let bare = json!({ "team_id": "TEAM#1", "linked_at": "2026-11-02T00:00:00Z" }); + assert_eq!(jira_sync_plan(&old, Some(&bare)), JiraSync::Nothing); + } + #[test] fn a_link_keeps_the_installs_own_jira_settings_aside() { let item = |pairs: &[(&str, &str)]| { diff --git a/services/gateway/src/routes/hybrid_jira.rs b/services/gateway/src/routes/hybrid_jira.rs index c55f39817..5ca90ac04 100644 --- a/services/gateway/src/routes/hybrid_jira.rs +++ b/services/gateway/src/routes/hybrid_jira.rs @@ -471,14 +471,26 @@ pub async fn delete_link( /// The Forge triggers a linked install may call through the proxy: the /// Jira settings field it reads and the trigger's name in the proxy path. -pub const TRIGGERS: &[(&str, &str)] = &[ - ("list_projects_url", "list_projects"), - ("create_ticket_url", "create_ticket"), - ("add_comment_url", "add_comment"), - ("publish_release_url", "publish_release"), - ("get_issues_url", "get_issues"), - ("confluence_trigger_url", "confluence"), -]; +pub const TRIGGERS: &[(&str, &str)] = common::jira_connection::TRIGGERS; + +/// The triggers the linked team's site has registered here, by name: sent +/// with the link on `/hybrid/status`, so the install copies the settings +/// again whenever the site registers a trigger it didn't have (an app +/// update that adds one), not only on a relink. +pub async fn linked_triggers(state: &AppState, team_id: &str) -> Option> { + let item = state + .dynamo + .get_item() + .table_name(&state.config.jira_config_table_name) + .key("pk", s(team_id)) + .key("sk", s("JIRA#config")) + .send() + .await + .ok()? + .item + .unwrap_or_default(); + Some(common::jira_connection::registered(&item)) +} /// The proxy link the install calls for one trigger. pub fn proxy_url( diff --git a/services/gateway/src/routes/integrations.rs b/services/gateway/src/routes/integrations.rs index f83b6ead0..f927fd289 100644 --- a/services/gateway/src/routes/integrations.rs +++ b/services/gateway/src/routes/integrations.rs @@ -1078,10 +1078,27 @@ pub async fn list( )); // Jira. - let forge = jira_config + // The one test of "connected" chat and the runs use too + // (`common::jira_connection`). + let conn = common::jira_connection::Connection::from_config( + jira_config.as_ref(), + jira_secret.is_some(), + ); + let forge = conn.app; + let jira_on = conn.connected(); + // An ability the app lacks is named, and put right by the system. + let ticket_reads = match conn.ticket_reads() { + common::jira_connection::TicketReads::Ready { .. } => json!({ "ready": true }), + common::jira_connection::TicketReads::Off(gap) => { + json!({ "ready": false, "why": gap.words() }) + } + }; + if jira_config .as_ref() - .is_some_and(|i| !s(i, "add_comment_url").is_empty()); - let jira_on = forge || jira_secret.is_some(); + .is_some_and(|i| !common::jira_connection::missing_registrations(i).is_empty()) + { + Box::pin(super::jira_heal::heal(&state, &team, jira_config.as_ref())).await; + } // The site's app is older than the latest release: what it lacks and // where its admin accepts the update. let app_update = if forge { @@ -1106,7 +1123,7 @@ pub async fn list( }, "", "/settings/integrations/jira", - json!({ "app": forge, "app_update": app_update }), + json!({ "app": forge, "app_update": app_update, "ticket_reads": ticket_reads }), ); let mut confluence_part = Value::Null; let mut agent_tools_part = Value::Null; diff --git a/services/gateway/src/routes/jira_heal.rs b/services/gateway/src/routes/jira_heal.rs new file mode 100644 index 000000000..997040ed9 --- /dev/null +++ b/services/gateway/src/routes/jira_heal.rs @@ -0,0 +1,150 @@ +//! The Jira app's links put right by the system, never by a person. +//! +//! A site's app registers its trigger links when it is installed, when an +//! admin saves its settings, on a major update, and (from this change) on +//! the first event after any version change. A site that gained a trigger +//! before that (Forge rolls a minor version out without telling the app) +//! still lacks the link here, and a self-hosted install linked through +//! CoderHelm copied the hosted links once, when it linked. +//! +//! [`heal`] is what every reader that finds a link missing calls: it asks +//! the app, through its project-list trigger, to register all of its links +//! again (`common::jira_connection::REGISTER_AGAIN`), and on a linked +//! install copies the hosted settings again afterwards. It is cheap to call +//! often: once per team per [`QUIET`]. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::jira_connection::Connection; +use common::mcp_remote::http::{GuardedHttps, Http, HttpRequest, Limit}; +use tracing::{info, warn}; + +use crate::AppState; + +type Item = HashMap; + +/// How long after one attempt the same team's next one waits. +pub const QUIET: Duration = Duration::from_secs(10 * 60); + +static LAST: Mutex>> = Mutex::new(None); + +/// Whether this team may be tried now; marks it tried when so. +pub fn take_turn(team_id: &str, now: Instant) -> bool { + let Ok(mut g) = LAST.lock() else { + return false; + }; + let map = g.get_or_insert_with(HashMap::new); + match map.get(team_id) { + Some(at) if now.duration_since(*at) < QUIET => false, + _ => { + map.insert(team_id.to_string(), now); + true + } + } +} + +/// Whether the team's record lacks a link the app always registers, or the +/// event reports another app version than the one last seen. +pub fn wants_heal(item: Option<&Item>, event_version: Option<&str>) -> bool { + let Some(item) = item else { + return false; + }; + if !common::jira_connection::missing_registrations(item).is_empty() { + return true; + } + let stored = item + .get(common::jira_app_version::FIELD_VERSION) + .and_then(|v| v.as_s().ok()) + .map(|v| v.trim()) + .unwrap_or(""); + let reported = event_version + .and_then(common::jira_app_version::Version::parse) + .map(|v| v.to_string()) + .unwrap_or_default(); + !reported.is_empty() && !stored.is_empty() && reported != stored +} + +/// Asks the app to register its links again (when it lacks one), then, on +/// a self-hosted install linked through CoderHelm, copies the hosted +/// settings again. True when anything was refreshed. At most once per team +/// per [`QUIET`]; never fails the caller. +pub async fn heal(state: &AppState, team_id: &str, item: Option<&Item>) -> bool { + if !take_turn(team_id, Instant::now()) { + return false; + } + let conn = Connection::from_config(item, false); + let mut asked = false; + if let Some((url, body)) = conn.register_again(item) { + // On a linked install this is CoderHelm's proxy link: the site's app + // registers with CoderHelm, which the copy below then picks up. + match GuardedHttps + .send(HttpRequest::json(&url, &body, Limit::Metadata)) + .await + { + Ok(r) if r.status == 200 => asked = true, + Ok(r) => warn!( + team_id, + status = r.status, + "Jira app: asking it to register again was refused" + ), + Err(e) => warn!(team_id, error = %e, "Jira app: couldn't ask it to register again"), + } + } + let copied = super::hybrid_install::refresh_jira_copy(state).await; + if asked || copied { + info!(team_id, asked, copied, "Jira app: links refreshed"); + } + asked || copied +} + +#[cfg(test)] +mod tests { + use super::*; + + fn item(pairs: &[(&str, &str)]) -> Item { + pairs + .iter() + .map(|(k, v)| (k.to_string(), AttributeValue::S(v.to_string()))) + .collect() + } + + #[test] + fn a_missing_link_or_a_new_version_asks_for_a_heal() { + let full = item(&[ + ( + "list_projects_url", + "https://x.hello.atlassian-dev.net/x1/lp", + ), + ( + "create_ticket_url", + "https://x.hello.atlassian-dev.net/x1/ct", + ), + ("add_comment_url", "https://x.hello.atlassian-dev.net/x1/ac"), + ("get_issues_url", "https://x.hello.atlassian-dev.net/x1/gi"), + ("forge_secret", "s"), + ("app_version", "7.3.0"), + ]); + assert!(!wants_heal(Some(&full), Some("7.3.0"))); + assert!(!wants_heal(Some(&full), None)); + assert!(wants_heal(Some(&full), Some("7.4.0"))); + let mut lacking = full.clone(); + lacking.insert("get_issues_url".into(), AttributeValue::S(String::new())); + assert!(wants_heal(Some(&lacking), Some("7.3.0"))); + assert!(!wants_heal(None, Some("7.4.0"))); + } + + #[test] + fn one_try_per_team_per_quiet_spell() { + let t0 = Instant::now(); + assert!(take_turn("TEAM#heal-a", t0)); + assert!(!take_turn("TEAM#heal-a", t0 + Duration::from_secs(60))); + assert!(take_turn("TEAM#heal-b", t0)); + assert!(take_turn( + "TEAM#heal-a", + t0 + QUIET + Duration::from_secs(1) + )); + } +} diff --git a/services/gateway/src/routes/jira_webhook.rs b/services/gateway/src/routes/jira_webhook.rs index 4d6efec7a..038cbe52e 100644 --- a/services/gateway/src/routes/jira_webhook.rs +++ b/services/gateway/src/routes/jira_webhook.rs @@ -940,6 +940,22 @@ pub async fn handle_forge( )) .await; + // The app runs another version than last seen, or the record lacks a + // link the app always registers (a trigger it gained after it + // registered): the app is asked to register again, here, before anyone + // reads a missing link. + let event_version = payload + .pointer("/coderhelm/app_version") + .and_then(|v| v.as_str()); + if super::jira_heal::wants_heal(config_item.as_ref(), event_version) { + Box::pin(super::jira_heal::heal( + &state, + &team_id, + config_item.as_ref(), + )) + .await; + } + // Hosted side of hybrid: the team linked its Jira site to a self-hosted // install. The event passed the team's own check; it goes there, and is // not handled here as well. diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index fd93e20fb..bba6f0147 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -48,6 +48,7 @@ pub mod installation_owner; pub mod integration_status; pub mod integrations; pub mod jira_app_status; +pub mod jira_heal; pub mod jira_webhook; pub mod knowledge; pub mod knowledge_ask; diff --git a/services/worker/src/passes/incidents/bm_teams_never_cross.rs b/services/worker/src/passes/incidents/bm_teams_never_cross.rs index 3199c88c5..6e8a0f111 100644 --- a/services/worker/src/passes/incidents/bm_teams_never_cross.rs +++ b/services/worker/src/passes/incidents/bm_teams_never_cross.rs @@ -333,6 +333,7 @@ const CACHES: &[(&str, &str)] = &[ ("common/src/github_grants.rs::KNOWN", "installation id"), ("common/src/hybrid/client.rs::TOKENS", "installation id"), ("common/src/hybrid/client.rs::FAILING", "installation id"), + ("gateway/src/routes/jira_heal.rs::LAST", "team id; holds only when that team last asked the Jira app to register again"), ("common/src/knowledge/search.rs::C", "S3 key under `{team}/knowledge/`, checked by owns_key before the lookup"), ("common/src/knowledge/sources/pace.rs::GATES", "provider rate gate; no data"), ("common/src/ticket_decisions.rs::KNOWN", "installation id plus `owner/repo@ticket`: read back only by description writes made with that installation"), diff --git a/services/worker/src/passes/incidents/jc_jira_connected_in_chat.rs b/services/worker/src/passes/incidents/jc_jira_connected_in_chat.rs new file mode 100644 index 000000000..cb7f3f966 --- /dev/null +++ b/services/worker/src/passes/incidents/jc_jira_connected_in_chat.rs @@ -0,0 +1,124 @@ +//! jc. A new user on a self-hosted install asked chat what was waiting on +//! him. Chat answered "Jira isn't connected to Coderhelm", while Settings, +//! Integrations showed Atlassian connected and runs from Jira tickets +//! worked. The install linked its Jira site through CoderHelm before the +//! Jira app had its ticket lookup, and copied the hosted links once. The app +//! gained the lookup in a minor version, which Forge rolls out with no +//! lifecycle event, so the app never registered it, and the install never +//! copied again. Chat read "no lookup link" as "not connected". +//! +//! Guarantee: one answer to "is Jira connected" for every reader +//! (`common::jira_connection::Connection::connected`); a missing ability is +//! named as that ability, never as "not connected" (`Gap::words`); a record +//! that lacks a link the app always registers asks the app to register again +//! (`missing_registrations`, `Connection::register_again`); and an install's +//! copy that differs from what the site registered on CoderHelm is copied +//! again (`registered`, `copy_is_stale`). + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use common::jira_connection::{ + copy_is_stale, missing_registrations, registered, Connection, Gap, TicketReads, NOT_CONNECTED, + REGISTER_AGAIN, +}; + +type Item = HashMap; + +fn item(pairs: &[(&str, &str)]) -> Item { + pairs + .iter() + .map(|(k, v)| (k.to_string(), AttributeValue::S(v.to_string()))) + .collect() +} + +const PROXY: &str = "https://api.example.com/hybrid/jira/trigger/ins_a"; + +/// The install's record as it was: the proxy links copied at link time, the +/// install's token, the site, a version seen today, no lookup. +fn install_record() -> Item { + item(&[ + ("list_projects_url", &format!("{PROXY}/list_projects/t")), + ("create_ticket_url", &format!("{PROXY}/create_ticket/t")), + ("add_comment_url", &format!("{PROXY}/add_comment/t")), + ("publish_release_url", ""), + ("get_issues_url", ""), + ("confluence_trigger_url", ""), + ("forge_secret", "token-for-install"), + ("site_url", "https://example.atlassian.net"), + ("app_version", "7.3.0"), + ]) +} + +/// The hosted team's record once the site's app registered again. +fn hosted_after_register() -> Item { + let f = "https://0a1b2c3d.hello.atlassian-dev.net/x1"; + item(&[ + ("list_projects_url", &format!("{f}/lp")), + ("create_ticket_url", &format!("{f}/ct")), + ("add_comment_url", &format!("{f}/ac")), + ("publish_release_url", ""), + ("get_issues_url", &format!("{f}/gi")), + ("confluence_trigger_url", ""), + ("forge_secret", "site-secret"), + ("site_url", "https://example.atlassian.net"), + ]) +} + +#[test] +fn the_app_without_its_lookup_is_connected_and_the_gap_is_named() { + let rec = install_record(); + let c = Connection::from_config(Some(&rec), false); + assert!(c.connected(), "the integrations page and chat agree"); + let TicketReads::Off(gap) = c.ticket_reads() else { + panic!("no lookup link: not ready"); + }; + assert_eq!(gap, Gap::LookupNotRegistered); + let words = gap.words(); + assert!(!words.contains(NOT_CONNECTED), "{words}"); + assert!(!words.contains("isn't connected"), "{words}"); + assert!(words.starts_with("Jira is connected, but"), "{words}"); + assert!(words.contains("ticket lookup"), "{words}"); +} + +#[test] +fn the_system_asks_the_app_to_register_and_the_install_copies_again() { + let rec = install_record(); + // The lookup the app always registers is missing: ask, through the + // project-list link, with the secret the app checks. + assert_eq!(missing_registrations(&rec), vec!["get_issues_url"]); + let c = Connection::from_config(Some(&rec), false); + let (url, body) = c.register_again(Some(&rec)).expect("asks"); + assert!(url.contains("/list_projects/"), "{url}"); + assert_eq!(body[REGISTER_AGAIN], true); + // The site registered on CoderHelm: the install's copy is stale, so it + // is copied again, and then has the lookup. + let hosted = registered(&hosted_after_register()); + let copied: Vec = registered(&rec).iter().map(|s| s.to_string()).collect(); + let hosted: Vec = hosted.iter().map(|s| s.to_string()).collect(); + assert!(hosted.contains(&"get_issues".to_string())); + assert!(copy_is_stale(Some(&hosted), &copied)); + assert!(!copy_is_stale(Some(&hosted), &hosted)); + // Once copied, nothing more is asked. + let mut healed = rec.clone(); + healed.insert( + "get_issues_url".into(), + AttributeValue::S(format!("{PROXY}/get_issues/t")), + ); + assert!(missing_registrations(&healed).is_empty()); + assert!(matches!( + Connection::from_config(Some(&healed), false).ticket_reads(), + TicketReads::Ready { .. } + )); +} + +#[test] +fn only_a_team_with_no_jira_at_all_hears_not_connected() { + let none = Connection::from_config(None, false); + assert_eq!(none.ticket_reads(), TicketReads::Off(Gap::NotConnected)); + assert_eq!(Gap::NotConnected.words(), NOT_CONNECTED); + // A plain webhook is connected too, and says what it can't do. + let hook = Connection::from_config(None, true); + assert!(hook.connected()); + assert!(!Gap::WebhookOnly.words().contains("isn't connected")); +}