Shared Atlassian clients: atlassian/jira and atlassian/confluence

New library module yetano.dev/yetano/yetano-clients (owner decision
2026-11-01) replacing the three own Jira clients in yareco, yabaratla
and yamcp:

- atlassian: Options, Auth (api_token, basic, bearer/pat, cookie),
  Deployment (Cloud/Data Center), TLS, APIError and sentinel errors.
- atlassian/internal/transport: retry with backoff on 5xx/connection
  errors, shared adaptive 429 throttle honouring Retry-After (from
  yabaratla/yareco), CA file, proxy, cross-host redirect hardening,
  response cap (from yamcp), startAt pagination, file downloads.
- atlassian/jira: typed reads (projects, versions, fields, issues,
  comments, changelog, editmeta, transitions), JQL search on Cloud
  (/search/jql) and Data Center, classic search pages, issue writes,
  ADF/plain-text bodies per deployment, custom-field helpers.
- atlassian/confluence: small content API client (CQL search, pages,
  spaces, current user, create/update page with version check,
  comment, label), taken over from yamcp.

Standard library only; tests against httptest servers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
terminarandClaude Opus 5.5 committed 2026-11-01 14:11:00 +01:00
commit 6a97dbd4c6
24 files changed
+3524

No files matched your search

+201
View File
@@ -0,0 +1,201 @@
// Package confluence is a small Confluence REST API client (the classic
// /rest/api content API) for Atlassian Cloud and Server/Data Center:
// CQL search, pages with their children and ancestors, spaces, the
// current user, and the writes create page, update page (with an
// optimistic version check), footer comment and label.
//
// It is deliberately small -- what yamcp uses, taken over from there --
// not a complete Confluence SDK. Cloud's newer v2 API (/wiki/api/v2),
// attachments and the site-backup endpoints yabaratla drives are not
// covered (see the repository's TODO.md).
package confluence
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
"yetano.dev/yetano/yetano-clients/atlassian"
"yetano.dev/yetano/yetano-clients/atlassian/internal/transport"
)
// Client is a Confluence client. It is safe for concurrent use.
type Client struct {
t *transport.Client
cloud bool
}
// New builds a Client. BaseURL is the site root: on Cloud without the
// /wiki suffix (the client adds it), on Server/Data Center the
// Confluence root. It sends no request.
func New(o atlassian.Options) (*Client, error) {
t, err := transport.New(o)
if err != nil {
return nil, err
}
return &Client{t: t, cloud: o.Deployment.IsCloud()}, nil
}
// BaseURL is the site root without trailing slash.
func (c *Client) BaseURL() string { return c.t.BaseURL() }
// IsCloud reports whether the client talks to Atlassian Cloud.
func (c *Client) IsCloud() bool { return c.cloud }
// APIPrefix is /wiki/rest/api on Cloud and /rest/api on Server/Data
// Center.
func (c *Client) APIPrefix() string {
if c.cloud {
return "/wiki/rest/api"
}
return "/rest/api"
}
func (c *Client) api(suffix string) string { return c.APIPrefix() + suffix }
// WebBase is the root of the browsable site (with /wiki on Cloud).
func (c *Client) WebBase() string {
if c.cloud {
return c.BaseURL() + "/wiki"
}
return c.BaseURL()
}
// PageURL is the browser URL of a page: from its _links.webui when
// known, else the viewpage.action form.
func (c *Client) PageURL(id string, links *Links) string {
if links != nil && links.WebUI != "" {
return c.WebBase() + links.WebUI
}
return fmt.Sprintf("%s/pages/viewpage.action?pageId=%s", c.WebBase(), id)
}
// Close releases idle connections.
func (c *Client) Close() { c.t.Close() }
// SetSleep replaces every wait -- for tests that must not really wait.
func (c *Client) SetSleep(f func(ctx context.Context, d time.Duration) error) { c.t.SetSleep(f) }
// Get issues a GET against BaseURL+path (for endpoints without a typed
// call) and returns the JSON body.
func (c *Client) Get(ctx context.Context, path string, params url.Values) (json.RawMessage, error) {
return c.t.Do(ctx, http.MethodGet, path, params, nil)
}
func (c *Client) do(ctx context.Context, method, path string, q url.Values, body, out any) error {
raw, err := c.t.Do(ctx, method, path, q, body)
if err != nil {
return err
}
if out == nil {
return nil
}
if err := json.Unmarshal(raw, out); err != nil {
return fmt.Errorf("%s %s: decoding response: %w", method, path, err)
}
return nil
}
func requireID(what, v string) error {
if v == "" {
return fmt.Errorf("%w: %s must not be empty", atlassian.ErrInvalidArgument, what)
}
return nil
}
const contentExpand = "space,version,body.storage,ancestors"
// SearchOptions is one CQL search page. SpaceKey and ContentType are
// convenience filters ANDed onto CQL.
type SearchOptions struct {
CQL string
Start int
Limit int
SpaceKey string
ContentType string // "page", "blogpost", ...
}
// Search runs a CQL search and returns one page of content with space,
// version, storage body and ancestors expanded.
func (c *Client) Search(ctx context.Context, o SearchOptions) (ContentList, error) {
var out ContentList
cql := o.CQL
if o.SpaceKey != "" {
cql = addCQLClause(cql, fmt.Sprintf("space = %q", o.SpaceKey))
}
if o.ContentType != "" {
cql = addCQLClause(cql, fmt.Sprintf("type = %q", o.ContentType))
}
if cql == "" {
return out, fmt.Errorf("%w: cql (or space/content type filters) must resolve to a non-empty query", atlassian.ErrInvalidArgument)
}
q := url.Values{
"cql": {cql},
"start": {strconv.Itoa(o.Start)},
"limit": {strconv.Itoa(o.Limit)},
"expand": {contentExpand},
}
return out, c.do(ctx, http.MethodGet, c.api("/content/search"), q, nil, &out)
}
func addCQLClause(existing, clause string) string {
if existing == "" {
return clause
}
return existing + " AND " + clause
}
// Page returns one page (or other content) with space, version, storage
// body and ancestors.
func (c *Client) Page(ctx context.Context, id string) (Content, error) {
var out Content
if err := requireID("page id", id); err != nil {
return out, err
}
q := url.Values{"expand": {contentExpand}}
return out, c.do(ctx, http.MethodGet, c.api("/content/"+url.PathEscape(id)), q, nil, &out)
}
// PageChildren returns one page of a page's direct child pages.
func (c *Client) PageChildren(ctx context.Context, id string, start, limit int) (ContentList, error) {
var out ContentList
if err := requireID("page id", id); err != nil {
return out, err
}
q := url.Values{"start": {strconv.Itoa(start)}, "limit": {strconv.Itoa(limit)}}
return out, c.do(ctx, http.MethodGet, c.api("/content/"+url.PathEscape(id)+"/child/page"), q, nil, &out)
}
// Space returns one space with its plain description and home page.
func (c *Client) Space(ctx context.Context, key string) (Space, error) {
var out Space
if err := requireID("space key", key); err != nil {
return out, err
}
q := url.Values{"expand": {"description.plain,homepage"}}
return out, c.do(ctx, http.MethodGet, c.api("/space/"+url.PathEscape(key)), q, nil, &out)
}
// ListSpaces returns one page of the spaces the account can see.
func (c *Client) ListSpaces(ctx context.Context, start, limit int) (SpaceList, error) {
var out SpaceList
q := url.Values{"start": {strconv.Itoa(start)}, "limit": {strconv.Itoa(limit)}}
return out, c.do(ctx, http.MethodGet, c.api("/space"), q, nil, &out)
}
// CurrentUser returns the authenticated account.
func (c *Client) CurrentUser(ctx context.Context) (User, error) {
var out User
return out, c.do(ctx, http.MethodGet, c.api("/user/current"), nil, nil, &out)
}
// Ping checks that the API answers (one space listed). Confluence has no
// server-info endpoint that is stable across Cloud and Data Center, so
// this is reachability only, not a version.
func (c *Client) Ping(ctx context.Context) error {
return c.do(ctx, http.MethodGet, c.api("/space"), url.Values{"limit": {"1"}}, nil, nil)
}
+174
View File
@@ -0,0 +1,174 @@
package confluence
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"yetano.dev/yetano/yetano-clients/atlassian"
)
func newTestClient(t *testing.T, h http.HandlerFunc, dep atlassian.Deployment) *Client {
t.Helper()
srv := httptest.NewServer(h)
t.Cleanup(srv.Close)
c, err := New(atlassian.Options{BaseURL: srv.URL, Deployment: dep,
Auth: atlassian.Auth{Type: atlassian.AuthBearer, Token: "t"},
Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
if err != nil {
t.Fatal(err)
}
return c
}
func TestPrefixesAndURLs(t *testing.T) {
noop := func(http.ResponseWriter, *http.Request) {}
cloud := newTestClient(t, noop, atlassian.Cloud)
dc := newTestClient(t, noop, atlassian.DataCenter)
if cloud.APIPrefix() != "/wiki/rest/api" || dc.APIPrefix() != "/rest/api" {
t.Errorf("prefixes = %q, %q", cloud.APIPrefix(), dc.APIPrefix())
}
if got := cloud.PageURL("5", &Links{WebUI: "/spaces/IT/pages/5"}); got != cloud.BaseURL()+"/wiki/spaces/IT/pages/5" {
t.Errorf("PageURL with links = %q", got)
}
if got := dc.PageURL("5", nil); got != dc.BaseURL()+"/pages/viewpage.action?pageId=5" {
t.Errorf("PageURL fallback = %q", got)
}
}
func TestSearchBuildsCQLFromFilters(t *testing.T) {
var gotCQL, gotPath string
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
gotPath, gotCQL = r.URL.Path, r.URL.Query().Get("cql")
fmt.Fprint(w, `{"results":[{"id":"1","title":"A","version":{"number":2}}],"size":1}`)
}, atlassian.Cloud)
res, err := c.Search(context.Background(), SearchOptions{CQL: `text ~ "x"`, SpaceKey: "IT", ContentType: "page", Limit: 5})
if err != nil || len(res.Results) != 1 || res.Results[0].Version.Number != 2 {
t.Fatalf("res = %+v, %v", res, err)
}
if gotPath != "/wiki/rest/api/content/search" || gotCQL != `text ~ "x" AND space = "IT" AND type = "page"` {
t.Errorf("path = %q, cql = %q", gotPath, gotCQL)
}
}
func TestEmptyArgumentsSendNothing(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
t.Errorf("request sent: %s %s", r.Method, r.URL.Path)
}, atlassian.Cloud)
ctx := context.Background()
errs := map[string]error{}
_, errs["Search"] = c.Search(ctx, SearchOptions{})
_, errs["Page"] = c.Page(ctx, "")
_, errs["Space"] = c.Space(ctx, "")
_, errs["AddComment"] = c.AddComment(ctx, "", "x")
for name, err := range errs {
if !errors.Is(err, atlassian.ErrInvalidArgument) {
t.Errorf("%s: err = %v, want ErrInvalidArgument", name, err)
}
}
}
func pageHandler(t *testing.T, onPut func(body map[string]any)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
fmt.Fprint(w, `{"id":"123","title":"Page","space":{"key":"IT"},"version":{"number":5}}`)
return
}
if onPut == nil {
t.Fatalf("unexpected %s", r.Method)
}
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
onPut(body)
fmt.Fprint(w, `{}`)
}
}
func TestUpdatePageRefusesStaleVersion(t *testing.T) {
c := newTestClient(t, pageHandler(t, nil), atlassian.Cloud)
err := c.UpdatePage(context.Background(), UpdatePageInput{ID: "123", Content: "new", ExpectedVersion: 3})
var vc *VersionConflictError
if !errors.As(err, &vc) || vc.Current != 5 || vc.Expected != 3 {
t.Fatalf("err = %v, want VersionConflictError 5/3", err)
}
}
func TestUpdatePageWritesNextVersion(t *testing.T) {
var put map[string]any
c := newTestClient(t, pageHandler(t, func(b map[string]any) { put = b }), atlassian.Cloud)
if err := c.UpdatePage(context.Background(), UpdatePageInput{ID: "123", Content: "a <b>\n\nc", ExpectedVersion: 5}); err != nil {
t.Fatal(err)
}
if put["version"].(map[string]any)["number"].(float64) != 6 || put["title"] != "Page" {
t.Errorf("PUT = %v", put)
}
storage := put["body"].(map[string]any)["storage"].(map[string]any)
if storage["value"] != "<p>a &lt;b&gt;</p><p>c</p>" || storage["representation"] != "storage" {
t.Errorf("storage = %v", storage)
}
}
func TestCreatePageCommentLabel(t *testing.T) {
bodies := map[string]any{}
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
var body any
_ = json.NewDecoder(r.Body).Decode(&body)
key := r.Method + " " + r.URL.Path
if m, ok := body.(map[string]any); ok && m["type"] == "comment" {
key += " comment"
}
bodies[key] = body
fmt.Fprint(w, `{"id":"9"}`)
}, atlassian.DataCenter)
ctx := context.Background()
if id, err := c.CreatePage(ctx, CreatePageInput{SpaceKey: "IT", Title: "T", Content: "x", ParentPageID: "1"}); err != nil || id != "9" {
t.Fatalf("create = %q, %v", id, err)
}
if id, err := c.AddComment(ctx, "9", "hi"); err != nil || id != "9" {
t.Fatalf("comment = %q, %v", id, err)
}
if err := c.AddLabel(ctx, "9", "ops"); err != nil {
t.Fatal(err)
}
page := bodies["POST /rest/api/content"].(map[string]any)
if page["ancestors"].([]any)[0].(map[string]any)["id"] != "1" || page["space"].(map[string]any)["key"] != "IT" {
t.Errorf("create body = %v", page)
}
comment := bodies["POST /rest/api/content comment"].(map[string]any)
if comment["container"].(map[string]any)["id"] != "9" {
t.Errorf("comment body = %v", comment)
}
label := bodies["POST /rest/api/content/9/label"].([]any)[0].(map[string]any)
if label["prefix"] != "global" || label["name"] != "ops" {
t.Errorf("label body = %v", label)
}
}
func TestPingAndCurrentUser(t *testing.T) {
c := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer t" {
t.Errorf("auth header = %q", r.Header.Get("Authorization"))
}
switch r.URL.Path {
case "/wiki/rest/api/space":
fmt.Fprint(w, `{"results":[],"size":0}`)
case "/wiki/rest/api/user/current":
fmt.Fprint(w, `{"accountId":"a1","displayName":"Ada"}`)
default:
w.WriteHeader(http.StatusNotFound)
}
}, atlassian.Cloud)
if err := c.Ping(context.Background()); err != nil {
t.Fatal(err)
}
u, err := c.CurrentUser(context.Background())
if err != nil || u.DisplayName != "Ada" {
t.Fatalf("user = %+v, %v", u, err)
}
}
+94
View File
@@ -0,0 +1,94 @@
package confluence
// Content is a page, blog post or comment.
type Content struct {
ID string `json:"id"`
Type string `json:"type"`
Status string `json:"status"`
Title string `json:"title"`
Space *SpaceRef `json:"space"`
Version *Version `json:"version"`
Body *Body `json:"body"`
Ancestors []ContentRef `json:"ancestors"`
Links *Links `json:"_links"`
}
// ContentRef is a minimal content reference (ancestors, children, home
// page).
type ContentRef struct {
ID string `json:"id"`
Title string `json:"title,omitempty"`
}
// SpaceRef identifies a space inside content.
type SpaceRef struct {
ID int `json:"id,omitempty"`
Key string `json:"key"`
Name string `json:"name,omitempty"`
}
// Version is a content version.
type Version struct {
Number int `json:"number"`
When string `json:"when"`
By *User `json:"by"`
}
// Body holds the storage-format body when expanded.
type Body struct {
Storage *BodyRepresentation `json:"storage"`
}
// BodyRepresentation is one body format ("storage", "plain", ...).
type BodyRepresentation struct {
Value string `json:"value"`
Representation string `json:"representation"`
}
// Links are the _links of a content object.
type Links struct {
WebUI string `json:"webui"`
Base string `json:"base"`
}
// User is a Confluence account: AccountID on Cloud, Username on
// Server/Data Center.
type User struct {
AccountID string `json:"accountId"`
Username string `json:"username"`
DisplayName string `json:"displayName"`
Email string `json:"email"`
AccountEmail string `json:"accountEmail,omitempty"`
}
// ContentList is one page of content.
type ContentList struct {
Results []Content `json:"results"`
Start int `json:"start"`
Limit int `json:"limit"`
Size int `json:"size"`
}
// Space is a Confluence space.
type Space struct {
ID int `json:"id"`
Key string `json:"key"`
Name string `json:"name"`
Type string `json:"type"`
Status string `json:"status"`
Description *SpaceDescription `json:"description"`
Homepage *ContentRef `json:"homepage"`
}
// SpaceDescription holds the expanded plain description.
type SpaceDescription struct {
Plain *BodyRepresentation `json:"plain"`
}
// SpaceList is one page of spaces.
type SpaceList struct {
Results []Space `json:"results"`
Start int `json:"start"`
Limit int `json:"limit"`
Size int `json:"size"`
}
+148
View File
@@ -0,0 +1,148 @@
package confluence
import (
"context"
"fmt"
"html"
"net/http"
"net/url"
"strings"
)
// StorageFromText turns plain text into a minimal storage-format body:
// each blank-line-separated paragraph becomes an HTML-escaped <p>. It
// never passes markup through, so text from an untrusted source cannot
// inject active content into a page.
func StorageFromText(text string) string {
var b strings.Builder
for _, p := range strings.Split(strings.TrimSpace(text), "\n\n") {
p = strings.TrimSpace(p)
if p == "" {
continue
}
b.WriteString("<p>")
b.WriteString(html.EscapeString(p))
b.WriteString("</p>")
}
return b.String()
}
type storageBody struct {
Storage BodyRepresentation `json:"storage"`
}
func storage(text string) storageBody {
return storageBody{Storage: BodyRepresentation{Value: StorageFromText(text), Representation: "storage"}}
}
// CreatePageInput describes a new page; Content is plain text (see
// StorageFromText).
type CreatePageInput struct {
SpaceKey string
Title string
Content string
ParentPageID string
}
// CreatePage creates a page and returns its ID.
func (c *Client) CreatePage(ctx context.Context, in CreatePageInput) (string, error) {
body := map[string]any{
"type": "page",
"title": in.Title,
"space": SpaceRef{Key: in.SpaceKey},
"body": storage(in.Content),
}
if in.ParentPageID != "" {
body["ancestors"] = []ContentRef{{ID: in.ParentPageID}}
}
var resp Content
if err := c.do(ctx, http.MethodPost, c.api("/content"), nil, body, &resp); err != nil {
return "", err
}
return resp.ID, nil
}
// VersionConflictError is returned by UpdatePage when the page changed
// since the caller read it.
type VersionConflictError struct {
PageID string
Current int
Expected int
}
func (e *VersionConflictError) Error() string {
return fmt.Sprintf("page %s has changed since it was last read (current version %d, expected %d); re-read the page and retry",
e.PageID, e.Current, e.Expected)
}
// UpdatePageInput describes an update; Content is plain text.
type UpdatePageInput struct {
ID string
Title string // empty keeps the current title
Content string
ExpectedVersion int // the version the caller last read
NewParentID string // empty keeps the parent
}
// UpdatePage replaces a page's body, never blindly: it re-reads the page
// and returns a *VersionConflictError without writing anything when its
// current version is not ExpectedVersion.
func (c *Client) UpdatePage(ctx context.Context, in UpdatePageInput) error {
current, err := c.Page(ctx, in.ID)
if err != nil {
return err
}
if current.Version == nil {
return fmt.Errorf("page %s has no version information", in.ID)
}
if current.Version.Number != in.ExpectedVersion {
return &VersionConflictError{PageID: in.ID, Current: current.Version.Number, Expected: in.ExpectedVersion}
}
title := in.Title
if title == "" {
title = current.Title
}
spaceKey := ""
if current.Space != nil {
spaceKey = current.Space.Key
}
body := map[string]any{
"id": in.ID,
"type": "page",
"title": title,
"space": SpaceRef{Key: spaceKey},
"body": storage(in.Content),
"version": map[string]int{"number": current.Version.Number + 1},
}
if in.NewParentID != "" {
body["ancestors"] = []ContentRef{{ID: in.NewParentID}}
}
return c.do(ctx, http.MethodPut, c.api("/content/"+url.PathEscape(in.ID)), nil, body, nil)
}
// AddComment adds a plain-text footer comment to a page and returns its
// ID.
func (c *Client) AddComment(ctx context.Context, pageID, text string) (string, error) {
if err := requireID("page id", pageID); err != nil {
return "", err
}
body := map[string]any{
"type": "comment",
"container": map[string]string{"id": pageID, "type": "page"},
"body": storage(text),
}
var resp Content
if err := c.do(ctx, http.MethodPost, c.api("/content"), nil, body, &resp); err != nil {
return "", err
}
return resp.ID, nil
}
// AddLabel adds a global label to a page.
func (c *Client) AddLabel(ctx context.Context, pageID, label string) error {
if err := requireID("page id", pageID); err != nil {
return err
}
body := []map[string]string{{"prefix": "global", "name": label}}
return c.do(ctx, http.MethodPost, c.api("/content/"+url.PathEscape(pageID)+"/label"), nil, body, nil)
}