Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions coderhelm-jira/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -190,6 +191,7 @@ exports.handler = async (event, context) => {
});

console.log(`Forwarded comment on ${issue.key} → gateway (${response.status})`);
await registerIfVersionChanged(config);
return;
}

Expand Down Expand Up @@ -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" }) };
Expand Down
93 changes: 79 additions & 14 deletions coderhelm-jira/src/register.js
Original file line number Diff line number Diff line change
@@ -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 || "";
Expand All @@ -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),
Expand All @@ -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;
Expand All @@ -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;
97 changes: 97 additions & 0 deletions coderhelm-jira/test/register.test.js
Original file line number Diff line number Diff line change
@@ -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/);
});
7 changes: 7 additions & 0 deletions docs/incidents/jc_jira_connected_in_chat.md
Original file line number Diff line number Diff line change
@@ -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`).
2 changes: 1 addition & 1 deletion docs/jira-app-release.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading
Loading