diff --git a/apps/backend/internal/jira/cloud_client.go b/apps/backend/internal/jira/cloud_client.go index f568749447..8ba7f67464 100644 --- a/apps/backend/internal/jira/cloud_client.go +++ b/apps/backend/internal/jira/cloud_client.go @@ -15,33 +15,59 @@ import ( "time" ) -// CloudClient is an Atlassian Cloud REST v3 client. It supports two auth modes: +// CloudClient is a Jira REST client. Despite the name, it supports both +// Atlassian Cloud and self-hosted Server / Data Center instances: // -// - api_token: Basic auth with {email}:{token} (the standard, recommended path). -// - session_cookie: the secret is the JWT value of `cloud.session.token` -// (password accounts) or `tenant.session.token` (SSO), copied from DevTools -// → Application → Cookies. The client wraps it under both cookie names so -// a single paste works for both account types. +// - Cloud uses REST v3 (`/rest/api/3/...`) and the token-paginated +// `/search/jql` endpoint. +// - Server/DC exposes only REST v2 (`/rest/api/2/...`) and the legacy +// `startAt`-paginated `/search`. +// +// Auth modes: +// +// - api_token (Cloud-only): Basic auth with {email}:{token} minted at +// id.atlassian.com. +// - pat (Server-only): Personal Access Token sent as `Authorization: Bearer`. +// - session_cookie (Cloud-only): the secret is the JWT value of +// `cloud.session.token` (password accounts) or `tenant.session.token` +// (SSO), copied from DevTools → Application → Cookies. +// buildSessionCookieHeader emits those two Atlassian-specific cookie +// names, and validateAuthInstance rejects the combo on Server/DC where +// the equivalent cookie is JSESSIONID — Server/DC users authenticate +// via PAT until a Server-aware session-cookie path is added. // // The client holds no state beyond credentials so it can be recreated cheaply -// per workspace if config changes. +// when config changes. type CloudClient struct { - http *http.Client - siteURL string - email string - secret string - authMethod string - maxBodySize int64 + http *http.Client + siteURL string + email string + secret string + authMethod string + instanceType string + apiBase string // "/rest/api/3" for cloud, "/rest/api/2" for server. + maxBodySize int64 } // NewCloudClient builds a client from a JiraConfig + secret. siteURL is // normalized: trailing slash stripped, https:// prepended when the user saved -// only a hostname (legacy rows; new rows are normalized on save). +// only a hostname (legacy rows; new rows are normalized on save). An empty +// InstanceType is treated as cloud — that's how every config row written by +// pre-Server-support releases looks, and we can't pick differently without +// breaking those installs. func NewCloudClient(cfg *JiraConfig, secret string) *CloudClient { site := strings.TrimRight(cfg.SiteURL, "/") if site != "" && !strings.Contains(site, "://") { site = "https://" + site } + instance := cfg.InstanceType + if instance == "" { + instance = InstanceTypeCloud + } + apiBase := "/rest/api/3" + if instance == InstanceTypeServer { + apiBase = "/rest/api/2" + } return &CloudClient{ http: &http.Client{ Timeout: 30 * time.Second, @@ -55,11 +81,13 @@ func NewCloudClient(cfg *JiraConfig, secret string) *CloudClient { return http.ErrUseLastResponse }, }, - siteURL: site, - email: cfg.Email, - secret: secret, - authMethod: cfg.AuthMethod, - maxBodySize: 4 << 20, // 4 MB — Jira payloads are small by design. + siteURL: site, + email: cfg.Email, + secret: secret, + authMethod: cfg.AuthMethod, + instanceType: instance, + apiBase: apiBase, + maxBodySize: 4 << 20, // 4 MB — Jira payloads are small by design. } } @@ -73,6 +101,8 @@ func (c *CloudClient) authorize(req *http.Request) { case AuthMethodAPIToken: basic := base64.StdEncoding.EncodeToString([]byte(c.email + ":" + c.secret)) req.Header.Set("Authorization", "Basic "+basic) + case AuthMethodPAT: + req.Header.Set("Authorization", "Bearer "+c.secret) case AuthMethodSessionCookie: req.Header.Set("Cookie", buildSessionCookieHeader(c.secret)) } @@ -115,13 +145,13 @@ func (c *CloudClient) do(ctx context.Context, method, path string, body interfac return err } if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return &APIError{StatusCode: resp.StatusCode, Message: summarizeBody(resp, raw)} + return &APIError{StatusCode: resp.StatusCode, Message: c.summarizeBody(resp, raw, false)} } // Guardrail: some misconfigured Atlassian flows return a 200 HTML login // page instead of JSON. If we accidentally get HTML, surface an auth error // rather than letting json.Unmarshal fail with "invalid character '<'". if isHTMLResponse(resp, raw) { - return &APIError{StatusCode: resp.StatusCode, Message: "Atlassian returned an HTML page — the session likely requires step-up auth or has expired. Refresh your Jira tab and copy the cookie again."} + return &APIError{StatusCode: resp.StatusCode, Message: c.summarizeBody(resp, raw, true)} } if out == nil || len(raw) == 0 { return nil @@ -141,14 +171,21 @@ func isHTMLResponse(resp *http.Response, raw []byte) bool { return bytes.HasPrefix(trimmed, []byte("<")) } -// summarizeBody returns a short, useful error message from a non-2xx response. -// For HTML bodies it skips the page content in favor of a step-up hint; for -// plain text or JSON it returns the body verbatim (capped, so we don't spam -// logs with multi-KB pages). -func summarizeBody(resp *http.Response, raw []byte) string { - if isHTMLResponse(resp, raw) { - return "Atlassian returned an HTML page (status " + strconv.Itoa(resp.StatusCode) + - "). This usually means step-up authentication is required; sign in again in your Jira tab and re-copy the cookie." +// summarizeBody returns a short, useful error message from a Jira response. +// For HTML bodies it skips the page content in favor of an auth-method-aware +// hint; for plain text or JSON it returns the body verbatim (capped, so we +// don't spam logs with multi-KB pages). htmlOn2xx flags the "successful status +// but HTML body" case — that means the response went through an auth-filter +// login page instead of the REST API, so the hint adds "instead of JSON" to +// distinguish it from the more common error-status HTML case. +func (c *CloudClient) summarizeBody(resp *http.Response, raw []byte, htmlOn2xx bool) string { + if htmlOn2xx || isHTMLResponse(resp, raw) { + suffix := ". " + if htmlOn2xx { + suffix = " instead of JSON. " + } + return "Jira returned an HTML page (status " + strconv.Itoa(resp.StatusCode) + + ")" + suffix + c.authHint() } const maxMsg = 500 if len(raw) > maxMsg { @@ -157,6 +194,30 @@ func summarizeBody(resp *http.Response, raw []byte) string { return string(raw) } +// authHint picks an actionable explanation for an HTML-from-API response, +// based on auth method and instance type. The wording differs because the +// failure mode is different in each combo: a Cloud API token rejection looks +// the same on the wire as a Server PAT rejection, but the user's next step +// (check id.atlassian.com vs. check the instance's PAT page) is different. +func (c *CloudClient) authHint() string { + switch c.authMethod { + case AuthMethodAPIToken: + if c.instanceType == InstanceTypeServer { + // Mismatched config: API-token auth is Cloud-only. Server/DC will + // reject `Basic email:token` and redirect to /login.jsp, which the + // JSON decoder sees as HTML. + return "API token auth is Cloud-only — this site looks like Jira Server/DC. Switch the auth method to PAT (Personal Access Token)." + } + return "Check the email and API token; create a new one at id.atlassian.com/manage-profile/security/api-tokens if needed." + case AuthMethodPAT: + return "The Personal Access Token is rejected. Recreate it from your Jira profile → Personal Access Tokens and update the saved value." + case AuthMethodSessionCookie: + return "The session cookie likely expired or requires step-up auth. Sign in again in your Jira tab and re-copy the cookie." + default: + return "Check the saved credentials." + } +} + // TestAuth hits /rest/api/3/myself which is the cheapest authenticated // endpoint; a 200 proves credentials work and identifies the user. func (c *CloudClient) TestAuth(ctx context.Context) (*TestConnectionResult, error) { @@ -165,7 +226,7 @@ func (c *CloudClient) TestAuth(ctx context.Context) (*TestConnectionResult, erro DisplayName string `json:"displayName"` EmailAddress string `json:"emailAddress"` } - if err := c.do(ctx, http.MethodGet, "/rest/api/3/myself", nil, &body); err != nil { + if err := c.do(ctx, http.MethodGet, c.apiBase+"/myself", nil, &body); err != nil { var apiErr *APIError if errors.As(err, &apiErr) { return &TestConnectionResult{OK: false, Error: apiErr.Error()}, nil @@ -253,7 +314,7 @@ type transitionsResponse struct { // ticket with an empty transitions menu. func (c *CloudClient) GetTicket(ctx context.Context, ticketKey string) (*JiraTicket, error) { var issue issueResponse - path := "/rest/api/3/issue/" + url.PathEscape(ticketKey) + "?expand=renderedFields" + path := c.apiBase + "/issue/" + url.PathEscape(ticketKey) + "?expand=renderedFields" if err := c.do(ctx, http.MethodGet, path, nil, &issue); err != nil { return nil, err } @@ -275,7 +336,7 @@ func (c *CloudClient) GetTicket(ctx context.Context, ticketKey string) (*JiraTic // ListTransitions returns the transitions currently available for ticketKey. func (c *CloudClient) ListTransitions(ctx context.Context, ticketKey string) ([]JiraTransition, error) { var resp transitionsResponse - path := "/rest/api/3/issue/" + url.PathEscape(ticketKey) + "/transitions" + path := c.apiBase + "/issue/" + url.PathEscape(ticketKey) + "/transitions" if err := c.do(ctx, http.MethodGet, path, nil, &resp); err != nil { return nil, err } @@ -297,7 +358,7 @@ func (c *CloudClient) DoTransition(ctx context.Context, ticketKey, transitionID body := map[string]interface{}{ "transition": map[string]string{"id": transitionID}, } - path := "/rest/api/3/issue/" + url.PathEscape(ticketKey) + "/transitions" + path := c.apiBase + "/issue/" + url.PathEscape(ticketKey) + "/transitions" return c.do(ctx, http.MethodPost, path, body, nil) } @@ -312,7 +373,11 @@ func (c *CloudClient) ListProjects(ctx context.Context) ([]JiraProject, error) { Name string `json:"name"` } `json:"values"` } - if err := c.do(ctx, http.MethodGet, "/rest/api/3/project/search?maxResults=200", nil, &body); err != nil { + // Server/DC exposes /project/search starting with Jira 8.0 (2019). For + // older instances the call returns 404, which surfaces as an API error the + // user can read. The legacy GET /project endpoint isn't paginated and we + // don't need to keep two code paths just for ancient deployments. + if err := c.do(ctx, http.MethodGet, c.apiBase+"/project/search?maxResults=200", nil, &body); err != nil { return nil, err } out := make([]JiraProject, 0, len(body.Values)) @@ -322,20 +387,47 @@ func (c *CloudClient) ListProjects(ctx context.Context) ([]JiraProject, error) { return out, nil } -// searchResponse mirrors the subset of /rest/api/3/search/jql we consume. The -// new endpoint is token-paginated: there's no total count and pagination uses -// nextPageToken rather than startAt. Transitions are intentionally omitted from -// search results (fetched lazily when the user opens a ticket). -type searchResponse struct { +// cloudSearchResponse mirrors the subset of /rest/api/3/search/jql we consume. +// The token-paginated endpoint exposes no total count; pagination is driven by +// `nextPageToken`. Transitions are intentionally omitted from search results +// (fetched lazily when the user opens a ticket). +type cloudSearchResponse struct { Issues []issueResponse `json:"issues"` NextPageToken string `json:"nextPageToken"` IsLast bool `json:"isLast"` } -// SearchTickets runs a JQL search and returns a page of tickets. Uses the -// /rest/api/3/search/jql endpoint (the legacy /search was removed by Atlassian -// in 2025). pageToken is the cursor returned in the previous page's -// NextPageToken; pass "" for the first page. maxResults is capped at 100. +// serverSearchResponse mirrors the legacy `startAt`-paginated `/search` +// endpoint that Jira Server / Data Center exposes. We synthesize a string +// page token from `startAt + maxResults` so the public SearchResult shape stays +// identical regardless of upstream pagination style. +type serverSearchResponse struct { + Issues []issueResponse `json:"issues"` + StartAt int `json:"startAt"` + MaxResults int `json:"maxResults"` + Total int `json:"total"` +} + +// searchFields is the list of issue fields we ask Jira to return. Kept short +// because tickets are listed in dense table rows; the rest is fetched lazily +// on click. +var searchFields = []string{ + "summary", "status", "project", "issuetype", + "priority", "assignee", "reporter", "updated", +} + +// SearchTickets runs a JQL search and returns a page of tickets. The transport +// branches on instance type because Cloud and Server/DC expose different +// search endpoints with incompatible pagination shapes: +// +// - Cloud: POST /rest/api/3/search/jql — token-paginated, no total count. +// The legacy /search was removed by Atlassian in 2025. +// - Server/DC: POST /rest/api/2/search — startAt/total style; we encode the +// next startAt offset into the SearchResult.NextPageToken string so the +// caller can opaquely round-trip it. +// +// pageToken is the cursor returned in the previous page's NextPageToken; +// pass "" for the first page. maxResults is capped at 100. func (c *CloudClient) SearchTickets(ctx context.Context, jql, pageToken string, maxResults int) (*SearchResult, error) { if maxResults <= 0 { maxResults = 25 @@ -343,19 +435,23 @@ func (c *CloudClient) SearchTickets(ctx context.Context, jql, pageToken string, if maxResults > 100 { maxResults = 100 } + if c.instanceType == InstanceTypeServer { + return c.searchTicketsServer(ctx, jql, pageToken, maxResults) + } + return c.searchTicketsCloud(ctx, jql, pageToken, maxResults) +} + +func (c *CloudClient) searchTicketsCloud(ctx context.Context, jql, pageToken string, maxResults int) (*SearchResult, error) { body := map[string]interface{}{ "jql": jql, "maxResults": maxResults, - "fields": []string{ - "summary", "status", "project", "issuetype", - "priority", "assignee", "reporter", "updated", - }, + "fields": searchFields, } if pageToken != "" { body["nextPageToken"] = pageToken } - var resp searchResponse - if err := c.do(ctx, http.MethodPost, "/rest/api/3/search/jql", body, &resp); err != nil { + var resp cloudSearchResponse + if err := c.do(ctx, http.MethodPost, c.apiBase+"/search/jql", body, &resp); err != nil { return nil, err } out := &SearchResult{ @@ -370,6 +466,43 @@ func (c *CloudClient) SearchTickets(ctx context.Context, jql, pageToken string, return out, nil } +func (c *CloudClient) searchTicketsServer(ctx context.Context, jql, pageToken string, maxResults int) (*SearchResult, error) { + startAt := 0 + if pageToken != "" { + // A malformed token is fixed by starting over from the first page — + // safer than 500-ing on what is ultimately UI-driven state. + if n, err := strconv.Atoi(pageToken); err == nil && n > 0 { + startAt = n + } + } + body := map[string]interface{}{ + "jql": jql, + "startAt": startAt, + "maxResults": maxResults, + "fields": searchFields, + } + var resp serverSearchResponse + if err := c.do(ctx, http.MethodPost, c.apiBase+"/search", body, &resp); err != nil { + return nil, err + } + nextStart := resp.StartAt + len(resp.Issues) + isLast := nextStart >= resp.Total || len(resp.Issues) == 0 + nextToken := "" + if !isLast { + nextToken = strconv.Itoa(nextStart) + } + out := &SearchResult{ + MaxResults: maxResults, + IsLast: isLast, + NextPageToken: nextToken, + Tickets: make([]JiraTicket, 0, len(resp.Issues)), + } + for i := range resp.Issues { + out.Tickets = append(out.Tickets, issueToTicket(&resp.Issues[i], c.siteURL)) + } + return out, nil +} + // issueToTicket converts the API response shape to our public JiraTicket. // Factored out so GetTicket and SearchTickets stay consistent. func issueToTicket(issue *issueResponse, siteURL string) JiraTicket { diff --git a/apps/backend/internal/jira/cloud_client_test.go b/apps/backend/internal/jira/cloud_client_test.go index 241c5c679c..177a9b82c3 100644 --- a/apps/backend/internal/jira/cloud_client_test.go +++ b/apps/backend/internal/jira/cloud_client_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "errors" + "io" "net/http" "net/http/httptest" "strings" @@ -188,9 +189,11 @@ func TestCloudClient_DoTransition_PostsBody(t *testing.T) { ts := newMockServer(t, func(w http.ResponseWriter, r *http.Request) { gotMethod = r.Method gotPath = r.URL.Path - buf := make([]byte, r.ContentLength) - _, _ = r.Body.Read(buf) - gotBody = string(buf) + // io.ReadAll over a sized r.Body.Read: chunked transfer encoding + // sets ContentLength=-1 (panicking on make), and a single Read may + // return partial bytes even when the length is known. + raw, _ := io.ReadAll(r.Body) + gotBody = string(raw) w.WriteHeader(http.StatusNoContent) }) c := clientTo(ts, AuthMethodAPIToken, "t") @@ -240,6 +243,218 @@ func TestCloudClient_SiteURLTrailingSlash_Stripped(t *testing.T) { } } +// --- Server / Data Center mode --- + +// serverClient builds a CloudClient configured for a self-hosted Server/DC +// instance against the test server. +func serverClient(ts *httptest.Server, method, secret string) *CloudClient { + cfg := &JiraConfig{ + SiteURL: ts.URL, + Email: "user@example.com", + AuthMethod: method, + InstanceType: InstanceTypeServer, + } + return NewCloudClient(cfg, secret) +} + +func TestCloudClient_ServerMode_UsesV2Paths(t *testing.T) { + var gotPath string + ts := newMockServer(t, func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"accountId":"a"}`)) + }) + c := serverClient(ts, AuthMethodPAT, "pat-token") + if _, err := c.TestAuth(context.Background()); err != nil { + t.Fatalf("test auth: %v", err) + } + if gotPath != "/rest/api/2/myself" { + t.Errorf("path: got %q, want /rest/api/2/myself", gotPath) + } +} + +func TestCloudClient_PAT_SendsBearer(t *testing.T) { + var gotAuth string + ts := newMockServer(t, func(w http.ResponseWriter, r *http.Request) { + gotAuth = r.Header.Get("Authorization") + _, _ = w.Write([]byte(`{}`)) + }) + c := serverClient(ts, AuthMethodPAT, "pat-token-value") + if _, err := c.TestAuth(context.Background()); err != nil { + t.Fatalf("test auth: %v", err) + } + if gotAuth != "Bearer pat-token-value" { + t.Errorf("auth header = %q, want Bearer pat-token-value", gotAuth) + } +} + +func TestCloudClient_ServerMode_SearchTickets_StartAtPagination(t *testing.T) { + var gotPath string + var gotBody string + ts := newMockServer(t, func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + raw, _ := io.ReadAll(r.Body) + gotBody = string(raw) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{ + "startAt": 50, + "maxResults": 50, + "total": 120, + "issues": [ + {"key":"P-51","fields":{"summary":"a","status":{},"project":{},"issuetype":{}}}, + {"key":"P-52","fields":{"summary":"b","status":{},"project":{},"issuetype":{}}} + ] + }`)) + }) + c := serverClient(ts, AuthMethodPAT, "tok") + res, err := c.SearchTickets(context.Background(), "project = P", "50", 50) + if err != nil { + t.Fatalf("search: %v", err) + } + if gotPath != "/rest/api/2/search" { + t.Errorf("path: got %q, want /rest/api/2/search", gotPath) + } + if !strings.Contains(gotBody, `"startAt":50`) { + t.Errorf("body missing startAt=50: %q", gotBody) + } + if res.IsLast { + t.Error("expected IsLast=false (52 of 120)") + } + if res.NextPageToken != "52" { + t.Errorf("next page token = %q, want 52", res.NextPageToken) + } + if len(res.Tickets) != 2 || res.Tickets[0].Key != "P-51" { + t.Errorf("tickets: %+v", res.Tickets) + } +} + +// Jira Server can return fewer issues than maxResults on a non-terminal page +// (rate limits, filtered results). The pager must still advance — IsLast is +// driven by total, not by len(issues) < maxResults. +func TestCloudClient_ServerMode_SearchTickets_PartialBatchAdvances(t *testing.T) { + ts := newMockServer(t, func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{ + "startAt": 100, + "maxResults": 50, + "total": 110, + "issues": [ + {"key":"P-101","fields":{"summary":"x","status":{},"project":{},"issuetype":{}}} + ] + }`)) + }) + c := serverClient(ts, AuthMethodPAT, "tok") + res, err := c.SearchTickets(context.Background(), "x", "100", 50) + if err != nil { + t.Fatalf("search: %v", err) + } + if res.IsLast { + t.Error("expected IsLast=false: startAt+len=101 < total=110") + } + if res.NextPageToken != "101" { + t.Errorf("next page token = %q, want 101", res.NextPageToken) + } +} + +func TestCloudClient_ServerMode_SearchTickets_TerminalPage(t *testing.T) { + ts := newMockServer(t, func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`{ + "startAt": 100, + "maxResults": 50, + "total": 102, + "issues": [ + {"key":"P-101","fields":{"summary":"x","status":{},"project":{},"issuetype":{}}}, + {"key":"P-102","fields":{"summary":"y","status":{},"project":{},"issuetype":{}}} + ] + }`)) + }) + c := serverClient(ts, AuthMethodPAT, "tok") + res, err := c.SearchTickets(context.Background(), "x", "100", 50) + if err != nil { + t.Fatalf("search: %v", err) + } + if !res.IsLast { + t.Error("expected IsLast=true on terminal page") + } + if res.NextPageToken != "" { + t.Errorf("expected empty NextPageToken on terminal page, got %q", res.NextPageToken) + } +} + +func TestCloudClient_ServerMode_GetTicket_UsesV2(t *testing.T) { + var paths []string + ts := newMockServer(t, func(w http.ResponseWriter, r *http.Request) { + paths = append(paths, r.URL.Path) + w.Header().Set("Content-Type", "application/json") + switch { + case strings.HasSuffix(r.URL.Path, "/transitions"): + _, _ = w.Write([]byte(`{"transitions":[]}`)) + default: + _, _ = w.Write([]byte(`{"key":"P-1","fields":{"summary":"s","description":"plain text","status":{},"project":{},"issuetype":{}}}`)) + } + }) + c := serverClient(ts, AuthMethodPAT, "tok") + ticket, err := c.GetTicket(context.Background(), "P-1") + if err != nil { + t.Fatalf("get: %v", err) + } + if ticket.Description != "plain text" { + t.Errorf("description: %q", ticket.Description) + } + wantPrefix := "/rest/api/2/issue/P-1" + for _, p := range paths { + if !strings.HasPrefix(p, wantPrefix) { + t.Errorf("path %q does not use v2 base", p) + } + } +} + +func TestCloudClient_ServerMode_HtmlAuthHint_MentionsPAT(t *testing.T) { + ts := newMockServer(t, func(w http.ResponseWriter, _ *http.Request) { + // Set headers before WriteHeader — once WriteHeader fires the response + // headers are committed and any later Header().Set is silently dropped. + w.Header().Set("Content-Type", "text/html") + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`
`)) + }) + c := serverClient(ts, AuthMethodPAT, "bad") + res, err := c.TestAuth(context.Background()) + if err != nil { + t.Fatalf("test auth: %v", err) + } + if res.OK { + t.Fatal("expected OK=false") + } + if !strings.Contains(res.Error, "Personal Access Token") { + t.Errorf("expected PAT hint, got %q", res.Error) + } +} + +func TestCloudClient_CloudMode_APITokenOnServer_HintFlagsMismatch(t *testing.T) { + ts := newMockServer(t, func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/html") + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`login`)) + }) + // Force the misconfiguration: instance=server but auth=api_token (which is + // what existing users saw before this change). The hint should call out + // the mismatch and direct them to switch to PAT. + cfg := &JiraConfig{ + SiteURL: ts.URL, + Email: "u@x", + AuthMethod: AuthMethodAPIToken, + InstanceType: InstanceTypeServer, + } + c := NewCloudClient(cfg, "tok") + res, _ := c.TestAuth(context.Background()) + if res.OK { + t.Fatal("expected OK=false") + } + if !strings.Contains(res.Error, "Cloud-only") || !strings.Contains(res.Error, "PAT") { + t.Errorf("hint should explain mismatch + suggest PAT, got %q", res.Error) + } +} + func TestExtractDescription_Nil(t *testing.T) { if got := extractDescription(nil); got != "" { t.Errorf("nil → %q", got) diff --git a/apps/backend/internal/jira/models.go b/apps/backend/internal/jira/models.go index 87cca025ee..88b1a1a53d 100644 --- a/apps/backend/internal/jira/models.go +++ b/apps/backend/internal/jira/models.go @@ -8,17 +8,36 @@ import "time" // Auth method identifiers persisted in JiraConfig.AuthMethod. const ( - AuthMethodAPIToken = "api_token" + // AuthMethodAPIToken is Atlassian Cloud's Basic auth with email + API token + // minted at id.atlassian.com. Cloud-only — Server/DC instances reject it. + AuthMethodAPIToken = "api_token" + // AuthMethodSessionCookie wraps a JWT session cookie copied from DevTools. + // Works against both Cloud and Server/DC since the cookie is the same shape. AuthMethodSessionCookie = "session_cookie" + // AuthMethodPAT is Server/DC's Personal Access Token, sent as Bearer. + // Created from the user's profile on the Jira instance. Server/DC-only — + // Cloud doesn't accept Bearer for the Jira REST API. + AuthMethodPAT = "pat" +) + +// Instance type identifiers persisted in JiraConfig.InstanceType. Cloud sites +// (acme.atlassian.net) expose REST v3 and the token-paginated `/search/jql`; +// Server / Data Center (self-hosted) instances expose only REST v2 and the +// legacy `startAt`-paginated `/search`. The client branches on this field to +// pick the right endpoints — there is no autodetect. +const ( + InstanceTypeCloud = "cloud" + InstanceTypeServer = "server" ) // JiraConfig is the install-wide configuration for the Jira integration. The -// secret value (API token or session cookie) is stored separately in the +// secret value (API token, PAT, or session cookie) is stored separately in the // encrypted secret store under SecretKey. type JiraConfig struct { SiteURL string `json:"siteUrl" db:"site_url"` Email string `json:"email" db:"email"` AuthMethod string `json:"authMethod" db:"auth_method"` + InstanceType string `json:"instanceType" db:"instance_type"` DefaultProjectKey string `json:"defaultProjectKey" db:"default_project_key"` HasSecret bool `json:"hasSecret" db:"-"` // SecretExpiresAt is populated for session_cookie auth when the cookie is @@ -42,6 +61,7 @@ type SetConfigRequest struct { SiteURL string `json:"siteUrl"` Email string `json:"email"` AuthMethod string `json:"authMethod"` + InstanceType string `json:"instanceType"` DefaultProjectKey string `json:"defaultProjectKey"` Secret string `json:"secret"` } diff --git a/apps/backend/internal/jira/service.go b/apps/backend/internal/jira/service.go index 87b4fca146..3267db9f5c 100644 --- a/apps/backend/internal/jira/service.go +++ b/apps/backend/internal/jira/service.go @@ -114,6 +114,7 @@ func (s *Service) SetConfig(ctx context.Context, req *SetConfigRequest) (*JiraCo SiteURL: normalizeSiteURL(req.SiteURL), Email: req.Email, AuthMethod: req.AuthMethod, + InstanceType: req.InstanceType, DefaultProjectKey: req.DefaultProjectKey, } if err := s.store.UpsertConfig(ctx, cfg); err != nil { @@ -333,56 +334,135 @@ func (s *Service) invalidateClient() { // (post-save re-test). func (s *Service) resolveCredentials(ctx context.Context, req *SetConfigRequest) (*JiraConfig, string, error) { cfg := &JiraConfig{ - SiteURL: normalizeSiteURL(req.SiteURL), - Email: req.Email, - AuthMethod: req.AuthMethod, + SiteURL: normalizeSiteURL(req.SiteURL), + Email: req.Email, + AuthMethod: req.AuthMethod, + InstanceType: req.InstanceType, } + var secret string if req.Secret != "" { - return cfg, req.Secret, nil - } - if s.secrets == nil { - return nil, "", errors.New("no secret store configured") - } - secret, err := s.secrets.Reveal(ctx, SecretKey) - if err != nil { - // Don't conflate a transient secret-store failure with "no token - // stored". Surfacing the real error gives the user a path to retry - // instead of telling them to paste a token they already have. - s.log.Warn("jira: secret reveal failed", zap.Error(err)) - return nil, "", fmt.Errorf("read jira secret: %w", err) - } - if secret == "" { - return nil, "", errors.New("no token stored — paste one to test") - } - // Merge with persisted config so the test uses saved site/email if the - // caller only passed a partial request. - if stored, _ := s.store.GetConfig(ctx); stored != nil { - if cfg.SiteURL == "" { - cfg.SiteURL = stored.SiteURL + secret = req.Secret + } else { + if s.secrets == nil { + return nil, "", errors.New("no secret store configured") } - if cfg.Email == "" { - cfg.Email = stored.Email + var err error + secret, err = s.secrets.Reveal(ctx, SecretKey) + if err != nil { + // Don't conflate a transient secret-store failure with "no token + // stored". Surfacing the real error gives the user a path to retry + // instead of telling them to paste a token they already have. + s.log.Warn("jira: secret reveal failed", zap.Error(err)) + return nil, "", fmt.Errorf("read jira secret: %w", err) } - if cfg.AuthMethod == "" { - cfg.AuthMethod = stored.AuthMethod + if secret == "" { + return nil, "", errors.New("no token stored — paste one to test") } } + // Merge with persisted config only when the caller didn't pass enough on + // its own. A fully-specified pre-save TestConnection request needs no DB + // read — keeping the call gated avoids a transient DB error blocking auth + // testing for a request that doesn't depend on persisted state. When a + // read does happen, surface its error so a real DB failure isn't masked + // as an opaque "missing field" validation message later on. + needsStoredConfig := cfg.SiteURL == "" || + cfg.AuthMethod == "" || + cfg.InstanceType == "" || + (cfg.AuthMethod == AuthMethodAPIToken && cfg.Email == "") + if needsStoredConfig { + if err := s.fillConfigFromStored(ctx, cfg); err != nil { + return nil, "", err + } + } + if cfg.InstanceType == "" { + cfg.InstanceType = InstanceTypeCloud + } + // Run the same auth/instance check the save path runs, so TestConnection + // reports invalid combos (e.g. pat+cloud, api_token+server) with a clear + // validation error instead of letting Jira return an opaque 401. + if err := validateAuthInstance(cfg.AuthMethod, cfg.InstanceType, cfg.Email); err != nil { + return nil, "", err + } return cfg, secret, nil } +// fillConfigFromStored reads the persisted singleton config and copies any +// fields the caller left blank onto cfg. A real read failure is returned so +// callers don't mask DB errors as opaque "missing field" validation errors; +// a missing row (stored == nil) is treated as "nothing to fill" rather than +// an error so first-time TestConnection requests still go through. +func (s *Service) fillConfigFromStored(ctx context.Context, cfg *JiraConfig) error { + stored, err := s.store.GetConfig(ctx) + if err != nil { + return fmt.Errorf("read jira config: %w", err) + } + if stored == nil { + return nil + } + if cfg.SiteURL == "" { + cfg.SiteURL = stored.SiteURL + } + if cfg.Email == "" { + cfg.Email = stored.Email + } + if cfg.AuthMethod == "" { + cfg.AuthMethod = stored.AuthMethod + } + if cfg.InstanceType == "" { + cfg.InstanceType = stored.InstanceType + } + return nil +} + func validateConfigRequest(req *SetConfigRequest) error { if req.SiteURL == "" { return errors.New("siteUrl required") } - switch req.AuthMethod { + // Require an explicit instanceType — defaulting to cloud here would let a + // stale client (one that pre-dates Server/DC support) silently downgrade + // a saved Server config back to Cloud on the next partial save. + switch req.InstanceType { + case InstanceTypeCloud, InstanceTypeServer: + case "": + return errors.New("instanceType required (cloud or server)") + default: + return fmt.Errorf("unknown instance type: %q", req.InstanceType) + } + return validateAuthInstance(req.AuthMethod, req.InstanceType, req.Email) +} + +// validateAuthInstance enforces the supported (auth method, instance type) +// combinations. Shared by config-save and the test-connection flow so a +// pre-save test surfaces the same diagnostic the eventual save would, instead +// of letting Jira return an opaque 401 for an unsupported combo. +func validateAuthInstance(authMethod, instanceType, email string) error { + switch authMethod { case AuthMethodAPIToken: - if req.Email == "" { + // API tokens are Cloud-only — Atlassian Server/DC rejects Basic auth + // with `id.atlassian.com` tokens and redirects to a login page, which + // makes the failure mode opaque. Catch it at config time. + if instanceType != InstanceTypeCloud { + return errors.New("api_token auth is supported only on Atlassian Cloud — use pat for Server/DC") + } + if email == "" { return errors.New("email required for api_token auth") } + case AuthMethodPAT: + // Personal Access Tokens are a Server/DC concept; Cloud expects + // id.atlassian.com tokens via Basic, not Bearer. + if instanceType != InstanceTypeServer { + return errors.New("pat auth is supported only on Jira Server/Data Center — use api_token for Cloud") + } case AuthMethodSessionCookie: - // email is optional for session cookies. + // The client wraps the session secret under cloud.session.token and + // tenant.session.token — both Atlassian-Cloud-specific cookie names. + // Server/DC uses JSESSIONID, so the current wrapping is a no-op there; + // reject the combo until we add a Server-aware session-cookie path. + if instanceType != InstanceTypeCloud { + return errors.New("session_cookie auth is supported only on Atlassian Cloud — use pat for Server/DC") + } default: - return fmt.Errorf("unknown auth method: %q", req.AuthMethod) + return fmt.Errorf("unknown auth method: %q", authMethod) } return nil } diff --git a/apps/backend/internal/jira/service_issue_watch_test.go b/apps/backend/internal/jira/service_issue_watch_test.go index 95f81909fd..4ba69c0ae6 100644 --- a/apps/backend/internal/jira/service_issue_watch_test.go +++ b/apps/backend/internal/jira/service_issue_watch_test.go @@ -149,7 +149,7 @@ func TestService_CheckIssueWatch_FiltersAlreadySeen(t *testing.T) { // Configure JIRA so clientFor succeeds. if _, err := f.svc.SetConfig(ctx, &SetConfigRequest{ SiteURL: "https://a.net", Email: "e", - AuthMethod: AuthMethodAPIToken, Secret: "tok", + AuthMethod: AuthMethodAPIToken, InstanceType: InstanceTypeCloud, Secret: "tok", }); err != nil { t.Fatalf("set config: %v", err) } @@ -199,7 +199,7 @@ func TestService_CheckIssueWatch_StampsLastPolledOnError(t *testing.T) { ctx := context.Background() if _, err := f.svc.SetConfig(ctx, &SetConfigRequest{ SiteURL: "https://a.net", Email: "e", - AuthMethod: AuthMethodAPIToken, Secret: "tok", + AuthMethod: AuthMethodAPIToken, InstanceType: InstanceTypeCloud, Secret: "tok", }); err != nil { t.Fatalf("set config: %v", err) } diff --git a/apps/backend/internal/jira/service_test.go b/apps/backend/internal/jira/service_test.go index dc47394604..f61e59feef 100644 --- a/apps/backend/internal/jira/service_test.go +++ b/apps/backend/internal/jira/service_test.go @@ -134,10 +134,11 @@ func TestService_SetConfig_UpsertsAndStoresSecret(t *testing.T) { ctx := context.Background() cfg, err := f.svc.SetConfig(ctx, &SetConfigRequest{ - SiteURL: "https://acme.atlassian.net/", - Email: "u@example.com", - AuthMethod: AuthMethodAPIToken, - Secret: "tok1", + SiteURL: "https://acme.atlassian.net/", + Email: "u@example.com", + AuthMethod: AuthMethodAPIToken, + InstanceType: InstanceTypeCloud, + Secret: "tok1", }) if err != nil { t.Fatalf("set: %v", err) @@ -160,7 +161,7 @@ func TestService_SetConfig_ProbesAuthImmediately(t *testing.T) { } if _, err := f.svc.SetConfig(context.Background(), &SetConfigRequest{ SiteURL: "https://a.net", Email: "e", - AuthMethod: AuthMethodAPIToken, Secret: "tok", + AuthMethod: AuthMethodAPIToken, InstanceType: InstanceTypeCloud, Secret: "tok", }); err != nil { t.Fatalf("set: %v", err) } @@ -180,7 +181,7 @@ func TestService_SetConfig_PersistsProbeFailure(t *testing.T) { } if _, err := f.svc.SetConfig(context.Background(), &SetConfigRequest{ SiteURL: "https://a.net", Email: "e", - AuthMethod: AuthMethodAPIToken, Secret: "bad", + AuthMethod: AuthMethodAPIToken, InstanceType: InstanceTypeCloud, Secret: "bad", }); err != nil { t.Fatalf("set: %v", err) } @@ -216,14 +217,14 @@ func TestService_SetConfig_EmptySecret_KeepsExisting(t *testing.T) { ctx := context.Background() _, err := f.svc.SetConfig(ctx, &SetConfigRequest{ SiteURL: "https://a.net", Email: "e", - AuthMethod: AuthMethodAPIToken, Secret: "first", + AuthMethod: AuthMethodAPIToken, InstanceType: InstanceTypeCloud, Secret: "first", }) if err != nil { t.Fatalf("initial: %v", err) } _, err = f.svc.SetConfig(ctx, &SetConfigRequest{ SiteURL: "https://a.net", Email: "new@x", - AuthMethod: AuthMethodAPIToken, Secret: "", + AuthMethod: AuthMethodAPIToken, InstanceType: InstanceTypeCloud, Secret: "", }) if err != nil { t.Fatalf("update: %v", err) @@ -238,7 +239,7 @@ func TestService_SetConfig_InvalidatesClientCache(t *testing.T) { ctx := context.Background() _, _ = f.svc.SetConfig(ctx, &SetConfigRequest{ SiteURL: "https://a.net", Email: "e", - AuthMethod: AuthMethodAPIToken, Secret: "t", + AuthMethod: AuthMethodAPIToken, InstanceType: InstanceTypeCloud, Secret: "t", }) // SetConfig spawns an async probe that also builds the client; wait for it // so the rest of the test sees a stable factoryHit count. @@ -259,7 +260,7 @@ func TestService_SetConfig_InvalidatesClientCache(t *testing.T) { // race with the GetTicket assertion. _, _ = f.svc.SetConfig(ctx, &SetConfigRequest{ SiteURL: "https://a.net", Email: "e", - AuthMethod: AuthMethodAPIToken, Secret: "t2", + AuthMethod: AuthMethodAPIToken, InstanceType: InstanceTypeCloud, Secret: "t2", }) waitForAuthProbe(t, f) if _, err := f.svc.GetTicket(ctx, "A-3"); err != nil { @@ -277,9 +278,29 @@ func TestService_Validation(t *testing.T) { name string req SetConfigRequest }{ - {"missing site", SetConfigRequest{AuthMethod: AuthMethodAPIToken, Email: "e"}}, - {"missing email api_token", SetConfigRequest{SiteURL: "x", AuthMethod: AuthMethodAPIToken}}, - {"bad auth", SetConfigRequest{SiteURL: "x", AuthMethod: "bogus"}}, + {"missing site", SetConfigRequest{AuthMethod: AuthMethodAPIToken, Email: "e", InstanceType: InstanceTypeCloud}}, + { + "missing email api_token", + SetConfigRequest{SiteURL: "x", AuthMethod: AuthMethodAPIToken, InstanceType: InstanceTypeCloud}, + }, + {"bad auth", SetConfigRequest{SiteURL: "x", AuthMethod: "bogus", InstanceType: InstanceTypeCloud}}, + {"bad instance", SetConfigRequest{SiteURL: "x", AuthMethod: AuthMethodPAT, InstanceType: "bogus"}}, + { + "missing instanceType rejected", + SetConfigRequest{SiteURL: "x", AuthMethod: AuthMethodAPIToken, Email: "e"}, + }, + { + "pat on cloud rejected", + SetConfigRequest{SiteURL: "x", AuthMethod: AuthMethodPAT, InstanceType: InstanceTypeCloud}, + }, + { + "api_token on server rejected", + SetConfigRequest{SiteURL: "x", AuthMethod: AuthMethodAPIToken, Email: "e", InstanceType: InstanceTypeServer}, + }, + { + "session_cookie on server rejected", + SetConfigRequest{SiteURL: "x", AuthMethod: AuthMethodSessionCookie, InstanceType: InstanceTypeServer}, + }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -290,6 +311,41 @@ func TestService_Validation(t *testing.T) { } } +func TestService_SetConfig_PATOnServer_Accepted(t *testing.T) { + f := newSvcFixture(t) + ctx := context.Background() + cfg, err := f.svc.SetConfig(ctx, &SetConfigRequest{ + SiteURL: "https://jira.acme.com/", + AuthMethod: AuthMethodPAT, + InstanceType: InstanceTypeServer, + Secret: "pat-token", + }) + if err != nil { + t.Fatalf("set: %v", err) + } + if cfg.InstanceType != InstanceTypeServer { + t.Errorf("instance type round-trip: got %q", cfg.InstanceType) + } + if cfg.AuthMethod != AuthMethodPAT { + t.Errorf("auth method round-trip: got %q", cfg.AuthMethod) + } +} + +// TestService_SetConfig_RejectsMissingInstanceType guards the no-silent-downgrade +// invariant: a stale client that forgets to send instanceType must not be able +// to overwrite a saved Server config back to Cloud. +func TestService_SetConfig_RejectsMissingInstanceType(t *testing.T) { + f := newSvcFixture(t) + _, err := f.svc.SetConfig(context.Background(), &SetConfigRequest{ + SiteURL: "https://a.atlassian.net", Email: "u@x", + AuthMethod: AuthMethodAPIToken, Secret: "tok", + // InstanceType deliberately omitted. + }) + if err == nil { + t.Fatal("expected validation error when instanceType is missing") + } +} + func TestService_TestConnection_InlineSecret(t *testing.T) { f := newSvcFixture(t) called := false @@ -299,7 +355,7 @@ func TestService_TestConnection_InlineSecret(t *testing.T) { } res, err := f.svc.TestConnection(context.Background(), &SetConfigRequest{ SiteURL: "https://a.net", Email: "e", - AuthMethod: AuthMethodAPIToken, Secret: "inline", + AuthMethod: AuthMethodAPIToken, InstanceType: InstanceTypeCloud, Secret: "inline", }) if err != nil || !called { t.Fatalf("called=%v err=%v", called, err) @@ -313,7 +369,7 @@ func TestService_TestConnection_NoStoredSecret_ReturnsFailure(t *testing.T) { f := newSvcFixture(t) res, err := f.svc.TestConnection(context.Background(), &SetConfigRequest{ SiteURL: "https://a.net", Email: "e", - AuthMethod: AuthMethodAPIToken, + AuthMethod: AuthMethodAPIToken, InstanceType: InstanceTypeCloud, }) if err != nil { t.Fatalf("unexpected err: %v", err) @@ -328,7 +384,7 @@ func TestService_DeleteConfig_RemovesSecret(t *testing.T) { ctx := context.Background() _, _ = f.svc.SetConfig(ctx, &SetConfigRequest{ SiteURL: "https://a.net", Email: "e", - AuthMethod: AuthMethodAPIToken, Secret: "t", + AuthMethod: AuthMethodAPIToken, InstanceType: InstanceTypeCloud, Secret: "t", }) if err := f.svc.DeleteConfig(ctx); err != nil { t.Fatalf("delete: %v", err) @@ -373,7 +429,7 @@ func TestService_DoTransition_PassThrough(t *testing.T) { ctx := context.Background() _, _ = f.svc.SetConfig(ctx, &SetConfigRequest{ SiteURL: "https://a.net", Email: "e", - AuthMethod: AuthMethodAPIToken, Secret: "t", + AuthMethod: AuthMethodAPIToken, InstanceType: InstanceTypeCloud, Secret: "t", }) if err := f.svc.DoTransition(ctx, "PROJ-9", "31"); err != nil { t.Fatalf("transition: %v", err) diff --git a/apps/backend/internal/jira/store.go b/apps/backend/internal/jira/store.go index be8b6aa2fb..ceb2921aeb 100644 --- a/apps/backend/internal/jira/store.go +++ b/apps/backend/internal/jira/store.go @@ -47,6 +47,7 @@ const createTablesSQL = ` site_url TEXT NOT NULL, email TEXT NOT NULL DEFAULT '', auth_method TEXT NOT NULL, + instance_type TEXT NOT NULL DEFAULT 'cloud', default_project_key TEXT NOT NULL DEFAULT '', last_checked_at DATETIME, last_ok INTEGER NOT NULL DEFAULT 0, @@ -97,6 +98,28 @@ func (s *Store) initSchema() error { if _, err := s.db.Exec(createTablesSQL); err != nil { return err } + if err := s.addInstanceTypeColumn(); err != nil { + return err + } + return nil +} + +// addInstanceTypeColumn brings older databases up to the current schema by +// adding the instance_type column to jira_configs when missing. Existing rows +// were all written when the code only spoke Cloud, so 'cloud' is the safe +// default. A fresh install hits the column-already-present branch since +// createTablesSQL above declares the column with the same default. +func (s *Store) addInstanceTypeColumn() error { + cols, err := s.tableColumns("jira_configs") + if err != nil { + return err + } + if _, ok := cols["instance_type"]; ok { + return nil + } + if _, err := s.db.Exec(`ALTER TABLE jira_configs ADD COLUMN instance_type TEXT NOT NULL DEFAULT 'cloud'`); err != nil { + return fmt.Errorf("add instance_type column: %w", err) + } return nil } @@ -162,6 +185,7 @@ func (s *Store) migrateLegacyPerWorkspaceTable() error { site_url TEXT NOT NULL, email TEXT NOT NULL DEFAULT '', auth_method TEXT NOT NULL, + instance_type TEXT NOT NULL DEFAULT 'cloud', default_project_key TEXT NOT NULL DEFAULT '', last_checked_at DATETIME, last_ok INTEGER NOT NULL DEFAULT 0, @@ -171,6 +195,9 @@ func (s *Store) migrateLegacyPerWorkspaceTable() error { )`); err != nil { return err } + // instance_type column is intentionally omitted from the INSERT: the column + // default ('cloud') is the correct value for every legacy row, since prior + // releases only supported Atlassian Cloud. if _, err := tx.Exec(` INSERT INTO jira_configs (id, site_url, email, auth_method, default_project_key, last_checked_at, last_ok, last_error, created_at, updated_at) @@ -231,7 +258,7 @@ func (s *Store) tableColumns(table string) (map[string]struct{}, error) { return cols, rows.Err() } -const selectConfigColumns = `site_url, email, auth_method, default_project_key, +const selectConfigColumns = `site_url, email, auth_method, instance_type, default_project_key, last_checked_at, last_ok, last_error, created_at, updated_at` // GetConfig returns the singleton Jira config, or nil when no row exists. @@ -258,16 +285,23 @@ func (s *Store) UpsertConfig(ctx context.Context, cfg *JiraConfig) error { cfg.CreatedAt = now } cfg.UpdatedAt = now + // Defensive: callers that bypass the service layer (tests, future + // migrations) may leave InstanceType empty. Coerce to 'cloud' so reads + // never surface a value the client doesn't understand. + if cfg.InstanceType == "" { + cfg.InstanceType = InstanceTypeCloud + } _, err := s.db.ExecContext(ctx, ` - INSERT INTO jira_configs (id, site_url, email, auth_method, default_project_key, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?) + INSERT INTO jira_configs (id, site_url, email, auth_method, instance_type, default_project_key, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET site_url = excluded.site_url, email = excluded.email, auth_method = excluded.auth_method, + instance_type = excluded.instance_type, default_project_key = excluded.default_project_key, updated_at = excluded.updated_at`, - singletonID, cfg.SiteURL, cfg.Email, cfg.AuthMethod, cfg.DefaultProjectKey, cfg.CreatedAt, cfg.UpdatedAt) + singletonID, cfg.SiteURL, cfg.Email, cfg.AuthMethod, cfg.InstanceType, cfg.DefaultProjectKey, cfg.CreatedAt, cfg.UpdatedAt) return err } diff --git a/apps/backend/internal/jira/store_test.go b/apps/backend/internal/jira/store_test.go index f373d815c2..dd1bcc2266 100644 --- a/apps/backend/internal/jira/store_test.go +++ b/apps/backend/internal/jira/store_test.go @@ -332,3 +332,57 @@ func TestStore_MigrateLegacyPerWorkspaceTable_PreHealthColumns(t *testing.T) { t.Errorf("expected LastCheckedAt=nil (default), got %v", cfg.LastCheckedAt) } } + +// TestStore_AddsInstanceTypeColumn_OnExistingSingleton covers the upgrade path +// where a singleton-shaped jira_configs already exists (no workspace_id +// migration needed) but predates the instance_type column. The ALTER TABLE +// must run and seed the legacy row to 'cloud'. +func TestStore_AddsInstanceTypeColumn_OnExistingSingleton(t *testing.T) { + raw, err := sql.Open("sqlite3", ":memory:") + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + raw.SetMaxOpenConns(1) + raw.SetMaxIdleConns(1) + db := sqlx.NewDb(raw, "sqlite3") + t.Cleanup(func() { _ = db.Close() }) + + // Pre-instance_type schema: singleton id, no instance_type column. + if _, err := db.Exec(` + CREATE TABLE jira_configs ( + id TEXT PRIMARY KEY CHECK(id = 'singleton'), + site_url TEXT NOT NULL, + email TEXT NOT NULL DEFAULT '', + auth_method TEXT NOT NULL, + default_project_key TEXT NOT NULL DEFAULT '', + last_checked_at DATETIME, + last_ok INTEGER NOT NULL DEFAULT 0, + last_error TEXT NOT NULL DEFAULT '', + created_at DATETIME NOT NULL, + updated_at DATETIME NOT NULL + )`); err != nil { + t.Fatalf("legacy schema: %v", err) + } + now := time.Now().UTC() + if _, err := db.Exec(`INSERT INTO jira_configs + (id, site_url, email, auth_method, default_project_key, created_at, updated_at) + VALUES ('singleton', ?, ?, ?, ?, ?, ?)`, + "https://acme.atlassian.net", "u@example.com", AuthMethodAPIToken, "PROJ", now, now); err != nil { + t.Fatalf("seed singleton row: %v", err) + } + + store, err := NewStore(db, db) + if err != nil { + t.Fatalf("NewStore on pre-instance_type schema: %v", err) + } + cfg, err := store.GetConfig(context.Background()) + if err != nil { + t.Fatalf("get singleton: %v", err) + } + if cfg == nil { + t.Fatal("expected singleton row after migration") + } + if cfg.InstanceType != InstanceTypeCloud { + t.Errorf("expected legacy row to default to cloud, got %q", cfg.InstanceType) + } +} diff --git a/apps/web/components/jira/jira-settings.tsx b/apps/web/components/jira/jira-settings.tsx index 056a3514f1..3115a154bc 100644 --- a/apps/web/components/jira/jira-settings.tsx +++ b/apps/web/components/jira/jira-settings.tsx @@ -1,6 +1,6 @@ "use client"; -import { useCallback, useEffect, useState } from "react"; +import { useCallback, useEffect, useState, type Dispatch, type SetStateAction } from "react"; import { IconTicket, IconCode } from "@tabler/icons-react"; import { Button } from "@kandev/ui/button"; import { Card, CardContent } from "@kandev/ui/card"; @@ -26,7 +26,12 @@ import { deleteJiraConfig, testJiraConnection, } from "@/lib/api/domains/jira-api"; -import type { JiraAuthMethod, JiraConfig, TestJiraConnectionResult } from "@/lib/types/jira"; +import type { + JiraAuthMethod, + JiraConfig, + JiraInstanceType, + TestJiraConnectionResult, +} from "@/lib/types/jira"; // Session cookies are HttpOnly so document.cookie can't read them, but // DevTools → Application → Cookies surfaces them in plain text. Users copy @@ -43,6 +48,7 @@ type FormState = { siteUrl: string; email: string; authMethod: JiraAuthMethod; + instanceType: JiraInstanceType; defaultProjectKey: string; secret: string; }; @@ -51,6 +57,7 @@ const emptyForm: FormState = { siteUrl: "", email: "", authMethod: "api_token", + instanceType: "cloud", defaultProjectKey: "", secret: "", }; @@ -61,11 +68,34 @@ function configToForm(cfg: JiraConfig | null): FormState { siteUrl: cfg.siteUrl, email: cfg.email, authMethod: cfg.authMethod, + // Legacy rows written before Server/DC support carry an empty instanceType; + // default to cloud so the dropdown has a valid selection. + instanceType: cfg.instanceType || "cloud", defaultProjectKey: cfg.defaultProjectKey, secret: "", }; } +// defaultAuthForInstance returns the canonical auth method for an instance +// type. Used when the user switches Instance type and the current auth method +// is no longer valid for the new type (e.g. PAT picked for Cloud). +function defaultAuthForInstance(instance: JiraInstanceType): JiraAuthMethod { + return instance === "server" ? "pat" : "api_token"; +} + +// authAllowedForInstance reports whether an auth method is allowed for a given +// instance type. Mirrors the backend validation so the user can't submit an +// invalid combination. session_cookie is Cloud-only today because the backend +// wraps the secret under cloud.session.token / tenant.session.token cookie +// names — Server/DC uses JSESSIONID, so the wrapping is a no-op there until we +// add a Server-aware path. +function authAllowedForInstance(auth: JiraAuthMethod, instance: JiraInstanceType): boolean { + if (auth === "api_token") return instance === "cloud"; + if (auth === "pat") return instance === "server"; + if (auth === "session_cookie") return instance === "cloud"; + return false; +} + function saveLabel(saving: boolean, hasConfig: boolean): string { if (saving) return "Saving..."; return hasConfig ? "Update" : "Save"; @@ -77,19 +107,44 @@ type FieldsRowProps = { update: (key: K, value: FormState[K]) => void; }; -function SiteFields({ form, loading, update }: FieldsRowProps) { +type InstanceFieldsProps = FieldsRowProps & { + setForm: Dispatch>; +}; + +function InstanceFields({ form, loading, setForm }: InstanceFieldsProps) { return (
- - update("siteUrl", e.target.value)} + + +

+ {form.instanceType === "cloud" + ? "Sites hosted at *.atlassian.net." + : "Self-hosted Jira (Server or Data Center)."} +

@@ -98,7 +153,9 @@ function SiteFields({ form, loading, update }: FieldsRowProps) { data-testid="jira-project-input" placeholder="PROJ" value={form.defaultProjectKey} - onChange={(e) => update("defaultProjectKey", e.target.value.toUpperCase())} + onChange={(e) => + setForm((prev) => ({ ...prev, defaultProjectKey: e.target.value.toUpperCase() })) + } disabled={loading} />
@@ -106,7 +163,26 @@ function SiteFields({ form, loading, update }: FieldsRowProps) { ); } +function SiteFields({ form, loading, update }: FieldsRowProps) { + const placeholder = + form.instanceType === "server" ? "https://jira.your-company.com" : "https://acme.atlassian.net"; + return ( +
+ + update("siteUrl", e.target.value)} + disabled={loading} + /> +
+ ); +} + function AuthFields({ form, loading, update }: FieldsRowProps) { + const showEmail = form.instanceType === "cloud" && form.authMethod === "api_token"; return (
@@ -116,29 +192,38 @@ function AuthFields({ form, loading, update }: FieldsRowProps) { onValueChange={(v) => update("authMethod", v as JiraAuthMethod)} disabled={loading} > - + - API token (recommended) - Browser session cookie + {form.instanceType === "cloud" ? ( + <> + API token (recommended) + Browser session cookie + + ) : ( + Personal Access Token + )}
-
- - update("email", e.target.value)} - disabled={loading} - /> -
+ {showEmail ? ( +
+ + update("email", e.target.value)} + disabled={loading} + /> +
+ ) : ( + // Keep the grid balanced so the auth select doesn't span both columns. +
+ )}
); } @@ -166,9 +251,17 @@ function SessionSnippet() { type SecretFieldProps = FieldsRowProps & { hasSavedSecret: boolean }; -function secretPlaceholder(isApiToken: boolean, hasSavedSecret: boolean): string { - if (hasSavedSecret) return "••••••••"; - return isApiToken ? "paste token here" : "paste cloud.session.token value"; +// SECRET_COPY centralizes the field label and empty-state placeholder per +// auth method. Keyed by JiraAuthMethod so adding a new method causes the +// type system to flag the missing entry. +const SECRET_COPY: Record = { + api_token: { label: "API token", placeholder: "paste API token here" }, + pat: { label: "Personal Access Token", placeholder: "paste personal access token here" }, + session_cookie: { label: "Session token value", placeholder: "paste cloud.session.token value" }, +}; + +function secretPlaceholder(method: JiraAuthMethod, hasSavedSecret: boolean): string { + return hasSavedSecret ? "••••••••" : SECRET_COPY[method].placeholder; } function formatExpiry(expiresAt: string): { label: string; tone: "ok" | "warn" | "danger" } { @@ -212,11 +305,13 @@ function SecretField({ hasSavedSecret, secretExpiresAt, }: SecretFieldPropsWithExpiry) { - const isApiToken = form.authMethod === "api_token"; + const method = form.authMethod; + const siteUrl = form.siteUrl.replace(/\/+$/, ""); + const patHref = siteUrl ? `${siteUrl}/secure/ViewProfile.jspa` : undefined; return (
); } @@ -403,6 +521,7 @@ function useJiraSettings() { siteUrl: form.siteUrl, email: form.email, authMethod: form.authMethod, + instanceType: form.instanceType, defaultProjectKey: form.defaultProjectKey, secret: form.secret || undefined, }); @@ -435,6 +554,7 @@ function useJiraSettings() { return { config, form, + setForm, loading, saving, testing, @@ -464,35 +584,65 @@ function EnabledPill() { ); } +// normalizeComparableSiteUrl mirrors the backend's normalizeSiteURL (strip +// trailing slash, prepend https:// if no scheme) so that +// "acme.atlassian.net" and "https://acme.atlassian.net" don't read as +// different hosts in savedSecretMatches. +function normalizeComparableSiteUrl(value: string): string { + const trimmed = value.trim().replace(/\/+$/, ""); + if (!trimmed) return ""; + return trimmed.includes("://") ? trimmed : `https://${trimmed}`; +} + +// savedSecretMatches reports whether the saved secret can be reused against +// the current form values. Reuse is only safe when every identity component +// of the saved credential still matches: same auth method, same instance +// type, same Jira host, and — for Cloud api_token where the basic pair is +// email:token — the same email (case-insensitive). Otherwise the user could +// change the site URL or Cloud account and silently submit the previous +// token to a different host/account. +function savedSecretMatches(config: JiraConfig | null, form: FormState): boolean { + if (!config?.hasSecret) return false; + if (config.authMethod !== form.authMethod) return false; + if ((config.instanceType || "cloud") !== form.instanceType) return false; + if (normalizeComparableSiteUrl(config.siteUrl) !== normalizeComparableSiteUrl(form.siteUrl)) { + return false; + } + if (form.authMethod !== "api_token") return true; + return (config.email ?? "").toLowerCase() === form.email.toLowerCase(); +} + // JiraConnectionSection holds the install-wide credentials form. Watchers and // task presets live elsewhere because they scope per workspace. export function JiraConnectionSection() { const s = useJiraSettings(); - const missingSecret = !s.config?.hasSecret && !s.form.secret; + const savedSecretMatchesMode = savedSecretMatches(s.config, s.form); + const missingSecret = !savedSecretMatchesMode && !s.form.secret; + // Email is only required for the Cloud + api_token combination. Server PAT + // and session cookies authenticate the user out of the token itself. + const emailRequired = s.form.instanceType === "cloud" && s.form.authMethod === "api_token"; const disableSave = - s.saving || - !s.form.siteUrl || - (s.form.authMethod === "api_token" && !s.form.email) || - missingSecret; + s.saving || !s.form.siteUrl || (emailRequired && !s.form.email) || missingSecret; const disableTest = missingSecret; return ( } title="Jira integration" - description="Connect Kandev to an Atlassian Cloud site. Credentials are stored encrypted server-side and shared across all workspaces." + description="Connect Kandev to Atlassian Cloud or a self-hosted Jira Server / Data Center instance. Credentials are stored encrypted server-side and shared across all workspaces." action={} > + diff --git a/apps/web/e2e/helpers/api-client.ts b/apps/web/e2e/helpers/api-client.ts index f07714549c..43a8ed7011 100644 --- a/apps/web/e2e/helpers/api-client.ts +++ b/apps/web/e2e/helpers/api-client.ts @@ -1194,13 +1194,15 @@ export class ApiClient { async setJiraConfig(payload: { siteUrl: string; email: string; - authMethod?: "api_token" | "session_cookie"; + authMethod?: "api_token" | "pat" | "session_cookie"; + instanceType?: "cloud" | "server"; defaultProjectKey?: string; secret: string; }): Promise { return this.request("POST", "/api/v1/jira/config", { ...payload, authMethod: payload.authMethod ?? "api_token", + instanceType: payload.instanceType ?? "cloud", }); } diff --git a/apps/web/e2e/pages/jira-settings-page.ts b/apps/web/e2e/pages/jira-settings-page.ts index ec4b5a6283..5200ffe25f 100644 --- a/apps/web/e2e/pages/jira-settings-page.ts +++ b/apps/web/e2e/pages/jira-settings-page.ts @@ -5,6 +5,8 @@ export class JiraSettingsPage { readonly projectInput: Locator; readonly emailInput: Locator; readonly secretInput: Locator; + readonly instanceSelect: Locator; + readonly authSelect: Locator; readonly testButton: Locator; readonly saveButton: Locator; readonly deleteButton: Locator; @@ -15,6 +17,8 @@ export class JiraSettingsPage { this.projectInput = page.getByTestId("jira-project-input"); this.emailInput = page.getByTestId("jira-email-input"); this.secretInput = page.getByTestId("jira-secret-input"); + this.instanceSelect = page.locator("#jira-instance"); + this.authSelect = page.locator("#jira-auth"); this.testButton = page.getByTestId("jira-test-button"); this.saveButton = page.getByTestId("jira-save-button"); this.deleteButton = page.getByTestId("jira-delete-button"); @@ -32,4 +36,19 @@ export class JiraSettingsPage { await this.secretInput.fill(args.secret); if (args.projectKey) await this.projectInput.fill(args.projectKey); } + + /** Open the Instance dropdown and pick "Atlassian Cloud" or "Server / Data Center". */ + async selectInstance(kind: "cloud" | "server") { + await this.instanceSelect.click(); + const label = kind === "server" ? "Server / Data Center" : "Atlassian Cloud"; + await this.page.getByRole("option", { name: label, exact: true }).click(); + } + + /** Open the Auth-method dropdown and pick by visible label. */ + async selectAuth( + label: "API token (recommended)" | "Browser session cookie" | "Personal Access Token", + ) { + await this.authSelect.click(); + await this.page.getByRole("option", { name: label, exact: true }).click(); + } } diff --git a/apps/web/e2e/tests/integrations/jira-settings.spec.ts b/apps/web/e2e/tests/integrations/jira-settings.spec.ts index 305f3f1c8e..ee06072045 100644 --- a/apps/web/e2e/tests/integrations/jira-settings.spec.ts +++ b/apps/web/e2e/tests/integrations/jira-settings.spec.ts @@ -123,4 +123,135 @@ test.describe("Jira settings", () => { await expect(settings.secretInput).toHaveValue(""); await expect(settings.statusBanner).toHaveCount(0); }); + + test("server / data center save flow with PAT persists across reload", async ({ + testPage, + apiClient, + }) => { + const settings = new JiraSettingsPage(testPage); + await settings.goto(); + + await settings.selectInstance("server"); + // Switching to Server auto-selects PAT — the dropdown should now show it + // as the (only) option, and the email input is no longer rendered. + await expect(settings.authSelect).toContainText(/Personal Access Token/i); + await expect(settings.emailInput).toHaveCount(0); + + await settings.siteInput.fill("https://jira.acme.com"); + await settings.secretInput.fill("pat-token-value"); + await expect(settings.saveButton).toBeEnabled(); + await settings.saveButton.click(); + await expect(settings.saveButton).toHaveText(/Update/i); + await apiClient.waitForIntegrationAuthHealthy("jira"); + + await testPage.reload(); + await settings.siteInput.waitFor(); + await expect(settings.siteInput).toHaveValue("https://jira.acme.com"); + await expect(settings.instanceSelect).toContainText(/Server \/ Data Center/i); + await expect(settings.authSelect).toContainText(/Personal Access Token/i); + await expect(settings.emailInput).toHaveCount(0); + await expect(settings.statusBanner).toHaveAttribute("data-state", "ok"); + }); + + test("switching instance type swaps the auth-method options", async ({ testPage }) => { + const settings = new JiraSettingsPage(testPage); + await settings.goto(); + + // Cloud default: api_token + session_cookie options, no PAT. + await expect(settings.authSelect).toContainText(/API token/i); + await settings.authSelect.click(); + await expect(testPage.getByRole("option", { name: /API token/i })).toBeVisible(); + await expect(testPage.getByRole("option", { name: /session cookie/i })).toBeVisible(); + await expect(testPage.getByRole("option", { name: /Personal Access Token/i })).toHaveCount(0); + // Dismiss the listbox before opening another select. + await testPage.keyboard.press("Escape"); + + await settings.selectInstance("server"); + await expect(settings.authSelect).toContainText(/Personal Access Token/i); + await settings.authSelect.click(); + await expect(testPage.getByRole("option", { name: /Personal Access Token/i })).toBeVisible(); + await expect(testPage.getByRole("option", { name: /API token/i })).toHaveCount(0); + await expect(testPage.getByRole("option", { name: /session cookie/i })).toHaveCount(0); + await testPage.keyboard.press("Escape"); + + // Round-trip back to Cloud restores the canonical default. + await settings.selectInstance("cloud"); + await expect(settings.authSelect).toContainText(/API token/i); + }); + + test("email field hides for session cookie and PAT, returns for cloud + api_token", async ({ + testPage, + }) => { + const settings = new JiraSettingsPage(testPage); + await settings.goto(); + + // Cloud + api_token (default) shows email. + await expect(settings.emailInput).toBeVisible(); + + // Cloud + session_cookie hides email — the secret is the cookie itself. + await settings.selectAuth("Browser session cookie"); + await expect(settings.emailInput).toHaveCount(0); + + // Server + PAT also hides email. + await settings.selectInstance("server"); + await expect(settings.emailInput).toHaveCount(0); + + // Back to Cloud + api_token brings email back. + await settings.selectInstance("cloud"); + await settings.selectAuth("API token (recommended)"); + await expect(settings.emailInput).toBeVisible(); + }); + + test("saved secret is not reused after switching identity fields", async ({ + testPage, + apiClient, + }) => { + const settings = new JiraSettingsPage(testPage); + await settings.goto(); + await settings.fillForm({ + siteUrl: "https://acme.atlassian.net", + email: "alice@example.com", + secret: "api-token-value", + }); + await settings.saveButton.click(); + await expect(settings.saveButton).toHaveText(/Update/i); + await apiClient.waitForIntegrationAuthHealthy("jira"); + + await testPage.reload(); + await settings.siteInput.waitFor(); + // Saved secret reuse: placeholder shows the masked dots, Save stays + // enabled with the field left blank. + await expect(settings.secretInput).toHaveAttribute("placeholder", /•/); + await expect(settings.saveButton).toBeEnabled(); + + // Change the site URL — the saved secret no longer applies to this host. + await settings.siteInput.fill("https://other.atlassian.net"); + await expect(settings.secretInput).toHaveAttribute("placeholder", /paste/i); + await expect(settings.saveButton).toBeDisabled(); + + // Restoring the host re-enables reuse without re-typing the token. + await settings.siteInput.fill("https://acme.atlassian.net"); + await expect(settings.secretInput).toHaveAttribute("placeholder", /•/); + await expect(settings.saveButton).toBeEnabled(); + + // Switching instance type also invalidates reuse. + await settings.selectInstance("server"); + await expect(settings.secretInput).toHaveAttribute("placeholder", /paste/i); + await expect(settings.saveButton).toBeDisabled(); + }); + + test("PAT help link targets the configured site", async ({ testPage }) => { + const settings = new JiraSettingsPage(testPage); + await settings.goto(); + + await settings.selectInstance("server"); + await settings.siteInput.fill("https://jira.acme.com/"); + // patHref strips trailing slashes, so the link should point at the bare + // host + /secure/ViewProfile.jspa. + const helpLink = testPage.getByRole("link", { + name: "https://jira.acme.com/secure/ViewProfile.jspa", + }); + await expect(helpLink).toBeVisible(); + await expect(helpLink).toHaveAttribute("href", "https://jira.acme.com/secure/ViewProfile.jspa"); + }); }); diff --git a/apps/web/hooks/domains/jira/use-jira-availability.test.ts b/apps/web/hooks/domains/jira/use-jira-availability.test.ts index 2bae9fc39d..72520461be 100644 --- a/apps/web/hooks/domains/jira/use-jira-availability.test.ts +++ b/apps/web/hooks/domains/jira/use-jira-availability.test.ts @@ -36,6 +36,7 @@ function makeConfig(overrides: Partial): JiraConfig { siteUrl: "https://example.atlassian.net", email: "u@example.com", authMethod: "api_token", + instanceType: "cloud", defaultProjectKey: "PROJ", hasSecret: true, lastOk: true, diff --git a/apps/web/lib/types/jira.ts b/apps/web/lib/types/jira.ts index de7972ad8d..9fe0e3f552 100644 --- a/apps/web/lib/types/jira.ts +++ b/apps/web/lib/types/jira.ts @@ -1,9 +1,23 @@ -export type JiraAuthMethod = "api_token" | "session_cookie"; +/** + * Authentication methods supported by the Jira integration. + * - `api_token` — Atlassian Cloud only (Basic auth with email + token from id.atlassian.com). + * - `pat` — Jira Server / Data Center only (Personal Access Token, sent as Bearer). + * - `session_cookie` — works on both Cloud and Server (wraps the session JWT cookie). + */ +export type JiraAuthMethod = "api_token" | "pat" | "session_cookie"; + +/** + * Jira deployment kind. Cloud uses REST v3 and the token-paginated search + * endpoint; Server / Data Center expose only REST v2 with legacy `startAt` + * pagination. The backend client picks endpoints based on this field. + */ +export type JiraInstanceType = "cloud" | "server"; export interface JiraConfig { siteUrl: string; email: string; authMethod: JiraAuthMethod; + instanceType: JiraInstanceType; defaultProjectKey: string; hasSecret: boolean; /** ISO timestamp when the session cookie's JWT expires, or null for api_token / opaque cookies. */ @@ -22,6 +36,7 @@ export interface SetJiraConfigRequest { siteUrl: string; email: string; authMethod: JiraAuthMethod; + instanceType: JiraInstanceType; defaultProjectKey?: string; secret?: string; }