Generated banner for Jira
Generated logo for Jira

Jira

MicrosoftOfficialPublished by Microsoft

  • Skill
  • Tool integration
  • Automation and integrations
  • MIT
  • Low risk
  • Has scripts

From the author

Jira issue workflows for search, issue updates, transitions, comments, field discovery, and interactive credential setup via the Jira REST API. Use when you need to configure Jira access, search with JQL, inspect an issue, create or update work items, move an issue between statuses, post comments, or discover required fields for issue creation.
— the description by Microsoft

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The Jira skill provides a secure, Python-based command-line interface for interacting with Jira Cloud, Server, and Data Center instances. It enables users to perform common issue management tasks such as searching with JQL, retrieving issue details, creating or updating work items, transitioning issue statuses, and adding comments. The skill includes robust support for credential management, audit logging, and field discovery, ensuring that interactions with Jira are both traceable and well-structured.

What it does

  • Search for issues using JQL with support for custom field extraction.
  • Create and update Jira issues using JSON payloads.
  • Transition issues between workflow statuses by name or ID.
  • Add and list comments on specific issues.
  • Discover project-specific issue types and required fields.
  • Maintain an audit trail of all API requests for operational transparency.

When to use it

  • When you need to automate issue tracking or status updates within a Jira project.
  • When you need to perform bulk searches or extract specific issue data for reporting.
  • When you are managing Jira workflows and need a programmatic way to transition tasks.
  • When you need to integrate Jira issue management into an agent-driven development workflow.

Advantages

  • Supports both Jira Cloud and Data Center/Server authentication methods.
  • Provides a structured, audit-ready approach to API interactions.
  • Allows for concise, field-specific output using dot-notation.
  • Includes built-in safety mechanisms for credential handling and write confirmation.

Usage examples

“Search for my active bugs in the PROJ project.”
The agent executes a JQL query to return a compact table of issues assigned to the current user with a status of 'Bug' in the specified project.
“Transition issue PROJ-123 to In Progress.”
The agent triggers the transition command to move the specified issue to the 'In Progress' workflow state.
“What are the required fields to create a new Task in PROJ?”
The agent queries the Jira API to list the mandatory fields and issue types for the specified project, helping you construct a valid creation payload.
“Add a comment to PROJ-456 saying the fix is deployed.”
The agent posts the specified text as a comment to the issue PROJ-456.

Install

Documentation by Microsoft

Jira Skill

Overview

This skill provides a Python CLI for common Jira REST API workflows:

  • Search with JQL

  • Get issue details

  • Create and update issues with JSON payloads

  • Transition issues by name or ID

  • Add comments and list existing comments

  • Discover issue types and required fields for creation

The skill supports Jira Cloud with email plus API token authentication and Jira Server or Data Center with a personal access token.

Use --fields on read commands by default to keep output concise. The script supports dot-notation such as fields.status.name and prints tab-separated output for lists.

Prerequisites

Set the required environment variables before running the script.

PlatformRuntime
Cross-platformPython 3.11+
Authentication Variables
VariableWhen requiredPurpose
JIRA_BASE_URLAlwaysJira base URL, for example https://company.atlassian.net
JIRA_USER_EMAILJira CloudAccount email used for basic authentication
JIRA_API_TOKENJira CloudAPI token paired with the Jira Cloud email
JIRA_PATJira Server or Data CenterPersonal access token used for bearer authentication
JIRA_CLOUD_TOKEN_MODEJira Cloud optionalunscoped (default) or scoped
JIRA_CLOUD_IDScoped Jira Cloud tokenAtlassian Cloud resource identifier

Authentication is selected automatically:

  • If JIRA_PAT is set, the script uses bearer authentication for Jira Server or Data Center.

  • Otherwise, the script expects JIRA_USER_EMAIL and JIRA_API_TOKEN for Jira Cloud.

  • Scoped Cloud mode routes only to https://api.atlassian.com/ex/jira/{cloudId}; mixed Cloud and Data Center credentials fail closed.

Scoped Cloud Token Setup

Scoped mode uses the same Basic authentication variables as unscoped mode and adds a Cloud ID. It is not the OAuth 3LO flow, so the oauth/token/accessible-resources endpoint is not a discovery or introspection step for these credentials.

  1. Create a scoped API token for your Atlassian account and select its scopes during creation. See Manage API tokens for your Atlassian account.

  2. Choose scopes for the commands you intend to run. read:jira-work covers search, get, comments, and fields. Add write:jira-work for create, update, transition, and comment. Granular scopes are listed in Jira scopes for OAuth 2.0 and Forge apps. Jira project permissions still apply independently of token scopes.

  3. Obtain the Cloud ID for your site from a trusted Atlassian administrator or your site's account record. The Cloud ID is not a secret, but it determines the request destination.

  4. Confirm that the Cloud ID belongs to the same site as JIRA_BASE_URL. The CLI cannot verify this association: in scoped mode it routes to the Atlassian resource API and does not use JIRA_BASE_URL as a destination. Treat the association as operator-maintained configuration.

  5. Set the variables, then confirm access with a read-only command:

export JIRA_BASE_URL="https://company.atlassian.net"
export JIRA_USER_EMAIL="[email protected]"
export JIRA_API_TOKEN="$(cat ~/.secrets/jira-token)"
export JIRA_CLOUD_TOKEN_MODE="scoped"
export JIRA_CLOUD_ID="your-cloud-id"
python scripts/jira.py --fields key search "ORDER BY created DESC" --max-results 1

A successful read proves the token and route work together. It does not prove that the Cloud ID corresponds to JIRA_BASE_URL, so verify that separately in step 4.

Operational Variables
VariableWhen requiredPurpose
JIRA_AUDIT_LOGOptionalPath to a JSON Lines audit log. When set, every request is audited (see Audit Logging).
JIRA_AUDIT_ACTOROptionalOverrides the recorded actor identity (for example, a CI service principal).
JIRA_DEBUGOptionalInherited environment only. Set to 1 to print a redacted traceback on failure. Never disables redaction.
JIRA_ALLOW_INSECUREOptionalSet to 1 to permit explicit loopback HTTP development endpoints only.
JIRA_CONFIRM_WRITESOptionalInherited environment only. Set to 1 to satisfy the write confirmation gate without --confirm or --yes.
Audit Logging

When JIRA_AUDIT_LOG is set, the script writes a structured JSON Lines audit trail for every API request. Auditing is fail-closed and write-ahead:

  • An attempt record is written before the request is sent. If the audit log cannot be written, the operation is aborted and nothing is sent to Jira.

  • An outcome record (success or error, with HTTP status on failure) is written after the request completes.

Each record includes a UTC timestamp, the actor (from JIRA_AUDIT_ACTOR, otherwise JIRA_USER_EMAIL or jira-pat), the operation, HTTP method, normalized origin, auth mode, and event. Resource paths, Cloud IDs, credentials, authorization headers, and query strings are excluded. Place this operationally sensitive file at an access-controlled path and retain it only as long as operations require. Audit failures after the request emit a warning without altering the result.

Credential Rotation

Atlassian Cloud API tokens have a selected lifetime of 1 to 365 days. Prefer a scoped token and set JIRA_CLOUD_TOKEN_MODE=scoped with JIRA_CLOUD_ID. Atlassian 3LO is not used because its token exchange requires a client secret. For Jira Data Center, create a bounded PAT through the Jira UI and rotate it out of band. The CLI does not issue PATs because the response would contain a new secret without a transactional, non-model-visible sink.

Credential Setup

Run this workflow when credentials are missing, incomplete, or failing. It is verification-first and non-destructive: it audits the current state, guides acquisition, writes only non-secret values, and validates connectivity after the user supplies the credential themselves.

Safety boundary

These rules are not adjustable by autonomy mode or user request.

  • Never ask for, accept, or echo a token or PAT in chat. Display this warning whenever instructing the user to add one:

    ⚠️ NEVER paste your API token or PAT into this chat.
       Tokens entered here are sent through the AI model and are not secure.
       Edit the credentials file directly in the editor instead.
  • Never write a credential value. Non-secret values (base URL, email) may be written; the token line is a placeholder the user replaces in their editor.

  • Never write credentials to a tracked file. ~/.jira.env lives in the user's home directory, outside any repository, so it cannot be accidentally committed. Do not write to .vscode/mcp.json or any repository file.

  • Never modify a shell profile without explicit user confirmation.

  • Never display a token value or any part of one, including a prefix. A credential variable is reported only as set or missing.

  • Never run a command that prints an environment value. printenv | grep -i JIRA and any other filtered dump are prohibited: grep selects which lines print, it does not mask them, so a live token reaches standard output and enters the transcript. Use the set-or-missing probe in the Protocol below instead. Never include raw credential values, full request headers, or verbose or trace HTTP output in a response, even while troubleshooting.

  • Send nothing over the network until the user explicitly confirms connectivity testing.

Terminal session isolation

The agent's terminal and the user's terminal are separate sessions, so an export in one is invisible to the other. The CLI loads supported Jira variables from ~/.jira.env in-process before it creates a client. It treats every value as data, never evaluates the file as shell code, and does not overwrite a variable already inherited by the terminal.

JIRA_DEBUG and JIRA_CONFIRM_WRITES are inherited-environment-only control variables. An unconfirmed write is rejected before the credential file is read, so that file cannot grant mutation authority.

On POSIX platforms, the CLI requires the file to be owned by the current user and accessible only by that owner. It opens the path without following symlinks and in non-blocking mode, then rejects non-regular files, oversized files, malformed assignments, and files with group or other permissions before loading values. Windows does not expose equivalent owner and mode checks through this path; protect the file with user-only ACLs. Errors name the configuration problem without printing credential values.

The environment file bridges the sessions:

  1. On POSIX, create the file with owner-only permissions by running umask 077; touch ~/.jira.env; chmod 0600 ~/.jira.env. On Windows, create it under the user's profile and apply a user-only ACL. Fill in non-secret values and credential placeholders.

  2. Resolve and display the absolute path so the user knows exactly which file to edit.

  3. Open it with code ~/.jira.env.

  4. The user replaces the placeholders and saves.

  5. Run the Jira CLI command. The CLI reads the file directly; do not source it.

Protocol
  1. Audit. The CLI loads supported values from ~/.jira.env, so inherited-process probes alone are not a complete setup audit. Check whether the file exists without reading or printing it. For inherited variables only, classify known names as set or missing without printing any value:

     for v in JIRA_BASE_URL JIRA_USER_EMAIL JIRA_API_TOKEN JIRA_PAT JIRA_CLOUD_TOKEN_MODE JIRA_CLOUD_ID JIRA_AUDIT_LOG JIRA_AUDIT_ACTOR; do
      if printenv "$v" >/dev/null 2>&1; then echo "$v: set"; else echo "$v: missing"; fi
    done

printenv exits zero only when the inherited variable exists, and its output is discarded, so the classification never reveals a value. Use no modifying command during the audit. Let the Jira CLI's value-free validation identify variables still missing after in-process file loading. 2. Detect the platform. JIRA_PAT set indicates Server or Data Center. JIRA_USER_EMAIL with JIRA_API_TOKEN indicates Cloud. When mixed or ambiguous, ask which platform the user has rather than guessing, because the wrong choice produces an authentication failure that looks like a bad credential. 3. Validate what exists. Confirm JIRA_BASE_URL starts with https:// and flag a malformed value. Identify which required variables are missing for the detected platform. 4. Guide acquisition. Direct the user to their Atlassian account token page for Cloud, or their instance personal-access-token settings for Server or Data Center. Give the steps; never request the result. 5. Write the file. Create or update ~/.jira.env with non-secret values and credential placeholders, including a do-not-commit warning comment. 6. Validate connectivity. After the user confirms the credential is saved, run one read-only call. The CLI loads the file in-process. A 401 or 403 means the credential is wrong, expired, or revoked; a connection error means the base URL is wrong. 7. Summarize. Report what changed, what remains, and the set-or-missing state of each variable.

Completion

Setup is complete when every required variable for the detected platform is set, the base URL is well-formed, and one read-only call succeeds. Anything short of that is reported as incomplete with the specific remaining step, never as a qualified success.

Quick Start

Search for your current Jira issues and return a compact table:

python scripts/jira.py --fields key,fields.summary,fields.status.name search 'assignee = currentUser() ORDER BY updated DESC'

Inspect one issue with a compact field list:

python scripts/jira.py --fields key,fields.summary,fields.status.name,fields.assignee.displayName get PROJ-123

Create an issue from JSON piped through stdin:

cat <<'EOF' | python scripts/jira.py create
{
  "fields": {
    "project": { "key": "PROJ" },
    "summary": "Fix login timeout on mobile",
    "issuetype": { "name": "Bug" }
  }
}
EOF

Parameters Reference

Command or optionSyntaxDefaultDescription
searchpython scripts/jira.py search '<jql>' [max_results]max_results = 50Search for issues with JQL
getpython scripts/jira.py get <ISSUE-KEY>NoneGet one issue
createpython scripts/jira.py create '<json>'Reads stdin if omittedCreate an issue from JSON
updatepython scripts/jira.py update <ISSUE-KEY> '<json>'Reads stdin if omittedUpdate an issue from JSON
transitionpython scripts/jira.py transition <ISSUE-KEY> '<name-or-id>'NoneMove an issue to another workflow state
commentpython scripts/jira.py comment <ISSUE-KEY> '<body>'Reads stdin if omittedAdd a comment to an issue
commentspython scripts/jira.py comments <ISSUE-KEY> [ISSUE-KEY ...]NoneList comments across one or more issues
fieldspython scripts/jira.py fields <PROJECT-KEY> [issue-type-id]NoneDiscover issue types or required create fields
--fields--fields key,fields.summary,...NoneExtract selected fields from search, get, and comments output

Script Reference

Search for Issues

Use bounded JQL for Jira Cloud queries. Include a project, assignee, sprint, or another filter instead of a bare ORDER BY query. See JQL Reference for the query patterns this skill expects.

python scripts/jira.py --fields key,fields.summary,fields.status.name search 'project = PROJ AND status = "In Progress"'
python scripts/jira.py --fields key,fields.summary search 'assignee = currentUser() ORDER BY updated DESC' 10
Get One Issue
python scripts/jira.py --fields key,fields.summary,fields.priority.name,fields.status.name get PROJ-123
Create an Issue

Discover valid issue types first:

python scripts/jira.py fields PROJ

Inspect required fields for one issue type:

python scripts/jira.py fields PROJ 10045

Create the issue:

python scripts/jira.py create '{
  "fields": {
    "project": { "key": "PROJ" },
    "summary": "Document rollout checklist",
    "issuetype": { "name": "Task" },
    "labels": ["docs", "release"]
  }
}'
Update an Issue
python scripts/jira.py update PROJ-123 '{
  "fields": {
    "summary": "Updated summary",
    "priority": { "name": "High" },
    "labels": ["backend", "urgent"]
  }
}'
Transition an Issue

Use a transition display name or a numeric transition ID:

python scripts/jira.py transition PROJ-123 'In Progress'
python scripts/jira.py transition PROJ-123 31

If a transition name is not found, the script returns the available transition names in the error output.

Comment on an Issue
python scripts/jira.py comment PROJ-123 'PR #42 addresses this issue.'
printf 'Deployed to staging.\n' | python scripts/jira.py comment PROJ-123
List Comments
python scripts/jira.py --fields _issue,author.displayName,created,body comments PROJ-123 PROJ-456

Troubleshooting

SymptomLikely causeResolution
JIRA_BASE_URL is not setBase URL is missingExport JIRA_BASE_URL in the current shell
Authentication errorWrong token or missing auth variablesVerify JIRA_PAT for Jira Server or Data Center, or verify JIRA_USER_EMAIL and JIRA_API_TOKEN for Jira Cloud
Invalid issue keyIssue key format is malformedUse keys in the form PROJ-123
Transition not foundThe requested workflow transition is unavailableRe-run the command with the transition name returned in the error output
JSON payload errorInvalid JSON was passed to create or updateValidate the payload and retry with well-formed JSON
Network connection errorJira instance URL is unreachableVerify the base URL and local network access

Files

tests/test_jira_helpers.py

# Copyright (c) 2026 Microsoft Corporation. All rights reserved.
# SPDX-License-Identifier: MIT
"""Helper-oriented unit tests for jira.py."""

from __future__ import annotations

import ast
import io
import json
import logging
import os
import pathlib
import stat
from types import SimpleNamespace

import jira
import pytest
from conftest import StdinFactory
from test_constants import (
    ERROR_FIELDS_EMPTY,
    FIELDS_COMMENT,
    FIELDS_ISSUE,
    TEST_API_URL,
    TEST_ISSUE_KEY,
    USAGE_CREATE,
)

SOURCE = pathlib.Path(jira.__file__).read_text(encoding="utf-8")
SOURCE_TREE = ast.parse(SOURCE)
SECRET = "s3cr3t-Value_123"
EXPECTED_REDACT_KEYS = (
    "access_token",
    "refresh_token",
    "code_verifier",
    "client_secret",
    "id_token",
    "assertion",
    "client_assertion",
    "device_code",
    "password",
    "jira_pat",
    "api_token",
    "personal_access_token",
)


@pytest.mark.parametrize(
    "value",
    [
        "$(touch should-not-exist)",
        "`touch should-not-exist`",
        "token; touch should-not-exist",
        "token > should-not-exist",
        "token < should-not-exist",
    ],
)
def test_parse_env_file_preserves_shell_shaped_values(value: str) -> None:
    parsed = jira._parse_env_file(f"JIRA_API_TOKEN={value}")

    assert parsed == {"JIRA_API_TOKEN": value}


def test_parse_env_file_preserves_embedded_newlines() -> None:
    parsed = jira._parse_env_file('JIRA_API_TOKEN="first\nsecond"')

    assert parsed == {"JIRA_API_TOKEN": "first\nsecond"}


def test_parse_env_file_preserves_unicode_line_separator_as_data() -> None:
    value = "first\u2028JIRA_PAT=second"

    parsed = jira._parse_env_file(f"JIRA_API_TOKEN={value}")

    assert parsed == {"JIRA_API_TOKEN": value}


def test_parse_env_file_accepts_crlf_records() -> None:
    parsed = jira._parse_env_file("JIRA_PAT=pat-value\r\nJIRA_BASE_URL=https://x\r\n")

    assert parsed == {
        "JIRA_PAT": "pat-value",
        "JIRA_BASE_URL": "https://x",
    }


def test_parse_env_file_rejects_nul_without_value() -> None:
    with pytest.raises(jira.ScriptError) as exc_info:
        jira._parse_env_file("JIRA_PAT=secret\0value")

    assert "secret" not in str(exc_info.value)
    assert "NUL" in str(exc_info.value)


def test_parse_env_file_rejects_unterminated_quote_without_value() -> None:
    with pytest.raises(jira.ScriptError) as exc_info:
        jira._parse_env_file('JIRA_PAT="secret-value')

    assert "secret-value" not in str(exc_info.value)
    assert "Unterminated" in str(exc_info.value)


def test_parse_env_file_ignores_unsupported_keys() -> None:
    parsed = jira._parse_env_file(
        "PATH=untrusted-path\nJIRA_DEBUG=1\nJIRA_PAT=pat-value"
    )

    assert parsed == {"JIRA_PAT": "pat-value"}


def test_load_jira_env_file_does_not_override_inherited_values(
    tmp_path: pathlib.Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    env_path = tmp_path / ".jira.env"
    env_path.write_text("JIRA_PAT=file-value\n", encoding="utf-8")
    env_path.chmod(stat.S_IRUSR | stat.S_IWUSR)
    monkeypatch.setenv("JIRA_PAT", "inherited-value")

    jira._load_jira_env_file(env_path)

    assert os.environ["JIRA_PAT"] == "inherited-value"


@pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits required")
def test_load_jira_env_file_rejects_non_owner_permissions(
    tmp_path: pathlib.Path,
) -> None:
    env_path = tmp_path / ".jira.env"
    env_path.write_text("JIRA_PAT=secret-value\n", encoding="utf-8")
    env_path.chmod(0o640)

    with pytest.raises(jira.ScriptError) as exc_info:
        jira._load_jira_env_file(env_path)

    assert "secret-value" not in str(exc_info.value)
    assert "owner access only" in str(exc_info.value)


def test_load_jira_env_file_rejects_different_owner(
    tmp_path: pathlib.Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    env_path = tmp_path / ".jira.env"
    env_path.write_text("JIRA_PAT=secret-value\n", encoding="utf-8")
    env_path.chmod(stat.S_IRUSR | stat.S_IWUSR)
    real_fstat = os.fstat

    def fstat_with_different_owner(descriptor: int) -> SimpleNamespace:
        file_stat = real_fstat(descriptor)
        return SimpleNamespace(
            st_mode=file_stat.st_mode,
            st_size=file_stat.st_size,
            st_uid=42,
        )

    monkeypatch.setattr(jira.os, "fstat", fstat_with_different_owner)
    monkeypatch.setattr(jira.os, "getuid", lambda: 100, raising=False)

    with pytest.raises(jira.ScriptError) as exc_info:
        jira._load_jira_env_file(env_path)

    assert "secret-value" not in str(exc_info.value)
    assert "current user" in str(exc_info.value)


def test_load_jira_env_file_rejects_non_regular_file_metadata(
    tmp_path: pathlib.Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    env_path = tmp_path / ".jira.env"
    env_path.write_text("JIRA_PAT=secret-value\n", encoding="utf-8")
    real_fstat = os.fstat

    def fstat_as_fifo(descriptor: int) -> SimpleNamespace:
        file_stat = real_fstat(descriptor)
        return SimpleNamespace(
            st_mode=stat.S_IFIFO | stat.S_IRUSR,
            st_size=file_stat.st_size,
            st_uid=getattr(file_stat, "st_uid", 0),
        )

    monkeypatch.setattr(jira.os, "fstat", fstat_as_fifo)

    with pytest.raises(jira.ScriptError) as exc_info:
        jira._load_jira_env_file(env_path)

    assert "secret-value" not in str(exc_info.value)
    assert "regular file" in str(exc_info.value)


def test_load_jira_env_file_uses_nonblocking_open_when_available(
    tmp_path: pathlib.Path,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    env_path = tmp_path / ".jira.env"
    env_path.write_text("JIRA_PAT=file-value\n", encoding="utf-8")
    env_path.chmod(stat.S_IRUSR | stat.S_IWUSR)
    real_open = os.open
    observed_flags: list[int] = []

    def recording_open(path: pathlib.Path, flags: int) -> int:
        observed_flags.append(flags)
        return real_open(path, flags)

    monkeypatch.setattr(jira.os, "open", recording_open)
    monkeypatch.delenv("JIRA_PAT", raising=False)

    jira._load_jira_env_file(env_path)

    assert observed_flags[0] & getattr(os, "O_NONBLOCK", 0) == getattr(
        os, "O_NONBLOCK", 0
    )
    assert observed_flags[0] & getattr(os, "O_NOFOLLOW", 0) == getattr(
        os, "O_NOFOLLOW", 0
    )


def test_load_jira_env_file_rejects_oversized_file_without_value(
    tmp_path: pathlib.Path,
) -> None:
    env_path = tmp_path / ".jira.env"
    env_path.write_text(
        "JIRA_PAT=" + "s" * jira.MAX_ENV_FILE_BYTES,
        encoding="utf-8",
    )
    env_path.chmod(stat.S_IRUSR | stat.S_IWUSR)

    with pytest.raises(jira.ScriptError) as exc_info:
        jira._load_jira_env_file(env_path)

    assert "ssss" not in str(exc_info.value)
    assert "size limit" in str(exc_info.value)


def test_load_jira_env_file_rejects_invalid_input_without_value(
    tmp_path: pathlib.Path,
) -> None:
    env_path = tmp_path / ".jira.env"
    env_path.write_text("secret-value-without-assignment\n", encoding="utf-8")
    env_path.chmod(stat.S_IRUSR | stat.S_IWUSR)

    with pytest.raises(jira.ScriptError) as exc_info:
        jira._load_jira_env_file(env_path)

    assert "secret-value" not in str(exc_info.value)
    assert "line 1" in str(exc_info.value)


def test_load_jira_env_file_rejects_symlink(
    tmp_path: pathlib.Path,
) -> None:
    target = tmp_path / "target.env"
    target.write_text("JIRA_PAT=secret-value\n", encoding="utf-8")
    env_path = tmp_path / ".jira.env"
    try:
        env_path.symlink_to(target)
    except OSError:
        pytest.skip("symlink creation is unavailable")

    with pytest.raises(jira.ScriptError) as exc_info:
        jira._load_jira_env_file(env_path)

    assert "secret-value" not in str(exc_info.value)
    assert "symlink" in str(exc_info.value)


@pytest.mark.parametrize(
    ("raw", "expected"),
    [
        ('{"errorMessages": ["bad input", "try again"]}', "bad input; try again"),
        ('{"errors": {"summary": "required"}}', "summary: required"),
        ('{"status": "bad"}', '{"status": "bad"}'),
        ("plain text error", "plain text error"),
        ("   ", "No error details returned"),
    ],
)
def test_extract_error_message(raw: str, expected: str) -> None:
    assert jira._extract_error_message(raw) == expected


def test_redact_masks_header_and_query_secrets() -> None:
    payload = (
        "Authorization: Bearer abc123 "
        "PRIVATE-TOKEN: pvt123 "
        "X-API-Key: key123 "
        "Cookie: sessionid=abc "
        "Set-Cookie: sid=abc "
        "https://x/?private_token=abc&access_token=def&token=ghi"
    )

    result = jira._redact(payload)

    assert "abc123" not in result
    assert "pvt123" not in result
    assert "key123" not in result
    assert "sessionid=abc" not in result
    assert "sid=abc" not in result
    assert "[REDACTED]" in result


@pytest.mark.parametrize("key", EXPECTED_REDACT_KEYS)
def test_redact_masks_pinned_json_and_form_keys(key: str) -> None:
    payload = f'{{"{key}": "{SECRET}"}} {key}={SECRET}'

    redacted = jira._redact(payload)

    assert SECRET not in redacted
    assert "[REDACTED]" in redacted


def test_pinned_keyset_excludes_public_pkce_challenge() -> None:
    """``code_challenge`` is public by PKCE design; masking it corrupts the URL."""
    assert jira._REDACT_KEYS == EXPECTED_REDACT_KEYS
    assert "code_challenge" not in jira._REDACT_KEYS

    authorize_url = "https://example.atlassian.net/authorize?code_challenge=abcDEF1"

    assert "abcDEF1" in jira._redact(authorize_url)


def test_redact_masks_mixed_case_escaped_and_encoded_forms() -> None:
    """Upstream payloads vary in casing and encoding; all shapes must mask."""
    payload = (
        '{"Access_Token":"mixed-secret"} '
        r"{\"refresh_token\":\"escaped-secret\"} "
        "api_token%3Dencoded-secret"
    )

    redacted = jira._redact(payload)

    assert "mixed-secret" not in redacted
    assert "escaped-secret" not in redacted
    assert "encoded-secret" not in redacted


def test_redact_masks_azure_sas_query_string() -> None:
    """SAS tokens ride in the query string, so drop everything after the ?."""
    url = f"https://acct.blob.core.windows.net/c/b?sig={SECRET}&se=2026"

    redacted = jira._redact(url)

    assert redacted == "https://acct.blob.core.windows.net/c/b?[REDACTED]"


def test_redact_masks_every_secret_in_a_multi_secret_line() -> None:
    payload = f"a access_token={SECRET}1 b api_token={SECRET}2 c"

    redacted = jira._redact(payload)

    assert f"{SECRET}1" not in redacted
    assert f"{SECRET}2" not in redacted


def test_redact_is_idempotent() -> None:
    """Re-redacting already-redacted text must not corrupt the marker."""
    once = jira._redact(f"api_token={SECRET}")

    assert jira._redact(once) == once


@pytest.mark.parametrize("payload", ["", "   "])
def test_redact_handles_empty_payloads(payload: str) -> None:
    assert jira._redact(payload).strip() == ""


def test_redact_preserves_unicode_around_masked_secrets() -> None:
    redacted = jira._redact(f"\u65e5\u672c\u8a9e api_token={SECRET} \u2713")

    assert SECRET not in redacted
    assert "\u65e5\u672c\u8a9e" in redacted
    assert "\u2713" in redacted


def test_client_repr_omits_authorization_header() -> None:
    client = jira.JiraClient(
        api_url=TEST_API_URL,
        auth_header=f"Bearer {SECRET}",
        use_legacy_search=True,
        audit_actor="actor",
        audit_origin="https://jira.example.com",
        auth_mode="data-center-pat",
    )

    assert SECRET not in repr(client)
    assert "auth_header" not in repr(client)


def test_api_error_and_debug_traceback_are_secret_free(
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
    caplog: pytest.LogCaptureFixture,
) -> None:
    error = jira.JiraAPIError(message=f"api_token={SECRET}")
    monkeypatch.setenv("JIRA_DEBUG", "1")
    with caplog.at_level(logging.ERROR, logger="jira"):
        jira._emit(f"api_token={SECRET}")
    jira._emit_debug_traceback(error)

    captured = capsys.readouterr()
    assert SECRET not in str(error)
    assert SECRET not in repr(error)
    assert SECRET not in captured.err
    assert SECRET not in caplog.text


def test_source_print_calls_remain_in_emit_helpers() -> None:
    owners: list[str] = []
    for node in ast.walk(SOURCE_TREE):
        if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
            continue
        if any(
            isinstance(child, ast.Call)
            and isinstance(child.func, ast.Name)
            and child.func.id == "print"
            for child in ast.walk(node)
        ):
            owners.append(node.name)

    assert set(owners) <= {
        "_emit",
        "_emit_stdout",
        "_emit_structured_stdout",
        "_emit_debug_traceback",
    }
    assert "LOGGER.exception(" not in SOURCE


@pytest.mark.parametrize("issue_key", [TEST_ISSUE_KEY, "ABC1-9", "Proj9-123"])
def test_validate_issue_key_accepts_valid_values(issue_key: str) -> None:
    jira._validate_issue_key(issue_key)


@pytest.mark.parametrize("issue_key", ["", "PROJ", "123-1", "PROJ_1", "PROJ-"])
def test_validate_issue_key_rejects_invalid_values(issue_key: str) -> None:
    with pytest.raises(jira.ScriptError) as exc_info:
        jira._validate_issue_key(issue_key)

    assert exc_info.value.exit_code == jira.EXIT_USAGE
    assert str(exc_info.value) == f"Invalid issue key: {issue_key}"


@pytest.mark.parametrize(
    ("payload", "expected"),
    [
        ('{"fields": {"summary": "x"}}', {"fields": {"summary": "x"}}),
        ("[1, 2]", [1, 2]),
    ],
)
def test_read_json_argument_parses_argument_payload(
    payload: str,
    expected: object,
) -> None:
    assert jira._read_json_argument(payload, USAGE_CREATE) == expected


def test_read_json_argument_reads_stdin(stdin_factory: StdinFactory) -> None:
    stdin_factory('{"fields": {"summary": "stdin"}}')

    assert jira._read_json_argument(None, USAGE_CREATE) == {
        "fields": {"summary": "stdin"}
    }


def test_read_json_argument_reads_bounded_stdin(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class LimitedStream(io.StringIO):
        def read(self, size: int | None = -1) -> str:
            if size is None or size < 0:
                raise AssertionError("unbounded stdin read")
            return super().read(size)

    monkeypatch.setattr("sys.stdin", LimitedStream('{"fields": {"summary": "stdin"}}'))

    assert jira._read_json_argument(None, USAGE_CREATE) == {
        "fields": {"summary": "stdin"}
    }


def test_read_json_argument_rejects_oversized_stdin(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    class LimitedStream(io.StringIO):
        def read(self, size: int | None = -1) -> str:
            if size is None or size < 0:
                raise AssertionError("unbounded stdin read")
            return super().read(size)

    monkeypatch.setattr("sys.stdin", LimitedStream("x" * (jira.MAX_BODY_BYTES + 1)))

    with pytest.raises(jira.ScriptError) as exc_info:
        jira._read_json_argument(None, USAGE_CREATE)

    assert exc_info.value.exit_code == jira.EXIT_USAGE
    assert "size limit" in str(exc_info.value).lower()


def test_read_json_argument_requires_content(stdin_factory: StdinFactory) -> None:
    stdin_factory("")

    with pytest.raises(jira.ScriptError) as exc_info:
        jira._read_json_argument(None, USAGE_CREATE)

    assert exc_info.value.exit_code == jira.EXIT_USAGE
    assert str(exc_info.value) == USAGE_CREATE


def test_read_json_argument_rejects_invalid_json() -> None:
    with pytest.raises(jira.ScriptError) as exc_info:
        jira._read_json_argument("{bad json}", USAGE_CREATE)

    assert exc_info.value.exit_code == jira.EXIT_USAGE
    assert "Invalid JSON payload" in str(exc_info.value)


@pytest.mark.parametrize(
    ("payload", "path", "expected"),
    [
        ({"key": TEST_ISSUE_KEY}, "key", TEST_ISSUE_KEY),
        ({"fields": {"summary": "Issue title"}}, "fields.summary", "Issue title"),
        ({"fields": {"labels": ["bug", "urgent"]}}, "fields.labels", "bug, urgent"),
        ({"fields": {"metadata": {"count": 3}}}, "fields.metadata", '{"count": 3}'),
        ({"fields": {"summary": None}}, "fields.summary", ""),
        ({"fields": "wrong"}, "fields.summary", ""),
    ],
)
def test_extract_field_returns_expected_values(
    payload: object,
    path: str,
    expected: str,
) -> None:
    assert jira._extract_field(payload, path) == expected


@pytest.mark.parametrize(
    ("value", "expected"),
    [(7, "7"), ("text", "text"), ({"x": 1}, '{"x": 1}'), ([1, 2], "[1, 2]")],
)
def test_stringify_value_renders_supported_types(value: object, expected: str) -> None:
    assert jira._stringify_value(value) == expected


def test_split_fields_returns_expected_list() -> None:
    assert jira._split_fields(" key, fields.summary , fields.status.name ") == [
        "key",
        "fields.summary",
        "fields.status.name",
    ]


@pytest.mark.parametrize("raw_fields", [None, ""])
def test_split_fields_returns_none_for_missing_value(raw_fields: str | None) -> None:
    assert jira._split_fields(raw_fields) is None


def test_split_fields_rejects_blank_field_list() -> None:
    with pytest.raises(jira.ScriptError) as exc_info:
        jira._split_fields(" , ")

    assert exc_info.value.exit_code == jira.EXIT_USAGE
    assert str(exc_info.value) == ERROR_FIELDS_EMPTY


def test_print_selected_fields_formats_lists(
    capsys: pytest.CaptureFixture[str],
) -> None:
    jira._print_selected_fields(
        [
            {"key": TEST_ISSUE_KEY, "fields": {"summary": "One"}},
            {"key": "PROJ-2", "fields": {"summary": "Two"}},
        ],
        FIELDS_ISSUE,
    )

    assert capsys.readouterr().out.splitlines() == [
        "key\tfields.summary",
        f"{TEST_ISSUE_KEY}\tOne",
        "PROJ-2\tTwo",
    ]


def test_print_selected_fields_formats_single_object(
    capsys: pytest.CaptureFixture[str],
) -> None:
    jira._print_selected_fields(
        {
            "_issue": TEST_ISSUE_KEY,
            "author": {"displayName": "Ada"},
            "body": "done",
        },
        FIELDS_COMMENT,
    )

    assert capsys.readouterr().out.splitlines() == [
        f"_issue: {TEST_ISSUE_KEY}",
        "author.displayName: Ada",
        "body: done",
    ]


def test_print_selected_fields_preserves_empty_edge_columns(
    capsys: pytest.CaptureFixture[str],
) -> None:
    jira._print_selected_fields(
        [{"first": "", "title": "fix secret token password", "last": ""}],
        ["first", "title", "last"],
    )

    lines = capsys.readouterr().out.splitlines()
    assert lines[1].split("\t") == ["", "fix secret token password", ""]


def test_sanitize_structured_preserves_sensitive_container_shape() -> None:
    payload = {
        "summary": "Basic auth broken",
        "api_token": {"value": SECRET, "nested": [SECRET]},
    }

    sanitized = jira._sanitize_structured(payload)

    assert sanitized == {
        "summary": "Basic auth broken",
        "api_token": {"value": "[REDACTED]", "nested": ["[REDACTED]"]},
    }


def test_print_result_with_none_produces_no_output(
    capsys: pytest.CaptureFixture[str],
) -> None:
    jira._print_result(None, None)

    assert capsys.readouterr().out == ""


def test_print_result_with_fields_delegates_to_selected_fields(
    capsys: pytest.CaptureFixture[str],
) -> None:
    jira._print_result(
        {"key": TEST_ISSUE_KEY, "fields": {"summary": "One"}},
        FIELDS_ISSUE,
    )

    assert capsys.readouterr().out.splitlines() == [
        f"key: {TEST_ISSUE_KEY}",
        "fields.summary: One",
    ]


def test_print_result_prints_string_and_json(
    capsys: pytest.CaptureFixture[str],
) -> None:
    jira._print_result("plain text", None)
    jira._print_result({"key": TEST_ISSUE_KEY}, None)

    lines = capsys.readouterr().out.splitlines()
    assert lines[0] == "plain text"
    assert json.loads("\n".join(lines[1:])) == {"key": TEST_ISSUE_KEY}


def test_emit_writes_exactly_one_stderr_line() -> None:
    """_emit prints once; logging's lastResort must not echo the record.

    _emit both logs at ERROR and prints to stderr. A logger with no handler
    falls back to logging.lastResort, which writes WARNING-or-above records to
    stderr as well, so every CLI error would appear twice.
    """
    assert any(isinstance(h, logging.NullHandler) for h in jira.LOGGER.handlers)


def test_emit_is_not_duplicated_by_last_resort(
    capsys: pytest.CaptureFixture[str],
) -> None:
    jira._emit("single line")

    lines = [line for line in capsys.readouterr().err.splitlines() if line.strip()]

    assert lines == ["single line"]

Requirements and compatibility

Written for: GitHub Copilot, Claude Code

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Claude Code frontmatter, Needs Python

The author says: Requires Python 3.11+ and Jira credentials in environment variables

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Microsoft
Publisher
Microsoft (Official)
Source
microsoft/hve-core · .github/skills/project-planning/jira · commit f425e94
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Microsoft.

Get it from the source

8 of this skill’s files are not mirrored here, so there is no ZIP. Get the complete skill from its source: microsoft/hve-core