feat(jira): pick the project, issue type and priority from the site (1.3.0)
create_issue and edit_issue declare options_from on project_key, issue_type_name and priority, and link_issues on link_type, so the playbook editor lists the Jira site's own values. Three read commands feed them: list_projects, list_issue_types (per project) and list_priorities. The README documents enum and options_from. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WhDQSYZd1mFtRsXK4ixtyB
This commit is contained in:
@@ -113,6 +113,32 @@ A command is **request-based** when it has a `request:` block, or
|
||||
**script-based** when a matching `scripts/<command-id>.py` exists. Prefer
|
||||
request-based commands: they need no sandbox and are easier to audit.
|
||||
|
||||
### Inputs with a list of values
|
||||
|
||||
An input can offer its values in the playbook editor instead of a free-text box.
|
||||
|
||||
- **A fixed list** — `enum:`, when the values are the vendor's own and the same
|
||||
everywhere (a verdict, a status). The editor shows a drop-down, and the
|
||||
command bar refuses a value outside it.
|
||||
- **A list read from the tenant** — `options_from:`, when the values belong to
|
||||
each customer's tool (projects, issue types, priorities). The editor runs the
|
||||
named command on the instance and lists what it returns; a typed value or an
|
||||
expression is still accepted.
|
||||
|
||||
```yaml
|
||||
issue_type_name:
|
||||
type: string
|
||||
options_from:
|
||||
command: list_issue_types # a command of this integration, risk: read only
|
||||
path: issue_types # where the rows are in its output (empty: the output itself)
|
||||
value: name # row field written into the input
|
||||
label: name # row field shown in the list (defaults to value)
|
||||
depends_on: [project_key] # sibling inputs passed to the command, when filled with a literal
|
||||
```
|
||||
|
||||
Riposte refuses an `options_from` command that is not `risk: read`: opening a
|
||||
field must never change anything in the customer's tool.
|
||||
|
||||
### `risk:` — the agent approval gate
|
||||
|
||||
Every command declares a tier. It is what Riposte's agent approval gate reads:
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
id: jira
|
||||
name: Jira
|
||||
version: 1.2.0
|
||||
version: 1.3.0
|
||||
description: "Atlassian Jira (REST API, Cloud and On-Prem/Data Center) — issue lifecycle (create/read/edit/delete, transitions, assign), comments, web + issue links, attachments (upload/download/delete), field and user lookups, agile boards/sprints/epics, plus issue ingestion (get_incidents) with an OCSF mapper. Basic (email + API token) or Personal Access Token authentication. Stdlib-only, no extra Python dependencies."
|
||||
changelog: "1.2.0 — Declare the risk tier on the 11 commands that carried none: 8 safe_write, 3 destructive. An unset risk is read as destructive by the agent approval gate, so the 8 that only annotate sat behind the same prompt as the ones that change the estate. | 1.1.0 — New command list_filters: the saved filters a Jira instance already holds, with their id, JQL and owner, plus the exact clause to paste into a fetch. A saved filter could always be ingested — filter = 12345 is ordinary JQL — but nothing told you the id, so the workflow was invisible. get_incidents and query_issues now mention it in their help. 1.0.2 — Command field help rewritten: every input now says what to type, in what format, and which command finds the value, instead of restating the field name. get_incidents explains that the fetch adds its own created >= watermark clause and ORDER BY, that the watermark is filled by the alert rule, and that a run does not page. Assignee, board, sprint, comment and attachment fields name the command that returns their id. 1.0.1 — A personal access token silently outranked Basic credentials, so an unusable value left in pat turned every call into an opaque 401. Basic authentication now wins whenever username and api_key are both set, pat serves the rest, and a 401/403 names the method it used and whether the other was configured and ignored. Three configurations that cannot work are refused with the reason instead of being sent to Jira: no usable credential, the Cloud gateway URL without a cloud_id, and a cloud_id set against any other host. HTML error pages are condensed to their message rather than dumped whole, and a non-JSON body reports what answered and where. 1.0.0 — Initial release: JQL ingestion + query, full issue CRUD and transitions, comments, links, attachments, fields/users, and agile board/sprint/epic listing. Cloud (API v3, ADF bodies) and On-Prem (API v2) supported."
|
||||
changelog: "1.3.0 — create_issue and edit_issue offer the Jira site's own values: the project, the issue type of that project and the priority are picked from a list the playbook editor loads from the instance, as is link_issues' link type. Three read commands feed them — list_projects, list_issue_types and list_priorities — and each field keeps accepting a typed value or an expression. 1.2.0 — Declare the risk tier on the 11 commands that carried none: 8 safe_write, 3 destructive. An unset risk is read as destructive by the agent approval gate, so the 8 that only annotate sat behind the same prompt as the ones that change the estate. | 1.1.0 — New command list_filters: the saved filters a Jira instance already holds, with their id, JQL and owner, plus the exact clause to paste into a fetch. A saved filter could always be ingested — filter = 12345 is ordinary JQL — but nothing told you the id, so the workflow was invisible. get_incidents and query_issues now mention it in their help. 1.0.2 — Command field help rewritten: every input now says what to type, in what format, and which command finds the value, instead of restating the field name. get_incidents explains that the fetch adds its own created >= watermark clause and ORDER BY, that the watermark is filled by the alert rule, and that a run does not page. Assignee, board, sprint, comment and attachment fields name the command that returns their id. 1.0.1 — A personal access token silently outranked Basic credentials, so an unusable value left in pat turned every call into an opaque 401. Basic authentication now wins whenever username and api_key are both set, pat serves the rest, and a 401/403 names the method it used and whether the other was configured and ignored. Three configurations that cannot work are refused with the reason instead of being sent to Jira: no usable credential, the Cloud gateway URL without a cloud_id, and a cloud_id set against any other host. HTML error pages are condensed to their message rather than dumped whole, and a non-JSON body reports what answered and where. 1.0.0 — Initial release: JQL ingestion + query, full issue CRUD and transitions, comments, links, attachments, fields/users, and agile board/sprint/epic listing. Cloud (API v3, ADF bodies) and On-Prem (API v2) supported."
|
||||
category: ticketing
|
||||
|
||||
# Per-instance configuration. For Jira Cloud set cloud_id (found at
|
||||
@@ -91,13 +91,22 @@ commands:
|
||||
risk: safe_write
|
||||
inputs_schema:
|
||||
properties:
|
||||
project_key: { type: string, description: "Project key — the prefix of its issue keys, so SOC for SOC-1423. Give this or project_name." }
|
||||
project_key:
|
||||
type: string
|
||||
description: "Project key — the prefix of its issue keys, so SOC for SOC-1423. Give this or project_name."
|
||||
options_from: { command: list_projects, path: projects, value: key, label: name }
|
||||
project_name: { type: string, description: "Project display name, e.g. Security Operations. It must match exactly one project. Give this or project_key, which is the faster path." }
|
||||
issue_type_name: { type: string, description: "Issue type as the target project names it, e.g. Task, Bug, Incident. Types are per-project. Give this or issue_type_id." }
|
||||
issue_type_name:
|
||||
type: string
|
||||
description: "Issue type as the target project names it, e.g. Task, Bug, Incident. Types are per-project. Give this or issue_type_id."
|
||||
options_from: { command: list_issue_types, path: issue_types, value: name, label: name, depends_on: [project_key] }
|
||||
issue_type_id: { type: string, description: "Numeric issue type ID, e.g. 10004. Give this or issue_type_name, which is usually easier to read." }
|
||||
summary: { type: string, description: "The issue title, one line. This is what shows in every Jira list." }
|
||||
description: { type: string, description: "Body text. Write plain text: it is converted to Atlassian Document Format on Cloud." }
|
||||
priority: { type: string, description: "Priority name exactly as the project defines it, e.g. Highest, High, Medium. An unknown name is rejected." }
|
||||
priority:
|
||||
type: string
|
||||
description: "Priority name exactly as the project defines it, e.g. Highest, High, Medium. An unknown name is rejected."
|
||||
options_from: { command: list_priorities, path: priorities, value: name, label: name }
|
||||
labels: { type: string, description: "Comma-separated, no space inside a label, e.g. soc,phishing. Unknown labels are created." }
|
||||
components: { type: string, description: "Comma-separated, e.g. Network,Endpoint. Components must already exist in the project — Jira will not create them." }
|
||||
assignee_id: { type: string, description: "Cloud: the account ID, e.g. 5b10a2844c20165700ede21g. get_id_by_attribute turns a name or email into one." }
|
||||
@@ -116,7 +125,10 @@ commands:
|
||||
issue_key: { type: string, description: "Issue key as shown in Jira, e.g. SOC-1423. Give this or issue_id." }
|
||||
summary: { type: string, description: "Replacement title. Leave empty to keep the current one." }
|
||||
description: { type: string, description: "Replacement body, plain text. Replaces the whole description; it does not append." }
|
||||
priority: { type: string, description: "Priority name exactly as the project defines it, e.g. Highest, High, Medium. An unknown name is rejected." }
|
||||
priority:
|
||||
type: string
|
||||
description: "Priority name exactly as the project defines it, e.g. Highest, High, Medium. An unknown name is rejected."
|
||||
options_from: { command: list_priorities, path: priorities, value: name, label: name }
|
||||
labels: { type: string, description: "Comma-separated, e.g. soc,phishing. Replaces the whole list: a label left out is removed." }
|
||||
components: { type: string, description: "Comma-separated, e.g. Network,Endpoint. Replaces the whole list, and each must already exist in the project." }
|
||||
assignee_id: { type: string, description: "Cloud: the account ID, e.g. 5b10a2844c20165700ede21g. get_id_by_attribute turns a name or email into one." }
|
||||
@@ -232,7 +244,10 @@ commands:
|
||||
properties:
|
||||
inward_issue: { type: string, description: "One end of the link, key or numeric ID, e.g. SOC-1423. get_link_types gives each type's inward and outward wording, which tells you which issue goes on which side." }
|
||||
outward_issue: { type: string, description: "The other end, key or numeric ID, e.g. SOC-1500. See get_link_types for which side is which." }
|
||||
link_type: { type: string, description: "Link type by name, e.g. Blocks, Relates, Duplicate — exactly as get_link_types returns it." }
|
||||
link_type:
|
||||
type: string
|
||||
description: "Link type by name, e.g. Blocks, Relates, Duplicate — exactly as get_link_types returns it."
|
||||
options_from: { command: get_link_types, path: link_types, value: name, label: name }
|
||||
comment: { type: string, description: "Comment recorded alongside the link. Optional." }
|
||||
required: [inward_issue, outward_issue, link_type]
|
||||
outputs_schema: { properties: {} }
|
||||
@@ -278,6 +293,31 @@ commands:
|
||||
outputs_schema: { properties: {} }
|
||||
|
||||
# ── Fields / users ────────────────────────────────────────────────────────
|
||||
- id: list_projects
|
||||
name: jira-list-projects
|
||||
description: "List the projects the account can see, with their key and name. Feeds the project picker of create_issue."
|
||||
risk: read
|
||||
inputs_schema:
|
||||
properties: {}
|
||||
required: []
|
||||
outputs_schema: { properties: {} }
|
||||
- id: list_issue_types
|
||||
name: jira-list-issue-types
|
||||
description: "List the issue types of one project — the ones create_issue accepts there — or every type of the site when no project is given."
|
||||
risk: read
|
||||
inputs_schema:
|
||||
properties:
|
||||
project_key: { type: string, description: "Project key, e.g. SOC. Empty lists the site's types, some of which a given project may refuse." }
|
||||
required: []
|
||||
outputs_schema: { properties: {} }
|
||||
- id: list_priorities
|
||||
name: jira-list-priorities
|
||||
description: "List the priorities defined on the site, by name."
|
||||
risk: read
|
||||
inputs_schema:
|
||||
properties: {}
|
||||
required: []
|
||||
outputs_schema: { properties: {} }
|
||||
- id: list_fields
|
||||
name: jira-list-fields
|
||||
description: "List the system and custom issue fields."
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import base64, html, json, os, re, sys, urllib.parse, urllib.request, urllib.error
|
||||
|
||||
|
||||
def _cfg():
|
||||
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
|
||||
|
||||
|
||||
def _is_cloud():
|
||||
return bool(str(_cfg().get("cloud_id") or "").strip())
|
||||
|
||||
|
||||
def _api():
|
||||
return "3" if _is_cloud() else "2"
|
||||
|
||||
|
||||
def _base():
|
||||
cfg = _cfg()
|
||||
root = str(cfg.get("server_url") or "https://api.atlassian.com/ex/jira").rstrip("/")
|
||||
cloud_id = str(cfg.get("cloud_id") or "").strip()
|
||||
if not cloud_id and "api.atlassian.com" in root:
|
||||
# The Cloud gateway addresses a site by its cloud id; without one every
|
||||
# path below it is a dead link, and Jira answers with an HTML 404 that
|
||||
# says nothing about the cause.
|
||||
raise Exception(
|
||||
"server_url is the Jira Cloud gateway (" + root + ") but cloud_id is empty. "
|
||||
"Set cloud_id, found at admin.atlassian.com/s/<cloud_id>/users, or point "
|
||||
"server_url at your own Jira URL for On-Prem/Data Center."
|
||||
)
|
||||
if cloud_id and "api.atlassian.com" not in root:
|
||||
# The reverse mistake, and the harder one to see: against any other host
|
||||
# a cloud id is just a path segment, and every call 404s.
|
||||
raise Exception(
|
||||
"cloud_id is set but server_url (" + root + ") is not the Jira Cloud gateway. "
|
||||
"A cloud id addresses a site through https://api.atlassian.com/ex/jira only. "
|
||||
"Clear cloud_id for On-Prem/Data Center, or restore the gateway URL."
|
||||
)
|
||||
return root + "/" + cloud_id if cloud_id else root
|
||||
|
||||
|
||||
def _creds():
|
||||
# A credential pasted from a password manager often carries a trailing
|
||||
# newline; unstripped it corrupts the header and reads back as a wrong
|
||||
# password. Basic wins whenever the pair is complete: a token left behind
|
||||
# from another deployment must not outrank credentials just filled in.
|
||||
# A lone username, or a lone api_key, is not a pair.
|
||||
cfg = _cfg()
|
||||
user = str(cfg.get("username") or "").strip()
|
||||
key = str(cfg.get("api_key") or "").strip()
|
||||
pat = str(cfg.get("pat") or "").strip()
|
||||
mode = "basic" if (user and key) else ("pat" if pat else "")
|
||||
return mode, user, key, pat
|
||||
|
||||
|
||||
def _auth_method():
|
||||
# Named in a 401/403, where the useful question is which credential was sent.
|
||||
mode, user, key, pat = _creds()
|
||||
if mode == "basic":
|
||||
return "Basic authentication as " + user + (
|
||||
" (a personal access token is also configured and was ignored)" if pat else ""
|
||||
)
|
||||
if mode == "pat":
|
||||
half = ""
|
||||
if user or key:
|
||||
half = " (" + ("username" if user else "api_key") + " is set but its pair is "
|
||||
half += "empty, so Basic authentication was not used)"
|
||||
return "a personal access token" + half
|
||||
return "no credential"
|
||||
|
||||
|
||||
def _auth():
|
||||
mode, user, key, pat = _creds()
|
||||
if mode == "basic":
|
||||
cred = (user + ":" + key).encode("utf-8")
|
||||
return "Basic " + base64.b64encode(cred).decode("ascii")
|
||||
if mode == "pat":
|
||||
return "Bearer " + pat
|
||||
raise Exception(
|
||||
"No usable credential. Jira Cloud needs username (account email) together with "
|
||||
"api_key (API token); On-Prem/Data Center needs pat. "
|
||||
+ ("Only " + ("username" if user else "api_key") + " is set."
|
||||
if (user or key) else "None of them is set.")
|
||||
)
|
||||
|
||||
|
||||
def _summarize(raw, ctype):
|
||||
# An error page is a wall of markup around one sentence. Keep the <title>
|
||||
# and the readable text: the rest only makes a log impossible to read.
|
||||
text = raw.decode("utf-8", "replace") if isinstance(raw, bytes) else str(raw)
|
||||
if "json" in (ctype or "").lower():
|
||||
return text.strip()[:500]
|
||||
title = re.search(r"<title[^>]*>(.*?)</title>", text, re.S | re.I)
|
||||
body = re.sub(r"<(script|style|head)[^>]*>.*?</\1>", " ", text, flags=re.S | re.I)
|
||||
body = re.sub(r"<[^>]+>", " ", body)
|
||||
out = (title.group(1) + " \u2014 " if title else "") + body
|
||||
return re.sub(r"\s+", " ", html.unescape(out)).strip()[:500]
|
||||
|
||||
|
||||
def request(method, path, params=None, body=None, full_url=None, raw=False):
|
||||
url = full_url or (_base() + path)
|
||||
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
|
||||
if q:
|
||||
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
|
||||
data = json.dumps(body).encode("utf-8") if body is not None else None
|
||||
headers = {"Accept": "application/json", "Authorization": _auth()}
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
with urllib.request.urlopen(req, timeout=90) as r:
|
||||
content = r.read()
|
||||
if raw:
|
||||
return content
|
||||
if not content:
|
||||
return {}
|
||||
try:
|
||||
return json.loads(content)
|
||||
except ValueError:
|
||||
# A 2xx that is not JSON is a login page, an SSO redirect or a proxy
|
||||
# answering in place of Jira. The URL the redirects landed on is
|
||||
# usually the whole diagnosis.
|
||||
landed = urllib.parse.urlsplit(r.geturl())
|
||||
ctype = r.headers.get("Content-Type") or "unknown"
|
||||
raise Exception(
|
||||
"Jira answered " + str(r.getcode()) + " with a non-JSON body at "
|
||||
+ landed.scheme + "://" + landed.netloc + landed.path
|
||||
+ " (content-type: " + ctype + "): " + _summarize(content, ctype)
|
||||
)
|
||||
|
||||
|
||||
def issue_ref(inputs):
|
||||
ref = str(inputs.get("issue_id") or "") or str(inputs.get("issue_key") or "")
|
||||
if not ref:
|
||||
raise Exception("issue_id or issue_key is required")
|
||||
return urllib.parse.quote(ref, safe="")
|
||||
|
||||
|
||||
def adf(text):
|
||||
# Jira Cloud (API v3) expects Atlassian Document Format for rich text; On-Prem (v2) takes plain text.
|
||||
if not _is_cloud():
|
||||
return text
|
||||
return {"type": "doc", "version": 1,
|
||||
"content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]}
|
||||
|
||||
|
||||
def main():
|
||||
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
|
||||
project = str(inputs.get("project_key") or "").strip()
|
||||
if project:
|
||||
# Issue types are per project: the project's own list is the one
|
||||
# create_issue accepts, where the global list offers types it refuses.
|
||||
res = request("GET", "/rest/api/" + _api() + "/project/" + urllib.parse.quote(project, safe=""))
|
||||
types = res.get("issueTypes", []) or []
|
||||
else:
|
||||
types = request("GET", "/rest/api/" + _api() + "/issuetype") or []
|
||||
out, seen = [], set()
|
||||
for t in types:
|
||||
name = t.get("name", "")
|
||||
if not name or name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
out.append({"id": t.get("id", ""), "name": name, "subtask": bool(t.get("subtask"))})
|
||||
print(json.dumps({"issue_types": out}))
|
||||
|
||||
|
||||
try:
|
||||
main()
|
||||
except urllib.error.HTTPError as e:
|
||||
ctype = e.headers.get("Content-Type", "") if e.headers else ""
|
||||
detail = _summarize(e.read(), ctype)
|
||||
if e.code in (401, 403):
|
||||
detail += " \u2014 the request was sent using " + _auth_method()
|
||||
print(json.dumps({"error": "HTTP " + str(e.code), "detail": detail}))
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(json.dumps({"error": str(e)}))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,161 @@
|
||||
import base64, html, json, os, re, sys, urllib.parse, urllib.request, urllib.error
|
||||
|
||||
|
||||
def _cfg():
|
||||
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
|
||||
|
||||
|
||||
def _is_cloud():
|
||||
return bool(str(_cfg().get("cloud_id") or "").strip())
|
||||
|
||||
|
||||
def _api():
|
||||
return "3" if _is_cloud() else "2"
|
||||
|
||||
|
||||
def _base():
|
||||
cfg = _cfg()
|
||||
root = str(cfg.get("server_url") or "https://api.atlassian.com/ex/jira").rstrip("/")
|
||||
cloud_id = str(cfg.get("cloud_id") or "").strip()
|
||||
if not cloud_id and "api.atlassian.com" in root:
|
||||
# The Cloud gateway addresses a site by its cloud id; without one every
|
||||
# path below it is a dead link, and Jira answers with an HTML 404 that
|
||||
# says nothing about the cause.
|
||||
raise Exception(
|
||||
"server_url is the Jira Cloud gateway (" + root + ") but cloud_id is empty. "
|
||||
"Set cloud_id, found at admin.atlassian.com/s/<cloud_id>/users, or point "
|
||||
"server_url at your own Jira URL for On-Prem/Data Center."
|
||||
)
|
||||
if cloud_id and "api.atlassian.com" not in root:
|
||||
# The reverse mistake, and the harder one to see: against any other host
|
||||
# a cloud id is just a path segment, and every call 404s.
|
||||
raise Exception(
|
||||
"cloud_id is set but server_url (" + root + ") is not the Jira Cloud gateway. "
|
||||
"A cloud id addresses a site through https://api.atlassian.com/ex/jira only. "
|
||||
"Clear cloud_id for On-Prem/Data Center, or restore the gateway URL."
|
||||
)
|
||||
return root + "/" + cloud_id if cloud_id else root
|
||||
|
||||
|
||||
def _creds():
|
||||
# A credential pasted from a password manager often carries a trailing
|
||||
# newline; unstripped it corrupts the header and reads back as a wrong
|
||||
# password. Basic wins whenever the pair is complete: a token left behind
|
||||
# from another deployment must not outrank credentials just filled in.
|
||||
# A lone username, or a lone api_key, is not a pair.
|
||||
cfg = _cfg()
|
||||
user = str(cfg.get("username") or "").strip()
|
||||
key = str(cfg.get("api_key") or "").strip()
|
||||
pat = str(cfg.get("pat") or "").strip()
|
||||
mode = "basic" if (user and key) else ("pat" if pat else "")
|
||||
return mode, user, key, pat
|
||||
|
||||
|
||||
def _auth_method():
|
||||
# Named in a 401/403, where the useful question is which credential was sent.
|
||||
mode, user, key, pat = _creds()
|
||||
if mode == "basic":
|
||||
return "Basic authentication as " + user + (
|
||||
" (a personal access token is also configured and was ignored)" if pat else ""
|
||||
)
|
||||
if mode == "pat":
|
||||
half = ""
|
||||
if user or key:
|
||||
half = " (" + ("username" if user else "api_key") + " is set but its pair is "
|
||||
half += "empty, so Basic authentication was not used)"
|
||||
return "a personal access token" + half
|
||||
return "no credential"
|
||||
|
||||
|
||||
def _auth():
|
||||
mode, user, key, pat = _creds()
|
||||
if mode == "basic":
|
||||
cred = (user + ":" + key).encode("utf-8")
|
||||
return "Basic " + base64.b64encode(cred).decode("ascii")
|
||||
if mode == "pat":
|
||||
return "Bearer " + pat
|
||||
raise Exception(
|
||||
"No usable credential. Jira Cloud needs username (account email) together with "
|
||||
"api_key (API token); On-Prem/Data Center needs pat. "
|
||||
+ ("Only " + ("username" if user else "api_key") + " is set."
|
||||
if (user or key) else "None of them is set.")
|
||||
)
|
||||
|
||||
|
||||
def _summarize(raw, ctype):
|
||||
# An error page is a wall of markup around one sentence. Keep the <title>
|
||||
# and the readable text: the rest only makes a log impossible to read.
|
||||
text = raw.decode("utf-8", "replace") if isinstance(raw, bytes) else str(raw)
|
||||
if "json" in (ctype or "").lower():
|
||||
return text.strip()[:500]
|
||||
title = re.search(r"<title[^>]*>(.*?)</title>", text, re.S | re.I)
|
||||
body = re.sub(r"<(script|style|head)[^>]*>.*?</\1>", " ", text, flags=re.S | re.I)
|
||||
body = re.sub(r"<[^>]+>", " ", body)
|
||||
out = (title.group(1) + " \u2014 " if title else "") + body
|
||||
return re.sub(r"\s+", " ", html.unescape(out)).strip()[:500]
|
||||
|
||||
|
||||
def request(method, path, params=None, body=None, full_url=None, raw=False):
|
||||
url = full_url or (_base() + path)
|
||||
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
|
||||
if q:
|
||||
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
|
||||
data = json.dumps(body).encode("utf-8") if body is not None else None
|
||||
headers = {"Accept": "application/json", "Authorization": _auth()}
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
with urllib.request.urlopen(req, timeout=90) as r:
|
||||
content = r.read()
|
||||
if raw:
|
||||
return content
|
||||
if not content:
|
||||
return {}
|
||||
try:
|
||||
return json.loads(content)
|
||||
except ValueError:
|
||||
# A 2xx that is not JSON is a login page, an SSO redirect or a proxy
|
||||
# answering in place of Jira. The URL the redirects landed on is
|
||||
# usually the whole diagnosis.
|
||||
landed = urllib.parse.urlsplit(r.geturl())
|
||||
ctype = r.headers.get("Content-Type") or "unknown"
|
||||
raise Exception(
|
||||
"Jira answered " + str(r.getcode()) + " with a non-JSON body at "
|
||||
+ landed.scheme + "://" + landed.netloc + landed.path
|
||||
+ " (content-type: " + ctype + "): " + _summarize(content, ctype)
|
||||
)
|
||||
|
||||
|
||||
def issue_ref(inputs):
|
||||
ref = str(inputs.get("issue_id") or "") or str(inputs.get("issue_key") or "")
|
||||
if not ref:
|
||||
raise Exception("issue_id or issue_key is required")
|
||||
return urllib.parse.quote(ref, safe="")
|
||||
|
||||
|
||||
def adf(text):
|
||||
# Jira Cloud (API v3) expects Atlassian Document Format for rich text; On-Prem (v2) takes plain text.
|
||||
if not _is_cloud():
|
||||
return text
|
||||
return {"type": "doc", "version": 1,
|
||||
"content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]}
|
||||
|
||||
|
||||
def main():
|
||||
res = request("GET", "/rest/api/" + _api() + "/priority") or []
|
||||
out = [{"id": p.get("id", ""), "name": p.get("name", "")} for p in res if p.get("name")]
|
||||
print(json.dumps({"priorities": out}))
|
||||
|
||||
|
||||
try:
|
||||
main()
|
||||
except urllib.error.HTTPError as e:
|
||||
ctype = e.headers.get("Content-Type", "") if e.headers else ""
|
||||
detail = _summarize(e.read(), ctype)
|
||||
if e.code in (401, 403):
|
||||
detail += " \u2014 the request was sent using " + _auth_method()
|
||||
print(json.dumps({"error": "HTTP " + str(e.code), "detail": detail}))
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(json.dumps({"error": str(e)}))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,177 @@
|
||||
import base64, html, json, os, re, sys, urllib.parse, urllib.request, urllib.error
|
||||
|
||||
|
||||
def _cfg():
|
||||
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
|
||||
|
||||
|
||||
def _is_cloud():
|
||||
return bool(str(_cfg().get("cloud_id") or "").strip())
|
||||
|
||||
|
||||
def _api():
|
||||
return "3" if _is_cloud() else "2"
|
||||
|
||||
|
||||
def _base():
|
||||
cfg = _cfg()
|
||||
root = str(cfg.get("server_url") or "https://api.atlassian.com/ex/jira").rstrip("/")
|
||||
cloud_id = str(cfg.get("cloud_id") or "").strip()
|
||||
if not cloud_id and "api.atlassian.com" in root:
|
||||
# The Cloud gateway addresses a site by its cloud id; without one every
|
||||
# path below it is a dead link, and Jira answers with an HTML 404 that
|
||||
# says nothing about the cause.
|
||||
raise Exception(
|
||||
"server_url is the Jira Cloud gateway (" + root + ") but cloud_id is empty. "
|
||||
"Set cloud_id, found at admin.atlassian.com/s/<cloud_id>/users, or point "
|
||||
"server_url at your own Jira URL for On-Prem/Data Center."
|
||||
)
|
||||
if cloud_id and "api.atlassian.com" not in root:
|
||||
# The reverse mistake, and the harder one to see: against any other host
|
||||
# a cloud id is just a path segment, and every call 404s.
|
||||
raise Exception(
|
||||
"cloud_id is set but server_url (" + root + ") is not the Jira Cloud gateway. "
|
||||
"A cloud id addresses a site through https://api.atlassian.com/ex/jira only. "
|
||||
"Clear cloud_id for On-Prem/Data Center, or restore the gateway URL."
|
||||
)
|
||||
return root + "/" + cloud_id if cloud_id else root
|
||||
|
||||
|
||||
def _creds():
|
||||
# A credential pasted from a password manager often carries a trailing
|
||||
# newline; unstripped it corrupts the header and reads back as a wrong
|
||||
# password. Basic wins whenever the pair is complete: a token left behind
|
||||
# from another deployment must not outrank credentials just filled in.
|
||||
# A lone username, or a lone api_key, is not a pair.
|
||||
cfg = _cfg()
|
||||
user = str(cfg.get("username") or "").strip()
|
||||
key = str(cfg.get("api_key") or "").strip()
|
||||
pat = str(cfg.get("pat") or "").strip()
|
||||
mode = "basic" if (user and key) else ("pat" if pat else "")
|
||||
return mode, user, key, pat
|
||||
|
||||
|
||||
def _auth_method():
|
||||
# Named in a 401/403, where the useful question is which credential was sent.
|
||||
mode, user, key, pat = _creds()
|
||||
if mode == "basic":
|
||||
return "Basic authentication as " + user + (
|
||||
" (a personal access token is also configured and was ignored)" if pat else ""
|
||||
)
|
||||
if mode == "pat":
|
||||
half = ""
|
||||
if user or key:
|
||||
half = " (" + ("username" if user else "api_key") + " is set but its pair is "
|
||||
half += "empty, so Basic authentication was not used)"
|
||||
return "a personal access token" + half
|
||||
return "no credential"
|
||||
|
||||
|
||||
def _auth():
|
||||
mode, user, key, pat = _creds()
|
||||
if mode == "basic":
|
||||
cred = (user + ":" + key).encode("utf-8")
|
||||
return "Basic " + base64.b64encode(cred).decode("ascii")
|
||||
if mode == "pat":
|
||||
return "Bearer " + pat
|
||||
raise Exception(
|
||||
"No usable credential. Jira Cloud needs username (account email) together with "
|
||||
"api_key (API token); On-Prem/Data Center needs pat. "
|
||||
+ ("Only " + ("username" if user else "api_key") + " is set."
|
||||
if (user or key) else "None of them is set.")
|
||||
)
|
||||
|
||||
|
||||
def _summarize(raw, ctype):
|
||||
# An error page is a wall of markup around one sentence. Keep the <title>
|
||||
# and the readable text: the rest only makes a log impossible to read.
|
||||
text = raw.decode("utf-8", "replace") if isinstance(raw, bytes) else str(raw)
|
||||
if "json" in (ctype or "").lower():
|
||||
return text.strip()[:500]
|
||||
title = re.search(r"<title[^>]*>(.*?)</title>", text, re.S | re.I)
|
||||
body = re.sub(r"<(script|style|head)[^>]*>.*?</\1>", " ", text, flags=re.S | re.I)
|
||||
body = re.sub(r"<[^>]+>", " ", body)
|
||||
out = (title.group(1) + " \u2014 " if title else "") + body
|
||||
return re.sub(r"\s+", " ", html.unescape(out)).strip()[:500]
|
||||
|
||||
|
||||
def request(method, path, params=None, body=None, full_url=None, raw=False):
|
||||
url = full_url or (_base() + path)
|
||||
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
|
||||
if q:
|
||||
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
|
||||
data = json.dumps(body).encode("utf-8") if body is not None else None
|
||||
headers = {"Accept": "application/json", "Authorization": _auth()}
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
with urllib.request.urlopen(req, timeout=90) as r:
|
||||
content = r.read()
|
||||
if raw:
|
||||
return content
|
||||
if not content:
|
||||
return {}
|
||||
try:
|
||||
return json.loads(content)
|
||||
except ValueError:
|
||||
# A 2xx that is not JSON is a login page, an SSO redirect or a proxy
|
||||
# answering in place of Jira. The URL the redirects landed on is
|
||||
# usually the whole diagnosis.
|
||||
landed = urllib.parse.urlsplit(r.geturl())
|
||||
ctype = r.headers.get("Content-Type") or "unknown"
|
||||
raise Exception(
|
||||
"Jira answered " + str(r.getcode()) + " with a non-JSON body at "
|
||||
+ landed.scheme + "://" + landed.netloc + landed.path
|
||||
+ " (content-type: " + ctype + "): " + _summarize(content, ctype)
|
||||
)
|
||||
|
||||
|
||||
def issue_ref(inputs):
|
||||
ref = str(inputs.get("issue_id") or "") or str(inputs.get("issue_key") or "")
|
||||
if not ref:
|
||||
raise Exception("issue_id or issue_key is required")
|
||||
return urllib.parse.quote(ref, safe="")
|
||||
|
||||
|
||||
def adf(text):
|
||||
# Jira Cloud (API v3) expects Atlassian Document Format for rich text; On-Prem (v2) takes plain text.
|
||||
if not _is_cloud():
|
||||
return text
|
||||
return {"type": "doc", "version": 1,
|
||||
"content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]}
|
||||
|
||||
|
||||
def main():
|
||||
# Cloud pages the project list (project/search); On-Prem answers it whole.
|
||||
# Both carry key and name, which is all a picker needs.
|
||||
projects = []
|
||||
if _is_cloud():
|
||||
start = 0
|
||||
while True:
|
||||
res = request("GET", "/rest/api/3/project/search",
|
||||
{"startAt": start, "maxResults": 50, "orderBy": "name"})
|
||||
rows = res.get("values", []) or []
|
||||
projects.extend(rows)
|
||||
start += len(rows)
|
||||
if res.get("isLast", True) or not rows or start >= 1000:
|
||||
break
|
||||
else:
|
||||
projects = request("GET", "/rest/api/2/project") or []
|
||||
out = [{"key": p.get("key", ""), "name": p.get("name", ""), "id": p.get("id", "")}
|
||||
for p in projects]
|
||||
out.sort(key=lambda p: p["name"].lower())
|
||||
print(json.dumps({"projects": out}))
|
||||
|
||||
|
||||
try:
|
||||
main()
|
||||
except urllib.error.HTTPError as e:
|
||||
ctype = e.headers.get("Content-Type", "") if e.headers else ""
|
||||
detail = _summarize(e.read(), ctype)
|
||||
if e.code in (401, 403):
|
||||
detail += " \u2014 the request was sent using " + _auth_method()
|
||||
print(json.dumps({"error": "HTTP " + str(e.code), "detail": detail}))
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(json.dumps({"error": str(e)}))
|
||||
sys.exit(1)
|
||||
Reference in New Issue
Block a user