From 4d3b598a8c1b93008f3bbee0f03b34b1e840677d Mon Sep 17 00:00:00 2001 From: fmuntean Date: Mon, 7 Sep 2026 16:32:17 +0200 Subject: [PATCH 01/21] feat(jira): add Cloud OAuth 2.0 client-credentials auth Service-account 2LO can mint 60-minute Bearer tokens and call the Atlassian API gateway, so Jira Cloud connections no longer require a user API token. Upstream-Status: Pending Co-authored-by: Cursor --- backend/plugins/jira/api/connection_api.go | 11 +- backend/plugins/jira/models/connection.go | 106 ++++++++- .../plugins/jira/models/connection_test.go | 144 +++++++++++++ .../20260907_add_oauth2_credentials.go | 48 +++++ .../jira/models/migrationscripts/register.go | 1 + backend/plugins/jira/models/oauth.go | 139 ++++++++++++ backend/plugins/jira/models/oauth_test.go | 92 ++++++++ backend/plugins/jira/tasks/api_client.go | 18 ++ backend/plugins/jira/token/round_tripper.go | 79 +++++++ backend/plugins/jira/token/token_provider.go | 109 ++++++++++ .../plugins/jira/token/token_provider_test.go | 197 +++++++++++++++++ config-ui/src/api/connection/index.ts | 6 + .../components/connection-form/index.tsx | 6 + .../register/jira/connection-fields/auth.tsx | 202 ++++++++++++++---- config-ui/src/types/connection.ts | 6 + docs/upstream-diffs.md | 36 ++++ 16 files changed, 1149 insertions(+), 51 deletions(-) create mode 100644 backend/plugins/jira/models/connection_test.go create mode 100644 backend/plugins/jira/models/migrationscripts/20260907_add_oauth2_credentials.go create mode 100644 backend/plugins/jira/models/oauth.go create mode 100644 backend/plugins/jira/models/oauth_test.go create mode 100644 backend/plugins/jira/token/round_tripper.go create mode 100644 backend/plugins/jira/token/token_provider.go create mode 100644 backend/plugins/jira/token/token_provider_test.go diff --git a/backend/plugins/jira/api/connection_api.go b/backend/plugins/jira/api/connection_api.go index 9b6071b15fc..f6388e007e7 100644 --- a/backend/plugins/jira/api/connection_api.go +++ b/backend/plugins/jira/api/connection_api.go @@ -39,13 +39,14 @@ type JiraTestConnResponse struct { } func testConnection(ctx context.Context, connection models.JiraConn) (*JiraTestConnResponse, errors.Error) { - // validate - if vld != nil { - e := vld.StructExcept(connection, "BasicAuth", "AccessToken") - if e != nil { - return nil, errors.Convert(e) + if connection.IsOAuth2() || vld != nil { + if err := connection.ValidateConnection(&connection, vld); err != nil { + return nil, err } } + if connection.IsOAuth2() { + connection.ApplyGatewayEndpoint() + } // test connection apiClient, err := api.NewApiClientFromConnection(ctx, basicRes, &connection) if err != nil { diff --git a/backend/plugins/jira/models/connection.go b/backend/plugins/jira/models/connection.go index 8060c308aaf..01214a7518d 100644 --- a/backend/plugins/jira/models/connection.go +++ b/backend/plugins/jira/models/connection.go @@ -18,13 +18,25 @@ limitations under the License. package models import ( - "github.com/apache/incubator-devlake/core/utils" + "fmt" "net/http" + "strings" + "time" + + "github.com/go-playground/validator/v10" "github.com/apache/incubator-devlake/core/errors" + "github.com/apache/incubator-devlake/core/plugin" + "github.com/apache/incubator-devlake/core/utils" helper "github.com/apache/incubator-devlake/helpers/pluginhelper/api" ) +const ( + // AUTH_METHOD_OAUTH2 is Jira Cloud service-account OAuth 2.0 (client credentials / 2LO). + // It is plugin-specific and is not registered in core MultiAuth. + AUTH_METHOD_OAUTH2 = "OAuth2" +) + type EpicResponse struct { Id int Title string @@ -43,20 +55,99 @@ type JiraConn struct { helper.MultiAuth `mapstructure:",squash"` helper.BasicAuth `mapstructure:",squash"` helper.AccessToken `mapstructure:",squash"` + + ClientId string `mapstructure:"clientId" json:"clientId" gorm:"type:varchar(255)"` + ClientSecret string `mapstructure:"clientSecret" json:"clientSecret" gorm:"type:text;serializer:encdec"` + CloudId string `mapstructure:"cloudId" json:"cloudId" gorm:"type:varchar(255)"` + + // OAuthTokenURL overrides the Atlassian token endpoint (tests only). + OAuthTokenURL string `json:"-" mapstructure:"-" gorm:"-"` + + oauthToken string + oauthTokenExpiresAt *time.Time } func (jc *JiraConn) Sanitize() JiraConn { jc.Password = "" jc.AccessToken.Token = utils.SanitizeString(jc.AccessToken.Token) + jc.ClientSecret = utils.SanitizeString(jc.ClientSecret) + jc.oauthToken = "" + jc.oauthTokenExpiresAt = nil return *jc } +func (jc *JiraConn) IsOAuth2() bool { + return jc.AuthMethod == AUTH_METHOD_OAUTH2 +} + +// GatewayEndpoint returns the Atlassian API gateway base URL for this cloud ID. +func (jc *JiraConn) GatewayEndpoint() string { + cloudId := strings.TrimSpace(jc.CloudId) + if cloudId == "" { + return "" + } + return fmt.Sprintf("https://api.atlassian.com/ex/jira/%s/rest/", cloudId) +} + +// ApplyGatewayEndpoint sets Endpoint to the OAuth 2.0 gateway URL. +func (jc *JiraConn) ApplyGatewayEndpoint() { + if !jc.IsOAuth2() { + return + } + if endpoint := jc.GatewayEndpoint(); endpoint != "" { + jc.Endpoint = endpoint + } +} + +func (jc *JiraConn) OAuthAccessToken() string { + return jc.oauthToken +} + +func (jc *JiraConn) OAuthAccessTokenExpiresAt() *time.Time { + return jc.oauthTokenExpiresAt +} + +func (jc *JiraConn) SetOAuthAccessToken(token string, expiresAt time.Time) { + jc.oauthToken = token + expiry := expiresAt + jc.oauthTokenExpiresAt = &expiry +} + // SetupAuthentication implements the `IAuthentication` interface by delegating // the actual logic to the `MultiAuth` struct to help us write less code func (jc *JiraConn) SetupAuthentication(req *http.Request) errors.Error { + if jc.IsOAuth2() { + token := jc.OAuthAccessToken() + if token == "" { + return errors.Unauthorized.New("oauth2 access token is missing") + } + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) + return nil + } return jc.MultiAuth.SetupAuthenticationForConnection(jc, req) } +// ValidateConnection shadows MultiAuth so authMethod=OAuth2 is not rejected by +// the shared oneof=BasicAuth AccessToken AppKey constraint. +func (jc *JiraConn) ValidateConnection(connection interface{}, v *validator.Validate) errors.Error { + if jc.IsOAuth2() { + jc.ApplyGatewayEndpoint() + if strings.TrimSpace(jc.ClientId) == "" || strings.TrimSpace(jc.ClientSecret) == "" || strings.TrimSpace(jc.CloudId) == "" { + return errors.BadInput.New("clientId, clientSecret and cloudId are required for OAuth2") + } + if jc.Endpoint == "" { + return errors.BadInput.New("cloudId is required for OAuth2") + } + if conn, ok := connection.(*JiraConnection); ok && strings.TrimSpace(conn.Name) == "" { + return errors.BadInput.New("name is required") + } + return nil + } + return jc.MultiAuth.ValidateConnection(connection, v) +} + +var _ plugin.PrepareApiClient = (*JiraConn)(nil) + // JiraConnection holds JiraConn plus ID/Name for database storage type JiraConnection struct { helper.BaseConnection `mapstructure:",squash"` @@ -67,9 +158,14 @@ func (JiraConnection) TableName() string { return "_tool_jira_connections" } +func (connection *JiraConnection) CustomValidate(entity interface{}, v *validator.Validate) errors.Error { + return connection.JiraConn.ValidateConnection(entity, v) +} + func (connection *JiraConnection) MergeFromRequest(target *JiraConnection, body map[string]interface{}) error { token := target.Token password := target.Password + clientSecret := target.ClientSecret authMethod := target.AuthMethod if err := helper.DecodeMapStruct(body, target, true); err != nil { @@ -78,6 +174,7 @@ func (connection *JiraConnection) MergeFromRequest(target *JiraConnection, body modifiedToken := target.Token modifiedPassword := target.Password + modifiedClientSecret := target.ClientSecret modifiedAuthMethod := target.AuthMethod // maybe auth method has changed @@ -88,6 +185,13 @@ func (connection *JiraConnection) MergeFromRequest(target *JiraConnection, body if modifiedPassword == "" || modifiedPassword == utils.SanitizeString(password) { target.Password = password } + if modifiedClientSecret == "" || modifiedClientSecret == utils.SanitizeString(clientSecret) { + target.ClientSecret = clientSecret + } + } + + if target.IsOAuth2() { + target.ApplyGatewayEndpoint() } return nil diff --git a/backend/plugins/jira/models/connection_test.go b/backend/plugins/jira/models/connection_test.go new file mode 100644 index 00000000000..c55db79a84e --- /dev/null +++ b/backend/plugins/jira/models/connection_test.go @@ -0,0 +1,144 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package models + +import ( + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/go-playground/validator/v10" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/apache/incubator-devlake/core/utils" + helper "github.com/apache/incubator-devlake/helpers/pluginhelper/api" +) + +func TestGatewayEndpoint(t *testing.T) { + jc := &JiraConn{CloudId: "abc-123"} + assert.Equal(t, "https://api.atlassian.com/ex/jira/abc-123/rest/", jc.GatewayEndpoint()) + + jc.CloudId = " abc-123 " + assert.Equal(t, "https://api.atlassian.com/ex/jira/abc-123/rest/", jc.GatewayEndpoint()) + + jc.CloudId = "" + assert.Equal(t, "", jc.GatewayEndpoint()) +} + +func TestApplyGatewayEndpoint(t *testing.T) { + jc := &JiraConn{ + CloudId: "cloud-1", + } + jc.AuthMethod = AUTH_METHOD_OAUTH2 + jc.ApplyGatewayEndpoint() + assert.Equal(t, "https://api.atlassian.com/ex/jira/cloud-1/rest/", jc.Endpoint) + + basic := &JiraConn{CloudId: "cloud-1"} + basic.AuthMethod = "BasicAuth" + basic.Endpoint = "https://example.atlassian.net/rest/" + basic.ApplyGatewayEndpoint() + assert.Equal(t, "https://example.atlassian.net/rest/", basic.Endpoint) +} + +func TestValidateConnectionOAuth2(t *testing.T) { + v := validator.New() + jc := &JiraConn{ + ClientId: "id", + ClientSecret: "secret", + CloudId: "cloud-1", + } + jc.AuthMethod = AUTH_METHOD_OAUTH2 + + err := jc.ValidateConnection(jc, v) + require.NoError(t, err) + assert.Equal(t, "https://api.atlassian.com/ex/jira/cloud-1/rest/", jc.Endpoint) + + missing := &JiraConn{CloudId: "cloud-1"} + missing.AuthMethod = AUTH_METHOD_OAUTH2 + err = missing.ValidateConnection(missing, v) + require.Error(t, err) + assert.Contains(t, err.Error(), "clientId, clientSecret and cloudId are required") +} + +func TestValidateConnectionOAuth2DoesNotUseMultiAuthOneOf(t *testing.T) { + v := validator.New() + conn := &JiraConnection{} + conn.Name = "jira-oauth" + conn.AuthMethod = AUTH_METHOD_OAUTH2 + conn.ClientId = "id" + conn.ClientSecret = "secret" + conn.CloudId = "cloud-1" + + err := conn.CustomValidate(conn, v) + require.NoError(t, err) +} + +func TestSanitizeAndMergeFromRequestClientSecret(t *testing.T) { + conn := &JiraConnection{} + conn.AuthMethod = AUTH_METHOD_OAUTH2 + conn.ClientId = "id" + conn.ClientSecret = "super-secret" + conn.CloudId = "cloud-1" + conn.ApplyGatewayEndpoint() + + sanitized := conn.Sanitize() + assert.Equal(t, utils.SanitizeString("super-secret"), sanitized.ClientSecret) + assert.Empty(t, sanitized.OAuthAccessToken()) + + err := conn.MergeFromRequest(conn, map[string]interface{}{ + "authMethod": AUTH_METHOD_OAUTH2, + "clientId": "id", + "clientSecret": utils.SanitizeString("super-secret"), + "cloudId": "cloud-1", + }) + require.NoError(t, err) + assert.Equal(t, "super-secret", conn.ClientSecret) + assert.Equal(t, "https://api.atlassian.com/ex/jira/cloud-1/rest/", conn.Endpoint) +} + +func TestSetupAuthenticationOAuth2(t *testing.T) { + jc := &JiraConn{} + jc.AuthMethod = AUTH_METHOD_OAUTH2 + jc.SetOAuthAccessToken("access-token", time.Now().Add(time.Hour)) + + req := httptest.NewRequest(http.MethodGet, "https://api.atlassian.com/ex/jira/c/rest/api/2/serverInfo", nil) + err := jc.SetupAuthentication(req) + require.NoError(t, err) + assert.Equal(t, "Bearer access-token", req.Header.Get("Authorization")) +} + +func TestSetupAuthenticationOAuth2MissingToken(t *testing.T) { + jc := &JiraConn{} + jc.AuthMethod = AUTH_METHOD_OAUTH2 + req := httptest.NewRequest(http.MethodGet, "https://example.com", nil) + err := jc.SetupAuthentication(req) + require.Error(t, err) +} + +func TestValidateConnectionBasicAuthStillWorks(t *testing.T) { + v := validator.New() + jc := &JiraConn{ + RestConnection: helper.RestConnection{Endpoint: "https://example.atlassian.net/rest/"}, + BasicAuth: helper.BasicAuth{Username: "user@example.com", Password: "token"}, + } + jc.AuthMethod = "BasicAuth" + err := jc.ValidateConnection(jc, v) + require.NoError(t, err) +} diff --git a/backend/plugins/jira/models/migrationscripts/20260907_add_oauth2_credentials.go b/backend/plugins/jira/models/migrationscripts/20260907_add_oauth2_credentials.go new file mode 100644 index 00000000000..0336e500655 --- /dev/null +++ b/backend/plugins/jira/models/migrationscripts/20260907_add_oauth2_credentials.go @@ -0,0 +1,48 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package migrationscripts + +import ( + "github.com/apache/incubator-devlake/core/context" + "github.com/apache/incubator-devlake/core/errors" + "github.com/apache/incubator-devlake/helpers/migrationhelper" +) + +type jiraOAuth20260907 struct { + ClientId string `gorm:"type:varchar(255)"` + ClientSecret string `gorm:"type:text"` + CloudId string `gorm:"type:varchar(255)"` +} + +func (jiraOAuth20260907) TableName() string { + return "_tool_jira_connections" +} + +type addJiraOAuth20260907 struct{} + +func (script *addJiraOAuth20260907) Up(basicRes context.BasicRes) errors.Error { + return migrationhelper.AutoMigrateTables(basicRes, &jiraOAuth20260907{}) +} + +func (*addJiraOAuth20260907) Version() uint64 { + return 20260907120000 +} + +func (*addJiraOAuth20260907) Name() string { + return "add oauth2 client credentials to _tool_jira_connections" +} diff --git a/backend/plugins/jira/models/migrationscripts/register.go b/backend/plugins/jira/models/migrationscripts/register.go index 9c334a9ef88..1e6b3cfd888 100644 --- a/backend/plugins/jira/models/migrationscripts/register.go +++ b/backend/plugins/jira/models/migrationscripts/register.go @@ -55,5 +55,6 @@ func All() []plugin.MigrationScript { new(flushJiraIssues), new(updateScopeConfig), new(addFixVersions20250619), + new(addJiraOAuth20260907), } } diff --git a/backend/plugins/jira/models/oauth.go b/backend/plugins/jira/models/oauth.go new file mode 100644 index 00000000000..87efdcfcfc0 --- /dev/null +++ b/backend/plugins/jira/models/oauth.go @@ -0,0 +1,139 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package models + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/apache/incubator-devlake/core/errors" + "github.com/apache/incubator-devlake/core/plugin" +) + +const ( + // AtlassianOAuthTokenURL is the token endpoint for Jira Cloud service-account OAuth 2.0. + AtlassianOAuthTokenURL = "https://auth.atlassian.com/oauth/token" + defaultTokenTimeout = 10 * time.Second + defaultTokenTTL = 3600 * time.Second +) + +// NewOAuthHTTPClient returns an HTTP client for Atlassian token requests. +// It must not share a transport with the Jira API client (which may wrap a refresh round tripper). +func NewOAuthHTTPClient(proxy string) (*http.Client, errors.Error) { + transport := &http.Transport{} + if proxy != "" { + pu, err := url.Parse(proxy) + if err != nil { + return nil, errors.Convert(err) + } + transport.Proxy = http.ProxyURL(pu) + } + return &http.Client{ + Timeout: defaultTokenTimeout, + Transport: transport, + }, nil +} + +func (jc *JiraConn) tokenURL() string { + if jc.OAuthTokenURL != "" { + return jc.OAuthTokenURL + } + return AtlassianOAuthTokenURL +} + +// MintOAuthAccessToken exchanges client_id/client_secret for a Bearer access token. +func (jc *JiraConn) MintOAuthAccessToken(httpClient *http.Client) errors.Error { + if httpClient == nil { + return errors.Default.New("oauth http client is required") + } + + form := url.Values{} + form.Set("grant_type", "client_credentials") + form.Set("client_id", jc.ClientId) + form.Set("client_secret", jc.ClientSecret) + + ctx, cancel := context.WithTimeout(context.Background(), defaultTokenTimeout) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, jc.tokenURL(), strings.NewReader(form.Encode())) + if err != nil { + return errors.Convert(err) + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "application/json") + + resp, err := httpClient.Do(req) + if err != nil { + return errors.Default.Wrap(err, "failed to request oauth2 access token") + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return errors.Convert(err) + } + if resp.StatusCode != http.StatusOK { + bodyStr := string(body) + const maxBodySnippet = 512 + if len(bodyStr) > maxBodySnippet { + bodyStr = bodyStr[:maxBodySnippet] + "…" + } + return errors.Default.New(fmt.Sprintf("failed to mint oauth2 access token: %d, body: %s", resp.StatusCode, bodyStr)) + } + + var result struct { + AccessToken string `json:"access_token"` + ExpiresIn int `json:"expires_in"` + TokenType string `json:"token_type"` + } + if err := json.Unmarshal(body, &result); err != nil { + return errors.Convert(err) + } + if result.AccessToken == "" { + return errors.Default.New("empty oauth2 access token returned") + } + + ttl := time.Duration(result.ExpiresIn) * time.Second + if ttl <= 0 { + ttl = defaultTokenTTL + } + jc.SetOAuthAccessToken(result.AccessToken, time.Now().Add(ttl)) + return nil +} + +// PrepareApiClient mints an OAuth 2.0 access token so subsequent requests can use Bearer auth. +func (jc *JiraConn) PrepareApiClient(_ plugin.ApiClient) errors.Error { + if !jc.IsOAuth2() { + return nil + } + jc.ApplyGatewayEndpoint() + if jc.OAuthAccessToken() != "" { + return nil + } + httpClient, err := NewOAuthHTTPClient(jc.GetProxy()) + if err != nil { + return err + } + return jc.MintOAuthAccessToken(httpClient) +} diff --git a/backend/plugins/jira/models/oauth_test.go b/backend/plugins/jira/models/oauth_test.go new file mode 100644 index 00000000000..556da1d1106 --- /dev/null +++ b/backend/plugins/jira/models/oauth_test.go @@ -0,0 +1,92 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package models + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestMintOAuthAccessToken(t *testing.T) { + var gotGrant, gotID, gotSecret, gotContentType string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotContentType = r.Header.Get("Content-Type") + require.NoError(t, r.ParseForm()) + gotGrant = r.Form.Get("grant_type") + gotID = r.Form.Get("client_id") + gotSecret = r.Form.Get("client_secret") + w.Header().Set("Content-Type", "application/json") + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "minted-token", + "expires_in": 3600, + "token_type": "Bearer", + "scope": "read:jira-work", + })) + })) + defer server.Close() + + jc := &JiraConn{ + ClientId: "cid", + ClientSecret: "csecret", + CloudId: "cloud-1", + OAuthTokenURL: server.URL, + } + jc.AuthMethod = AUTH_METHOD_OAUTH2 + + err := jc.MintOAuthAccessToken(server.Client()) + require.NoError(t, err) + assert.Equal(t, "application/x-www-form-urlencoded", gotContentType) + assert.Equal(t, "client_credentials", gotGrant) + assert.Equal(t, "cid", gotID) + assert.Equal(t, "csecret", gotSecret) + assert.Equal(t, "minted-token", jc.OAuthAccessToken()) + require.NotNil(t, jc.OAuthAccessTokenExpiresAt()) + assert.True(t, jc.OAuthAccessTokenExpiresAt().After(time.Now().Add(50*time.Minute))) +} + +func TestMintOAuthAccessTokenRejectsEmptyToken(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, `{"access_token":"","expires_in":3600}`) + })) + defer server.Close() + + jc := &JiraConn{OAuthTokenURL: server.URL} + err := jc.MintOAuthAccessToken(server.Client()) + require.Error(t, err) + assert.Contains(t, err.Error(), "empty oauth2 access token") +} + +func TestMintOAuthAccessTokenHTTPError(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(w, `{"error":"invalid_client"}`) + })) + defer server.Close() + + jc := &JiraConn{OAuthTokenURL: server.URL} + err := jc.MintOAuthAccessToken(server.Client()) + require.Error(t, err) + assert.Contains(t, err.Error(), "401") +} diff --git a/backend/plugins/jira/tasks/api_client.go b/backend/plugins/jira/tasks/api_client.go index 2062645b6b5..d00244c3b54 100644 --- a/backend/plugins/jira/tasks/api_client.go +++ b/backend/plugins/jira/tasks/api_client.go @@ -25,15 +25,33 @@ import ( "github.com/apache/incubator-devlake/core/plugin" "github.com/apache/incubator-devlake/helpers/pluginhelper/api" "github.com/apache/incubator-devlake/plugins/jira/models" + "github.com/apache/incubator-devlake/plugins/jira/token" ) func NewJiraApiClient(taskCtx plugin.TaskContext, connection *models.JiraConnection) (*api.ApiAsyncClient, errors.Error) { + if connection.IsOAuth2() { + connection.ApplyGatewayEndpoint() + } // create synchronize api client so we can calculate api rate limit dynamically apiClient, err := api.NewApiClientFromConnection(taskCtx.GetContext(), taskCtx, connection) if err != nil { return nil, err } + if connection.IsOAuth2() { + logger := taskCtx.GetLogger() + tp, terr := token.NewTokenProvider(&connection.JiraConn, logger) + if terr != nil { + return nil, terr + } + baseTransport := apiClient.GetClient().Transport + if baseTransport == nil { + baseTransport = http.DefaultTransport + } + apiClient.GetClient().Transport = token.NewRefreshRoundTripper(baseTransport, tp) + logger.Info("Installed oauth2 token refresh round tripper for Jira connection %d", connection.ID) + } + // create rate limit calculator rateLimiter := &api.ApiRateLimitCalculator{ UserRateLimitPerHour: connection.RateLimitPerHour, diff --git a/backend/plugins/jira/token/round_tripper.go b/backend/plugins/jira/token/round_tripper.go new file mode 100644 index 00000000000..8277559438b --- /dev/null +++ b/backend/plugins/jira/token/round_tripper.go @@ -0,0 +1,79 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package token + +import ( + "net/http" +) + +// RefreshRoundTripper automatically remints OAuth 2.0 client-credentials tokens. +// On 401 the round tripper will: +// - Force a refresh of the access token via the TokenProvider +// - Retry the original request with the new token +// +// When active, the RefreshRoundTripper overwrites the Authorization header +// on every request, superseding any header previously set by SetupAuthentication. +type RefreshRoundTripper struct { + base http.RoundTripper + tokenProvider *TokenProvider +} + +func NewRefreshRoundTripper(base http.RoundTripper, tp *TokenProvider) *RefreshRoundTripper { + return &RefreshRoundTripper{ + base: base, + tokenProvider: tp, + } +} + +func (rt *RefreshRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + return rt.roundTripWithRetry(req, false) +} + +func (rt *RefreshRoundTripper) roundTripWithRetry(req *http.Request, refreshAttempted bool) (*http.Response, error) { + token, err := rt.tokenProvider.GetToken() + if err != nil { + return nil, err + } + + reqClone := req.Clone(req.Context()) + reqClone.Header.Set("Authorization", "Bearer "+token) + + resp, reqErr := rt.base.RoundTrip(reqClone) + if reqErr != nil { + return nil, reqErr + } + + if resp.StatusCode == http.StatusUnauthorized && !refreshAttempted { + resp.Body.Close() + + if err := rt.tokenProvider.ForceRefresh(token); err != nil { + return nil, err + } + + newToken, err := rt.tokenProvider.GetToken() + if err != nil { + return nil, err + } + + reqRetry := req.Clone(req.Context()) + reqRetry.Header.Set("Authorization", "Bearer "+newToken) + return rt.roundTripWithRetry(reqRetry, true) + } + + return resp, nil +} diff --git a/backend/plugins/jira/token/token_provider.go b/backend/plugins/jira/token/token_provider.go new file mode 100644 index 00000000000..15449a54100 --- /dev/null +++ b/backend/plugins/jira/token/token_provider.go @@ -0,0 +1,109 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package token + +import ( + "net/http" + "sync" + "time" + + "github.com/apache/incubator-devlake/core/errors" + "github.com/apache/incubator-devlake/core/log" + "github.com/apache/incubator-devlake/plugins/jira/models" +) + +const ( + DefaultRefreshBuffer = 5 * time.Minute +) + +// TokenProvider mints Atlassian OAuth 2.0 client-credentials tokens and caches them in memory. +type TokenProvider struct { + conn *models.JiraConn + httpClient *http.Client + logger log.Logger + mu sync.Mutex +} + +// NewTokenProvider creates a TokenProvider that uses a dedicated HTTP client for token requests. +// Call this BEFORE wrapping the Jira API client's transport with RefreshRoundTripper so token +// minting never goes through the round tripper. +func NewTokenProvider(conn *models.JiraConn, logger log.Logger) (*TokenProvider, errors.Error) { + httpClient, err := models.NewOAuthHTTPClient(conn.GetProxy()) + if err != nil { + return nil, err + } + return &TokenProvider{ + conn: conn, + httpClient: httpClient, + logger: logger, + }, nil +} + +func (tp *TokenProvider) GetToken() (string, errors.Error) { + tp.mu.Lock() + defer tp.mu.Unlock() + + if tp.needsRefresh() { + if tp.logger != nil { + expiresStr := "unknown" + if exp := tp.conn.OAuthAccessTokenExpiresAt(); exp != nil { + expiresStr = exp.Format(time.RFC3339) + } + tp.logger.Info("Proactive oauth2 token refresh triggered (token expires at %s)", expiresStr) + } + if err := tp.refreshToken(); err != nil { + return "", err + } + } + return tp.conn.OAuthAccessToken(), nil +} + +func (tp *TokenProvider) needsRefresh() bool { + if tp.conn.OAuthAccessToken() == "" { + return true + } + expiresAt := tp.conn.OAuthAccessTokenExpiresAt() + if expiresAt == nil { + return false + } + return time.Now().Add(DefaultRefreshBuffer).After(*expiresAt) +} + +func (tp *TokenProvider) refreshToken() errors.Error { + if tp.logger != nil { + tp.logger.Info("Minting Jira oauth2 access token via client_credentials") + } + return tp.conn.MintOAuthAccessToken(tp.httpClient) +} + +// ForceRefresh remints the access token if the current token is still equal to oldToken. +func (tp *TokenProvider) ForceRefresh(oldToken string) errors.Error { + tp.mu.Lock() + defer tp.mu.Unlock() + + if tp.conn.OAuthAccessToken() != oldToken { + if tp.logger != nil { + tp.logger.Info("Skipping reactive oauth2 token refresh — token already changed by another goroutine") + } + return nil + } + if tp.logger != nil { + tp.logger.Info("Reactive oauth2 token refresh triggered (received 401)") + } + return tp.refreshToken() +} diff --git a/backend/plugins/jira/token/token_provider_test.go b/backend/plugins/jira/token/token_provider_test.go new file mode 100644 index 00000000000..bef2cbde5d8 --- /dev/null +++ b/backend/plugins/jira/token/token_provider_test.go @@ -0,0 +1,197 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package token + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/apache/incubator-devlake/plugins/jira/models" +) + +func oauthConn(tokenURL string) *models.JiraConn { + jc := &models.JiraConn{ + ClientId: "cid", + ClientSecret: "csecret", + CloudId: "cloud-1", + OAuthTokenURL: tokenURL, + } + jc.AuthMethod = models.AUTH_METHOD_OAUTH2 + return jc +} + +func TestNeedsRefresh(t *testing.T) { + tp := &TokenProvider{conn: oauthConn("")} + + assert.True(t, tp.needsRefresh(), "empty token should refresh") + + tp.conn.SetOAuthAccessToken("tok", time.Now().Add(10*time.Minute)) + assert.False(t, tp.needsRefresh()) + + tp.conn.SetOAuthAccessToken("tok", time.Now().Add(1*time.Minute)) + assert.True(t, tp.needsRefresh()) + + tp.conn.SetOAuthAccessToken("tok", time.Now().Add(-1*time.Minute)) + assert.True(t, tp.needsRefresh()) +} + +func TestGetTokenMintsWhenExpired(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.NoError(t, r.ParseForm()) + assert.Equal(t, "client_credentials", r.Form.Get("grant_type")) + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "fresh-token", + "expires_in": 3600, + "token_type": "Bearer", + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + conn.SetOAuthAccessToken("stale", time.Now().Add(-time.Minute)) + + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + + token, err := tp.GetToken() + require.NoError(t, err) + assert.Equal(t, "fresh-token", token) +} + +func TestForceRefreshSkipsIfTokenChanged(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + calls++ + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "new-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + conn.SetOAuthAccessToken("current", time.Now().Add(time.Hour)) + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + + require.NoError(t, tp.ForceRefresh("stale-old-token")) + assert.Equal(t, 0, calls) + assert.Equal(t, "current", conn.OAuthAccessToken()) + + require.NoError(t, tp.ForceRefresh("current")) + assert.Equal(t, 1, calls) + assert.Equal(t, "new-token", conn.OAuthAccessToken()) +} + +func TestGetTokenConcurrency(t *testing.T) { + var mu sync.Mutex + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + mu.Lock() + calls++ + mu.Unlock() + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "shared-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + + var wg sync.WaitGroup + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { + defer wg.Done() + token, gerr := tp.GetToken() + assert.NoError(t, gerr) + assert.Equal(t, "shared-token", token) + }() + } + wg.Wait() + + mu.Lock() + defer mu.Unlock() + assert.Equal(t, 1, calls) +} + +func TestRoundTripper401Refresh(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.NoError(t, r.ParseForm()) + assert.Equal(t, "client_credentials", r.Form.Get("grant_type")) + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "new-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + conn.SetOAuthAccessToken("old-token", time.Now().Add(10*time.Minute)) + + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + + apiCalls := 0 + base := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + apiCalls++ + auth := req.Header.Get("Authorization") + if auth == "Bearer old-token" { + return &http.Response{ + StatusCode: http.StatusUnauthorized, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + } + if auth == "Bearer new-token" { + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + } + return &http.Response{StatusCode: http.StatusInternalServerError, Body: io.NopCloser(http.NoBody), Request: req}, nil + }) + + rt := NewRefreshRoundTripper(base, tp) + req, reqErr := http.NewRequest(http.MethodGet, "https://api.atlassian.com/ex/jira/c/rest/api/2/serverInfo", nil) + require.NoError(t, reqErr) + + resp, tripErr := rt.RoundTrip(req) + require.NoError(t, tripErr) + assert.Equal(t, http.StatusOK, resp.StatusCode) + assert.Equal(t, 2, apiCalls) + assert.Equal(t, "new-token", conn.OAuthAccessToken()) +} + +type roundTripperFunc func(*http.Request) (*http.Response, error) + +func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} diff --git a/config-ui/src/api/connection/index.ts b/config-ui/src/api/connection/index.ts index 3cf46ee9063..6bb96067c63 100644 --- a/config-ui/src/api/connection/index.ts +++ b/config-ui/src/api/connection/index.ts @@ -49,6 +49,9 @@ export const test = ( | 'token' | 'appId' | 'secretKey' + | 'cloudId' + | 'clientId' + | 'clientSecret' | 'proxy' | 'rateLimitPerHour' | 'dbUrl' @@ -79,6 +82,9 @@ export const testOld = ( | 'token' | 'appId' | 'secretKey' + | 'cloudId' + | 'clientId' + | 'clientSecret' | 'proxy' | 'rateLimitPerHour' | 'dbUrl' diff --git a/config-ui/src/plugins/components/connection-form/index.tsx b/config-ui/src/plugins/components/connection-form/index.tsx index d728b17b063..3dce8b1e3b8 100644 --- a/config-ui/src/plugins/components/connection-form/index.tsx +++ b/config-ui/src/plugins/components/connection-form/index.tsx @@ -52,6 +52,9 @@ const buildUpdateTestPayload = (connection: any, values: any, customHeaders: ICu token: isEqual(connection?.token, values.token) ? undefined : values.token, appId: isEqual(connection?.appId, values.appId) ? undefined : values.appId, secretKey: isEqual(connection?.secretKey, values.secretKey) ? undefined : values.secretKey, + cloudId: isEqual(connection?.cloudId, values.cloudId) ? undefined : values.cloudId, + clientId: isEqual(connection?.clientId, values.clientId) ? undefined : values.clientId, + clientSecret: isEqual(connection?.clientSecret, values.clientSecret) ? undefined : values.clientSecret, proxy: isEqual(connection?.proxy, values.proxy) ? undefined : values.proxy, rateLimitPerHour: isEqual(connection?.rateLimitPerHour, values.rateLimitPerHour) ? undefined @@ -79,6 +82,9 @@ const buildCreateTestPayload = (initialValues: any, values: any, customHeaders: 'authMethod', 'appId', 'secretKey', + 'cloudId', + 'clientId', + 'clientSecret', 'accessKeyId', 'secretAccessKey', 'region', diff --git a/config-ui/src/plugins/register/jira/connection-fields/auth.tsx b/config-ui/src/plugins/register/jira/connection-fields/auth.tsx index a85999ba3b0..3f488b3f82c 100644 --- a/config-ui/src/plugins/register/jira/connection-fields/auth.tsx +++ b/config-ui/src/plugins/register/jira/connection-fields/auth.tsx @@ -24,8 +24,19 @@ import { Block, ExternalLink } from '@/components'; import { DOC_URL } from '@/release'; const JIRA_CLOUD_REGEX = /^https:\/\/\w+.atlassian.net\/rest\/$/; +const JIRA_OAUTH_GATEWAY_REGEX = /^https:\/\/api\.atlassian\.com\/ex\/jira\/[^/]+\/rest\/$/; -type Method = 'BasicAuth' | 'AccessToken'; +type Method = 'BasicAuth' | 'AccessToken' | 'OAuth2'; +type CloudMethod = 'BasicAuth' | 'OAuth2'; + +const gatewayEndpoint = (cloudId?: string) => + cloudId ? `https://api.atlassian.com/ex/jira/${cloudId.trim()}/rest/` : ''; + +const isCloudConnection = (values: { authMethod?: string; endpoint?: string }) => + values.authMethod === 'OAuth2' || + !values.endpoint || + JIRA_CLOUD_REGEX.test(values.endpoint) || + JIRA_OAUTH_GATEWAY_REGEX.test(values.endpoint); interface Props { type: 'create' | 'update'; @@ -40,10 +51,12 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop const [version, setVersion] = useState('cloud'); useEffect(() => { - if (initialValues.endpoint && !JIRA_CLOUD_REGEX.test(initialValues.endpoint)) { + if (isCloudConnection(initialValues)) { + setVersion('cloud'); + } else if (initialValues.endpoint) { setVersion('server'); } - }, [initialValues.endpoint]); + }, [initialValues.endpoint, initialValues.authMethod]); useEffect(() => { setValues({ @@ -52,6 +65,9 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop username: initialValues.username, password: initialValues.password, token: initialValues.token, + cloudId: initialValues.cloudId, + clientId: initialValues.clientId, + clientSecret: initialValues.clientSecret, }); }, [ initialValues.endpoint, @@ -59,21 +75,25 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop initialValues.username, initialValues.password, initialValues.token, + initialValues.cloudId, + initialValues.clientId, + initialValues.clientSecret, ]); useEffect(() => { const required = (values.authMethod === 'BasicAuth' && values.username && values.password) || (values.authMethod === 'AccessToken' && values.token) || + (values.authMethod === 'OAuth2' && values.cloudId && values.clientId && values.clientSecret) || type === 'update'; setErrors({ - endpoint: !values.endpoint ? 'endpoint is required' : '', + endpoint: values.authMethod === 'OAuth2' || values.endpoint ? '' : 'endpoint is required', auth: required ? '' : 'auth is required', }); }, [values]); const handleChangeVersion = (e: RadioChangeEvent) => { - const version = e.target.value; + const nextVersion = e.target.value; setValues({ endpoint: '', @@ -81,9 +101,12 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop username: undefined, password: undefined, token: undefined, + cloudId: undefined, + clientId: undefined, + clientSecret: undefined, }); - setVersion(version); + setVersion(nextVersion); }; const handleChangeEndpoint = (e: React.ChangeEvent) => { @@ -92,6 +115,20 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop }); }; + const handleChangeCloudMethod = (e: RadioChangeEvent) => { + const authMethod = (e.target as HTMLInputElement).value as CloudMethod; + setValues({ + authMethod, + username: undefined, + password: undefined, + token: undefined, + cloudId: undefined, + clientId: undefined, + clientSecret: undefined, + endpoint: '', + }); + }; + const handleChangeMethod = (e: RadioChangeEvent) => { setValues({ authMethod: (e.target as HTMLInputElement).value as Method, @@ -119,6 +156,28 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop }); }; + const handleChangeCloudId = (e: React.ChangeEvent) => { + const cloudId = e.target.value; + setValues({ + cloudId, + endpoint: gatewayEndpoint(cloudId), + }); + }; + + const handleChangeClientId = (e: React.ChangeEvent) => { + setValues({ + clientId: e.target.value, + }); + }; + + const handleChangeClientSecret = (e: React.ChangeEvent) => { + setValues({ + clientSecret: e.target.value, + }); + }; + + const cloudAuthMethod: CloudMethod = values.authMethod === 'OAuth2' ? 'OAuth2' : 'BasicAuth'; + return ( <> @@ -127,54 +186,107 @@ export const Auth = ({ type, initialValues, values, setValues, setErrors }: Prop Jira Server - - {version === 'cloud' - ? 'Provide the Jira instance API endpoint. For Jira Cloud, e.g. https://your-company.atlassian.net/rest/. Please note that the endpoint URL should end with /.' - : ''} - {version === 'server' - ? 'Provide the Jira instance API endpoint. For Jira Server, e.g. https://jira.your-company.com/rest/. Please note that the endpoint URL should end with /.' - : ''} - - } - required - > - - - - - {version === 'cloud' && ( - <> - - - + {!(version === 'cloud' && cloudAuthMethod === 'OAuth2') && ( Learn about how to create an API Token + <> + {version === 'cloud' + ? 'Provide the Jira instance API endpoint. For Jira Cloud, e.g. https://your-company.atlassian.net/rest/. Please note that the endpoint URL should end with /.' + : ''} + {version === 'server' + ? 'Provide the Jira instance API endpoint. For Jira Server, e.g. https://jira.your-company.com/rest/. Please note that the endpoint URL should end with /.' + : ''} + } required > + )} + + + {version === 'cloud' && ( + <> + + + API Token + OAuth 2.0 (Service Account) + + + + {cloudAuthMethod === 'BasicAuth' && ( + <> + + + + + Learn about how to create an API Token + + } + required + > + + + + )} + + {cloudAuthMethod === 'OAuth2' && ( + <> + + + + + + + + + + {values.endpoint && ( + + + + )} + + )} )} diff --git a/config-ui/src/types/connection.ts b/config-ui/src/types/connection.ts index bb39fa2e59b..65914ce5822 100644 --- a/config-ui/src/types/connection.ts +++ b/config-ui/src/types/connection.ts @@ -32,6 +32,9 @@ export interface IConnectionAPI { password?: string; appId?: string; secretKey?: string; + cloudId?: string; + clientId?: string; + clientSecret?: string; dbUrl?: string; companyId?: number; proxy: string; @@ -95,6 +98,9 @@ export interface IConnection { password?: string; appId?: string; secretKey?: string; + cloudId?: string; + clientId?: string; + clientSecret?: string; dbUrl?: string; companyId?: number; proxy: string; diff --git a/docs/upstream-diffs.md b/docs/upstream-diffs.md index 090e0a64537..02b3b59031f 100644 --- a/docs/upstream-diffs.md +++ b/docs/upstream-diffs.md @@ -288,3 +288,39 @@ has no equivalent table. **Rebase notes:** New files plus an append in `domaininfo.go` and `register.go:All()`. Low conflict risk unless upstream adds adjacent domain tables in the same slice. + +## jira: OAuth 2.0 client-credentials (service account / 2LO) + +**Files:** +- `backend/plugins/jira/models/connection.go` +- `backend/plugins/jira/models/oauth.go` +- `backend/plugins/jira/models/connection_test.go` +- `backend/plugins/jira/models/oauth_test.go` +- `backend/plugins/jira/models/migrationscripts/20260907_add_oauth2_credentials.go` +- `backend/plugins/jira/models/migrationscripts/register.go` +- `backend/plugins/jira/api/connection_api.go` +- `backend/plugins/jira/tasks/api_client.go` +- `backend/plugins/jira/token/token_provider.go` +- `backend/plugins/jira/token/round_tripper.go` +- `backend/plugins/jira/token/token_provider_test.go` +- `config-ui/src/plugins/register/jira/connection-fields/auth.tsx` +- `config-ui/src/plugins/components/connection-form/index.tsx` +- `config-ui/src/types/connection.ts` +- `config-ui/src/api/connection/index.ts` + +**Reason:** Jira Cloud service accounts authenticate with OAuth 2.0 client +credentials (`grant_type=client_credentials`), not Basic Auth / PAT. Access +tokens last 60 minutes and API calls must go through +`https://api.atlassian.com/ex/jira/{cloudId}/rest/`. Adds `authMethod=OAuth2` +handling inside the Jira plugin (no core MultiAuth change), in-memory token +minting, and a refresh round tripper for long collections. + +**Upstream status:** Pending — could be contributed upstream as a Jira plugin +enhancement. +**Upstream PR:** none yet +**Owner:** @fmuntean + +**Rebase notes:** Watch upstream changes to `JiraConn` / `_tool_jira_connections`, +`NewJiraApiClient`, `testConnection` validation, and Config UI Cloud auth fields. +`register.go` append is low risk. Shared Config UI connection form/types/API pick +lists gained `cloudId` / `clientId` / `clientSecret`. From b176aa064c27596678464a029c380440bc479af5 Mon Sep 17 00:00:00 2001 From: Rafaela Soares Date: Mon, 7 Sep 2026 16:10:01 +0100 Subject: [PATCH 02/21] fix(pluginhelper): include graphql error details and variables in collector logs Co-authored-by: Cursor --- .../pluginhelper/api/graphql_collector.go | 42 +++++++++++++++++-- .../api/graphql_collector_test.go | 27 ++++++++++++ docs/upstream-diffs.md | 23 ++++++++++ 3 files changed, 88 insertions(+), 4 deletions(-) diff --git a/backend/helpers/pluginhelper/api/graphql_collector.go b/backend/helpers/pluginhelper/api/graphql_collector.go index 28a5b2b9d86..3b97e07b4a6 100644 --- a/backend/helpers/pluginhelper/api/graphql_collector.go +++ b/backend/helpers/pluginhelper/api/graphql_collector.go @@ -20,6 +20,7 @@ package api import ( "context" "encoding/json" + "fmt" "net/http" "reflect" "strings" @@ -187,9 +188,11 @@ func (collector *GraphqlCollector) Execute() errors.Error { collector.args.GraphqlClient.Wait() if collector.HasError() { + for i, workerErr := range collector.workerErrors { + logger.Error(nil, "graphql collector worker error [%d/%d]: %s", i+1, len(collector.workerErrors), workerErr) + } err = errors.Default.Combine(collector.workerErrors) logger.Error(err, "ended Graphql collector execution with error") - logger.Error(collector.workerErrors[0], "the first error of them") return err } else { logger.Info("ended api collection without error") @@ -270,7 +273,9 @@ func (collector *GraphqlCollector) fetchAsync(reqData *GraphqlRequestData, handl // direct error message for error combine collector.checkError(err) } else { - collector.checkError(errors.Default.Wrap(err, `graphql query failed`)) + msg := formatGraphqlQueryFailure(err, variables) + logger.Error(err, "%s", msg) + collector.checkError(errors.Default.New(msg)) } return } @@ -279,11 +284,13 @@ func (collector *GraphqlCollector) fetchAsync(reqData *GraphqlRequestData, handl hasNonIgnorableDataErrors := false for _, dataError := range dataErrors { if isIgnorableGraphqlQueryError(dataError) { - logger.Warn(nil, "Issue may have been transferred or deleted.") + logger.Warn(nil, "ignorable graphql data error (issue transferred or deleted): %s", formatGraphqlDataError(dataError, variables)) continue } hasNonIgnorableDataErrors = true - collector.checkError(errors.Default.Wrap(dataError, `graphql query got error`)) + msg := formatGraphqlDataError(dataError, variables) + logger.Error(nil, "%s", msg) + collector.checkError(errors.Default.New(msg)) } if hasNonIgnorableDataErrors { return @@ -352,4 +359,31 @@ func isIgnorableGraphqlQueryError(err error) bool { return err != nil && strings.Contains(err.Error(), "Could not resolve to an Issue") } +func formatGraphqlQueryFailure(err error, variables map[string]interface{}) string { + return fmt.Sprintf("graphql query failed: %s%s", err.Error(), formatGraphqlVariables(variables)) +} + +func formatGraphqlDataError(err error, variables map[string]interface{}) string { + msg := err.Error() + if de, ok := err.(graphql.DataError); ok && len(de.Locations) > 0 { + locs := make([]string, 0, len(de.Locations)) + for _, loc := range de.Locations { + locs = append(locs, fmt.Sprintf("line %d col %d", loc.Line, loc.Column)) + } + msg = fmt.Sprintf("%s (%s)", msg, strings.Join(locs, ", ")) + } + return fmt.Sprintf("graphql query got error: %s%s", msg, formatGraphqlVariables(variables)) +} + +func formatGraphqlVariables(variables map[string]interface{}) string { + if len(variables) == 0 { + return "" + } + varsJSON, err := json.Marshal(variables) + if err != nil { + return fmt.Sprintf(" variables=%v", variables) + } + return fmt.Sprintf(" variables=%s", varsJSON) +} + var _ plugin.SubTask = (*GraphqlCollector)(nil) diff --git a/backend/helpers/pluginhelper/api/graphql_collector_test.go b/backend/helpers/pluginhelper/api/graphql_collector_test.go index fcab4dce098..ef530c4bef4 100644 --- a/backend/helpers/pluginhelper/api/graphql_collector_test.go +++ b/backend/helpers/pluginhelper/api/graphql_collector_test.go @@ -21,6 +21,7 @@ import ( "errors" "testing" + "github.com/merico-ai/graphql" "github.com/stretchr/testify/assert" ) @@ -29,3 +30,29 @@ func TestIsIgnorableGraphqlQueryError(t *testing.T) { assert.False(t, isIgnorableGraphqlQueryError(errors.New("some other graphql error"))) assert.False(t, isIgnorableGraphqlQueryError(nil)) } + +func TestFormatGraphqlDataError(t *testing.T) { + err := graphql.DataError{ + Message: "Could not resolve to a PullRequest with the number of 42.", + Locations: []struct { + Line int + Column int + }{{Line: 3, Column: 5}}, + } + got := formatGraphqlDataError(err, map[string]interface{}{ + "owner": "acme", + "name": "repo", + }) + assert.Contains(t, got, "Could not resolve to a PullRequest with the number of 42.") + assert.Contains(t, got, "line 3 col 5") + assert.Contains(t, got, `"owner":"acme"`) + assert.Contains(t, got, `"name":"repo"`) +} + +func TestFormatGraphqlQueryFailure(t *testing.T) { + got := formatGraphqlQueryFailure(errors.New("non-200 OK status code: 502"), map[string]interface{}{ + "pageSize": 10, + }) + assert.Contains(t, got, "graphql query failed: non-200 OK status code: 502") + assert.Contains(t, got, `"pageSize":10`) +} diff --git a/docs/upstream-diffs.md b/docs/upstream-diffs.md index 090e0a64537..a1ea0a831f7 100644 --- a/docs/upstream-diffs.md +++ b/docs/upstream-diffs.md @@ -288,3 +288,26 @@ has no equivalent table. **Rebase notes:** New files plus an append in `domaininfo.go` and `register.go:All()`. Low conflict risk unless upstream adds adjacent domain tables in the same slice. + +## graphql collector: include data-error message and variables in logs + +**Files:** +- `backend/helpers/pluginhelper/api/graphql_collector.go` +- `backend/helpers/pluginhelper/api/graphql_collector_test.go` + +**Reason:** `errors.Default.Wrap(dataError, "graphql query got error")` uses +cockroachdb `WithDetail`. `Error()` then `%+v`s that wrapper, so pipeline +messages look like `Wraps: (2) graphql query got error Error types: (1) +*hintdetail.withDetail (2) *errors.errorString` and drop the GraphQL +`Message`, locations, and request variables. Store/log a flattened string +instead (`errors.Default.New`) so subtask `message` and worker logs include +the real GitHub error and variables. + +**Upstream status:** Pending — should be contributed upstream as a diagnostics +fix. +**Upstream PR:** none yet +**Owner:** @rsoaresd + +**Rebase notes:** Touches `fetchAsync` data-error / transport-error handling +and `Execute` worker-error logging. Watch for upstream changes around +`IgnoreQueryErrors` / `isIgnorableGraphqlQueryError`. From 9b796d75cef7b7d76dd99e3c836214b00b8fa9f4 Mon Sep 17 00:00:00 2001 From: fmuntean Date: Wed, 9 Sep 2026 13:18:46 +0200 Subject: [PATCH 03/21] fix(jira): surface Jira errors on Test Connection without login redirect Credential 401s were forwarded as HTTP 401, so Config UI treated them as session expiry. Map them to 400, skip the login interceptor for plugin tests, and include Jira's response body (e.g. scope does not match). Upstream-Status: Pending Co-Authored-By: Cursor Grok 4.6 Co-authored-by: Cursor --- backend/plugins/jira/api/connection_api.go | 78 +++++++++++++++++-- .../plugins/jira/api/connection_api_test.go | 70 +++++++++++++++++ config-ui/src/utils/request.ts | 13 +++- docs/upstream-diffs.md | 2 + 4 files changed, 156 insertions(+), 7 deletions(-) create mode 100644 backend/plugins/jira/api/connection_api_test.go diff --git a/backend/plugins/jira/api/connection_api.go b/backend/plugins/jira/api/connection_api.go index f6388e007e7..6bcad630c60 100644 --- a/backend/plugins/jira/api/connection_api.go +++ b/backend/plugins/jira/api/connection_api.go @@ -19,7 +19,9 @@ package api import ( "context" + "encoding/json" "fmt" + "io" "net/http" "net/url" "strings" @@ -72,10 +74,12 @@ func testConnection(ctx context.Context, connection models.JiraConn) (*JiraTestC return nil, errors.NotFound.New(fmt.Sprintf("Seems like an invalid Endpoint URL, please try %s", restUrl.String())) } if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden { - return nil, errors.HttpStatus(res.StatusCode).New("Please check your credential") + // 400 not 401: Config UI treats HTTP 401 as a DevLake session expiry and + // navigates to /login, wiping the connection form and Network tab. + return nil, errors.BadInput.New(withJiraHTTPDetail(res, "Please check your credential")) } if res.StatusCode != http.StatusOK { - return nil, errors.HttpStatus(res.StatusCode).New(fmt.Sprintf("%s unexpected status code: %d", serverInfoFail, res.StatusCode)) + return nil, errors.HttpStatus(res.StatusCode).New(withJiraHTTPDetail(res, fmt.Sprintf("%s unexpected status code: %d", serverInfoFail, res.StatusCode))) } resBody := &models.JiraServerInfo{} @@ -99,13 +103,16 @@ func testConnection(ctx context.Context, connection models.JiraConn) (*JiraTestC } getStatusFail += ": [ " + res.Request.URL.String() + " ]" - errMsg := "" - if res.StatusCode == http.StatusUnauthorized { - return nil, errors.HttpStatus(res.StatusCode).New("Please check your credential") + if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden { + return nil, errors.BadInput.New(withJiraHTTPDetail(res, fmt.Sprintf( + "Jira accepted the connection (serverInfo OK) but GET %s returned %d", + res.Request.URL.String(), + res.StatusCode, + ))) } if res.StatusCode != http.StatusOK { - return nil, errors.HttpStatus(res.StatusCode).New(fmt.Sprintf("%s Unexpected [%s] status code: %d %s", getStatusFail, res.Request.URL, res.StatusCode, errMsg)) + return nil, errors.HttpStatus(res.StatusCode).New(withJiraHTTPDetail(res, fmt.Sprintf("%s Unexpected [%s] status code: %d", getStatusFail, res.Request.URL, res.StatusCode))) } connection = connection.Sanitize() body := JiraTestConnResponse{} @@ -220,3 +227,62 @@ func ListConnections(input *plugin.ApiResourceInput) (*plugin.ApiResourceOutput, func GetConnection(input *plugin.ApiResourceInput) (*plugin.ApiResourceOutput, errors.Error) { return dsHelper.ConnApi.GetDetail(input) } + +func withJiraHTTPDetail(res *http.Response, msg string) string { + if detail := jiraHTTPErrorDetail(res); detail != "" { + return msg + ": " + detail + } + return msg +} + +// jiraHTTPErrorDetail reads Jira's error payload. Classic REST uses +// errorMessages; the Atlassian OAuth gateway often uses message and/or +// WWW-Authenticate (e.g. insufficient_scope). +func jiraHTTPErrorDetail(res *http.Response) string { + if res == nil || res.Body == nil { + return "" + } + defer res.Body.Close() + raw, err := io.ReadAll(res.Body) + if err != nil { + return "" + } + if parsed := parseJiraErrorBody(strings.TrimSpace(string(raw))); parsed != "" { + return parsed + } + if auth := strings.TrimSpace(res.Header.Get("WWW-Authenticate")); auth != "" { + return auth + } + text := strings.TrimSpace(string(raw)) + if text == "" || strings.HasPrefix(text, "<") { + return "" + } + const maxLen = 500 + if len(text) > maxLen { + return text[:maxLen] + "..." + } + return text +} + +func parseJiraErrorBody(text string) string { + if text == "" || text[0] != '{' { + return "" + } + var payload struct { + ErrorMessages []string `json:"errorMessages"` + Message string `json:"message"` + } + if json.Unmarshal([]byte(text), &payload) != nil { + return "" + } + parts := make([]string, 0, len(payload.ErrorMessages)+1) + for _, m := range payload.ErrorMessages { + if m = strings.TrimSpace(m); m != "" { + parts = append(parts, m) + } + } + if m := strings.TrimSpace(payload.Message); m != "" { + parts = append(parts, m) + } + return strings.Join(parts, "; ") +} diff --git a/backend/plugins/jira/api/connection_api_test.go b/backend/plugins/jira/api/connection_api_test.go new file mode 100644 index 00000000000..31d3962a36f --- /dev/null +++ b/backend/plugins/jira/api/connection_api_test.go @@ -0,0 +1,70 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package api + +import ( + "io" + "net/http" + "strings" + "testing" +) + +func TestJiraHTTPErrorDetail(t *testing.T) { + tests := []struct { + name string + body string + header string + want string + }{ + { + name: "classic jira errorMessages", + body: `{"errorMessages":["Client must be authenticated to access this resource."],"errors":{}}`, + want: "Client must be authenticated to access this resource.", + }, + { + name: "atlassian gateway message", + body: `{"code":401,"message":"Unauthorized; scope does not match"}`, + want: "Unauthorized; scope does not match", + }, + { + name: "www-authenticate when body empty", + header: `Bearer error="insufficient_scope"`, + want: `Bearer error="insufficient_scope"`, + }, + { + name: "html body ignored", + body: `Unauthorized`, + want: "", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + res := &http.Response{ + StatusCode: http.StatusUnauthorized, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(tt.body)), + } + if tt.header != "" { + res.Header.Set("WWW-Authenticate", tt.header) + } + if got := jiraHTTPErrorDetail(res); got != tt.want { + t.Errorf("jiraHTTPErrorDetail() = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/config-ui/src/utils/request.ts b/config-ui/src/utils/request.ts index e91739f7242..3badcc0d4b7 100644 --- a/config-ui/src/utils/request.ts +++ b/config-ui/src/utils/request.ts @@ -41,18 +41,29 @@ export type RequestConfig = { const isLoginRoute = () => window.location.pathname.replace(/\/+$/, '').endsWith('/login'); +// Plugin connection tests often return 401 when the *remote* credential is +// wrong. That is not a DevLake session expiry — do not wipe the form. +const isPluginConnectionTest = (url?: string) => + !!url && /\/plugins\/[^/]+(?:\/connections\/[^/]+)?\/test\/?$/.test(url); + let redirectingToLogin = false; instance.interceptors.response.use( (response) => response, (error) => { const status = error.response?.status; + const requestUrl = error.config?.url as string | undefined; if (status === 428) { window.location.replace('/db-migrate'); } - if (status === 401 && !isLoginRoute() && !redirectingToLogin) { + if ( + status === 401 && + !isLoginRoute() && + !redirectingToLogin && + !isPluginConnectionTest(requestUrl) + ) { redirectingToLogin = true; const returnUrl = encodeURIComponent(window.location.pathname + window.location.search); window.location.replace(`/login?return_url=${returnUrl}`); diff --git a/docs/upstream-diffs.md b/docs/upstream-diffs.md index 02b3b59031f..dc3e8de2048 100644 --- a/docs/upstream-diffs.md +++ b/docs/upstream-diffs.md @@ -59,6 +59,7 @@ No conflicts expected unless upstream touches the same field mapping block. - `backend/server/api/auth/revocation_cache.go` - `backend/server/api/auth/revocation_cache_test.go` - `backend/server/api/auth/auth_test.go` +- `config-ui/src/utils/request.ts` (401 interceptor; skip plugin `/test` so remote credential failures do not redirect to `/login`) - `env.example` (OIDC/auth env var documentation) **Reason:** Upstream DevLake has no user authentication. This fork adds full OIDC login @@ -299,6 +300,7 @@ tables in the same slice. - `backend/plugins/jira/models/migrationscripts/20260907_add_oauth2_credentials.go` - `backend/plugins/jira/models/migrationscripts/register.go` - `backend/plugins/jira/api/connection_api.go` +- `backend/plugins/jira/api/connection_api_test.go` - `backend/plugins/jira/tasks/api_client.go` - `backend/plugins/jira/token/token_provider.go` - `backend/plugins/jira/token/round_tripper.go` From d946c40294ef49466c1d74f781c07198cc498276 Mon Sep 17 00:00:00 2001 From: fmuntean Date: Wed, 9 Sep 2026 19:50:38 +0200 Subject: [PATCH 04/21] fix(jira): harden OAuth2 token refresh against review findings Clear authFunc when the refresh round tripper is installed so collection workers do not race on oauthToken. Validate CloudId, restore request bodies on 401 retry, and stop echoing raw token-endpoint bodies. Upstream-Status: Pending Co-Authored-By: Cursor Grok 4.6 Co-authored-by: Cursor --- backend/plugins/jira/api/connection_api.go | 8 +- backend/plugins/jira/models/connection.go | 20 ++++- .../plugins/jira/models/connection_test.go | 19 ++++ backend/plugins/jira/models/oauth.go | 28 ++++-- backend/plugins/jira/models/oauth_test.go | 2 + backend/plugins/jira/tasks/api_client.go | 4 + backend/plugins/jira/token/round_tripper.go | 27 ++++-- .../plugins/jira/token/token_provider_test.go | 88 +++++++++++++++++++ 8 files changed, 176 insertions(+), 20 deletions(-) diff --git a/backend/plugins/jira/api/connection_api.go b/backend/plugins/jira/api/connection_api.go index 6bcad630c60..7ac31294df3 100644 --- a/backend/plugins/jira/api/connection_api.go +++ b/backend/plugins/jira/api/connection_api.go @@ -41,7 +41,11 @@ type JiraTestConnResponse struct { } func testConnection(ctx context.Context, connection models.JiraConn) (*JiraTestConnResponse, errors.Error) { - if connection.IsOAuth2() || vld != nil { + if connection.IsOAuth2() { + if err := connection.ValidateConnection(&connection, vld); err != nil { + return nil, err + } + } else if vld != nil { if err := connection.ValidateConnection(&connection, vld); err != nil { return nil, err } @@ -243,7 +247,7 @@ func jiraHTTPErrorDetail(res *http.Response) string { return "" } defer res.Body.Close() - raw, err := io.ReadAll(res.Body) + raw, err := io.ReadAll(io.LimitReader(res.Body, 4096)) if err != nil { return "" } diff --git a/backend/plugins/jira/models/connection.go b/backend/plugins/jira/models/connection.go index 01214a7518d..33289adb3e5 100644 --- a/backend/plugins/jira/models/connection.go +++ b/backend/plugins/jira/models/connection.go @@ -20,6 +20,7 @@ package models import ( "fmt" "net/http" + "regexp" "strings" "time" @@ -37,6 +38,10 @@ const ( AUTH_METHOD_OAUTH2 = "OAuth2" ) +// cloudIDPattern allows Atlassian Cloud IDs (UUIDs) and test fixtures such as "cloud-1". +// It rejects path separators and URL metacharacters so CloudId cannot change the gateway path. +var cloudIDPattern = regexp.MustCompile(`^[a-zA-Z0-9-]{1,64}$`) + type EpicResponse struct { Id int Title string @@ -80,9 +85,17 @@ func (jc *JiraConn) IsOAuth2() bool { return jc.AuthMethod == AUTH_METHOD_OAUTH2 } +func sanitizedCloudID(cloudId string) string { + cloudId = strings.TrimSpace(cloudId) + if !cloudIDPattern.MatchString(cloudId) { + return "" + } + return cloudId +} + // GatewayEndpoint returns the Atlassian API gateway base URL for this cloud ID. func (jc *JiraConn) GatewayEndpoint() string { - cloudId := strings.TrimSpace(jc.CloudId) + cloudId := sanitizedCloudID(jc.CloudId) if cloudId == "" { return "" } @@ -131,10 +144,13 @@ func (jc *JiraConn) SetupAuthentication(req *http.Request) errors.Error { // the shared oneof=BasicAuth AccessToken AppKey constraint. func (jc *JiraConn) ValidateConnection(connection interface{}, v *validator.Validate) errors.Error { if jc.IsOAuth2() { - jc.ApplyGatewayEndpoint() if strings.TrimSpace(jc.ClientId) == "" || strings.TrimSpace(jc.ClientSecret) == "" || strings.TrimSpace(jc.CloudId) == "" { return errors.BadInput.New("clientId, clientSecret and cloudId are required for OAuth2") } + if sanitizedCloudID(jc.CloudId) == "" { + return errors.BadInput.New("cloudId must contain only letters, digits, and hyphens") + } + jc.ApplyGatewayEndpoint() if jc.Endpoint == "" { return errors.BadInput.New("cloudId is required for OAuth2") } diff --git a/backend/plugins/jira/models/connection_test.go b/backend/plugins/jira/models/connection_test.go index c55db79a84e..a1fad3e6dca 100644 --- a/backend/plugins/jira/models/connection_test.go +++ b/backend/plugins/jira/models/connection_test.go @@ -40,6 +40,15 @@ func TestGatewayEndpoint(t *testing.T) { jc.CloudId = "" assert.Equal(t, "", jc.GatewayEndpoint()) + + jc.CloudId = "../evil" + assert.Equal(t, "", jc.GatewayEndpoint()) + + jc.CloudId = "foo/bar" + assert.Equal(t, "", jc.GatewayEndpoint()) + + jc.CloudId = "foo?x=1" + assert.Equal(t, "", jc.GatewayEndpoint()) } func TestApplyGatewayEndpoint(t *testing.T) { @@ -75,6 +84,16 @@ func TestValidateConnectionOAuth2(t *testing.T) { err = missing.ValidateConnection(missing, v) require.Error(t, err) assert.Contains(t, err.Error(), "clientId, clientSecret and cloudId are required") + + invalid := &JiraConn{ + ClientId: "id", + ClientSecret: "secret", + CloudId: "../evil", + } + invalid.AuthMethod = AUTH_METHOD_OAUTH2 + err = invalid.ValidateConnection(invalid, v) + require.Error(t, err) + assert.Contains(t, err.Error(), "cloudId must contain only letters, digits, and hyphens") } func TestValidateConnectionOAuth2DoesNotUseMultiAuthOneOf(t *testing.T) { diff --git a/backend/plugins/jira/models/oauth.go b/backend/plugins/jira/models/oauth.go index 87efdcfcfc0..eaf6993882f 100644 --- a/backend/plugins/jira/models/oauth.go +++ b/backend/plugins/jira/models/oauth.go @@ -36,6 +36,7 @@ const ( AtlassianOAuthTokenURL = "https://auth.atlassian.com/oauth/token" defaultTokenTimeout = 10 * time.Second defaultTokenTTL = 3600 * time.Second + maxOAuthResponseBytes = 4096 ) // NewOAuthHTTPClient returns an HTTP client for Atlassian token requests. @@ -89,17 +90,12 @@ func (jc *JiraConn) MintOAuthAccessToken(httpClient *http.Client) errors.Error { } defer resp.Body.Close() - body, err := io.ReadAll(resp.Body) + body, err := io.ReadAll(io.LimitReader(resp.Body, maxOAuthResponseBytes)) if err != nil { return errors.Convert(err) } if resp.StatusCode != http.StatusOK { - bodyStr := string(body) - const maxBodySnippet = 512 - if len(bodyStr) > maxBodySnippet { - bodyStr = bodyStr[:maxBodySnippet] + "…" - } - return errors.Default.New(fmt.Sprintf("failed to mint oauth2 access token: %d, body: %s", resp.StatusCode, bodyStr)) + return errors.Default.New(fmt.Sprintf("failed to mint oauth2 access token: %d: %s", resp.StatusCode, oauthErrorDetail(body))) } var result struct { @@ -137,3 +133,21 @@ func (jc *JiraConn) PrepareApiClient(_ plugin.ApiClient) errors.Error { } return jc.MintOAuthAccessToken(httpClient) } + +func oauthErrorDetail(body []byte) string { + var payload struct { + Error string `json:"error"` + ErrorDescription string `json:"error_description"` + } + if json.Unmarshal(body, &payload) == nil { + switch { + case payload.Error != "" && payload.ErrorDescription != "": + return payload.Error + ": " + payload.ErrorDescription + case payload.Error != "": + return payload.Error + case payload.ErrorDescription != "": + return payload.ErrorDescription + } + } + return "unexpected token endpoint response" +} diff --git a/backend/plugins/jira/models/oauth_test.go b/backend/plugins/jira/models/oauth_test.go index 556da1d1106..c4e4f3d3575 100644 --- a/backend/plugins/jira/models/oauth_test.go +++ b/backend/plugins/jira/models/oauth_test.go @@ -89,4 +89,6 @@ func TestMintOAuthAccessTokenHTTPError(t *testing.T) { err := jc.MintOAuthAccessToken(server.Client()) require.Error(t, err) assert.Contains(t, err.Error(), "401") + assert.Contains(t, err.Error(), "invalid_client") + assert.NotContains(t, err.Error(), `"error"`) } diff --git a/backend/plugins/jira/tasks/api_client.go b/backend/plugins/jira/tasks/api_client.go index d00244c3b54..447a513a453 100644 --- a/backend/plugins/jira/tasks/api_client.go +++ b/backend/plugins/jira/tasks/api_client.go @@ -49,6 +49,10 @@ func NewJiraApiClient(taskCtx plugin.TaskContext, connection *models.JiraConnect baseTransport = http.DefaultTransport } apiClient.GetClient().Transport = token.NewRefreshRoundTripper(baseTransport, tp) + // RefreshRoundTripper is the sole Authorization setter. Clearing authFunc + // avoids unsynchronized oauthToken reads in SetupAuthentication while + // TokenProvider remints on other worker goroutines. + apiClient.SetAuthFunction(nil) logger.Info("Installed oauth2 token refresh round tripper for Jira connection %d", connection.ID) } diff --git a/backend/plugins/jira/token/round_tripper.go b/backend/plugins/jira/token/round_tripper.go index 8277559438b..b0a5027868c 100644 --- a/backend/plugins/jira/token/round_tripper.go +++ b/backend/plugins/jira/token/round_tripper.go @@ -40,6 +40,7 @@ func NewRefreshRoundTripper(base http.RoundTripper, tp *TokenProvider) *RefreshR } } +// RoundTrip implements http.RoundTripper and remints the access token once on 401. func (rt *RefreshRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { return rt.roundTripWithRetry(req, false) } @@ -50,8 +51,10 @@ func (rt *RefreshRoundTripper) roundTripWithRetry(req *http.Request, refreshAtte return nil, err } - reqClone := req.Clone(req.Context()) - reqClone.Header.Set("Authorization", "Bearer "+token) + reqClone, cloneErr := cloneRequestWithBearer(req, token) + if cloneErr != nil { + return nil, cloneErr + } resp, reqErr := rt.base.RoundTrip(reqClone) if reqErr != nil { @@ -65,15 +68,21 @@ func (rt *RefreshRoundTripper) roundTripWithRetry(req *http.Request, refreshAtte return nil, err } - newToken, err := rt.tokenProvider.GetToken() + return rt.roundTripWithRetry(req, true) + } + + return resp, nil +} + +func cloneRequestWithBearer(req *http.Request, token string) (*http.Request, error) { + reqClone := req.Clone(req.Context()) + if req.GetBody != nil { + body, err := req.GetBody() if err != nil { return nil, err } - - reqRetry := req.Clone(req.Context()) - reqRetry.Header.Set("Authorization", "Bearer "+newToken) - return rt.roundTripWithRetry(reqRetry, true) + reqClone.Body = body } - - return resp, nil + reqClone.Header.Set("Authorization", "Bearer "+token) + return reqClone, nil } diff --git a/backend/plugins/jira/token/token_provider_test.go b/backend/plugins/jira/token/token_provider_test.go index bef2cbde5d8..80d49aa7ae6 100644 --- a/backend/plugins/jira/token/token_provider_test.go +++ b/backend/plugins/jira/token/token_provider_test.go @@ -22,6 +22,7 @@ import ( "io" "net/http" "net/http/httptest" + "strings" "sync" "testing" "time" @@ -190,6 +191,93 @@ func TestRoundTripper401Refresh(t *testing.T) { assert.Equal(t, "new-token", conn.OAuthAccessToken()) } +// TestRoundTripper401RetryRestoresBody: fake Jira 401s Bearer old-token, the +// round tripper remints via the token server, and retries with new-token. +// Both attempts must still send the original POST body. +func TestRoundTripper401RetryRestoresBody(t *testing.T) { + // Token endpoint: ForceRefresh POSTs here and gets new-token. + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "new-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + conn.SetOAuthAccessToken("old-token", time.Now().Add(10*time.Minute)) + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + + var bodies []string + base := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, readErr := io.ReadAll(req.Body) + require.NoError(t, readErr) + bodies = append(bodies, string(body)) + if req.Header.Get("Authorization") == "Bearer old-token" { + return &http.Response{ + StatusCode: http.StatusUnauthorized, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + } + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + }) + + rt := NewRefreshRoundTripper(base, tp) + req, reqErr := http.NewRequest(http.MethodPost, "https://example.com/rest", strings.NewReader(`{"ok":true}`)) + require.NoError(t, reqErr) + req.Header.Set("Content-Type", "application/json") + + resp, tripErr := rt.RoundTrip(req) + require.NoError(t, tripErr) + assert.Equal(t, http.StatusOK, resp.StatusCode) + // bodies[0] = first POST (old-token, 401); bodies[1] = retry (new-token, 200) + require.Len(t, bodies, 2) + assert.Equal(t, `{"ok":true}`, bodies[0]) + assert.Equal(t, `{"ok":true}`, bodies[1]) +} + +// TestRoundTripperPersistent401: fake Jira 401s even after remint. The round +// tripper must retry once, then return that 401 (no infinite loop). +func TestRoundTripperPersistent401(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "new-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + conn.SetOAuthAccessToken("old-token", time.Now().Add(10*time.Minute)) + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + + apiCalls := 0 + base := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + apiCalls++ + return &http.Response{ + StatusCode: http.StatusUnauthorized, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + }) + + rt := NewRefreshRoundTripper(base, tp) + req, reqErr := http.NewRequest(http.MethodGet, "https://example.com/rest", nil) + require.NoError(t, reqErr) + + resp, tripErr := rt.RoundTrip(req) + require.NoError(t, tripErr) + assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) + assert.Equal(t, 2, apiCalls) +} + type roundTripperFunc func(*http.Request) (*http.Response, error) func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { From 49f3b58a28d3e4ddf82743ae68991a69a517fa08 Mon Sep 17 00:00:00 2001 From: fmuntean Date: Thu, 10 Sep 2026 12:12:42 +0200 Subject: [PATCH 05/21] fix(jira): replay request bodies on OAuth 401 retry without GetBody Snapshot the original body when GetBody is missing so a reminted token retry does not send an empty POST. Also drop the redundant gateway and endpoint checks from Test Connection validation. Upstream-Status: Pending Co-Authored-By: Cursor Grok 4.6 Co-authored-by: Cursor --- backend/plugins/jira/api/connection_api.go | 9 +--- backend/plugins/jira/models/connection.go | 5 +- backend/plugins/jira/token/round_tripper.go | 29 +++++++++++ .../plugins/jira/token/token_provider_test.go | 52 +++++++++++++++++++ 4 files changed, 83 insertions(+), 12 deletions(-) diff --git a/backend/plugins/jira/api/connection_api.go b/backend/plugins/jira/api/connection_api.go index 7ac31294df3..198be0a13e8 100644 --- a/backend/plugins/jira/api/connection_api.go +++ b/backend/plugins/jira/api/connection_api.go @@ -41,17 +41,10 @@ type JiraTestConnResponse struct { } func testConnection(ctx context.Context, connection models.JiraConn) (*JiraTestConnResponse, errors.Error) { - if connection.IsOAuth2() { + if connection.IsOAuth2() || vld != nil { if err := connection.ValidateConnection(&connection, vld); err != nil { return nil, err } - } else if vld != nil { - if err := connection.ValidateConnection(&connection, vld); err != nil { - return nil, err - } - } - if connection.IsOAuth2() { - connection.ApplyGatewayEndpoint() } // test connection apiClient, err := api.NewApiClientFromConnection(ctx, basicRes, &connection) diff --git a/backend/plugins/jira/models/connection.go b/backend/plugins/jira/models/connection.go index 33289adb3e5..578ac3395a0 100644 --- a/backend/plugins/jira/models/connection.go +++ b/backend/plugins/jira/models/connection.go @@ -134,7 +134,7 @@ func (jc *JiraConn) SetupAuthentication(req *http.Request) errors.Error { if token == "" { return errors.Unauthorized.New("oauth2 access token is missing") } - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) + req.Header.Set("Authorization", "Bearer "+token) return nil } return jc.MultiAuth.SetupAuthenticationForConnection(jc, req) @@ -151,9 +151,6 @@ func (jc *JiraConn) ValidateConnection(connection interface{}, v *validator.Vali return errors.BadInput.New("cloudId must contain only letters, digits, and hyphens") } jc.ApplyGatewayEndpoint() - if jc.Endpoint == "" { - return errors.BadInput.New("cloudId is required for OAuth2") - } if conn, ok := connection.(*JiraConnection); ok && strings.TrimSpace(conn.Name) == "" { return errors.BadInput.New("name is required") } diff --git a/backend/plugins/jira/token/round_tripper.go b/backend/plugins/jira/token/round_tripper.go index b0a5027868c..a3051d8984b 100644 --- a/backend/plugins/jira/token/round_tripper.go +++ b/backend/plugins/jira/token/round_tripper.go @@ -18,6 +18,8 @@ limitations under the License. package token import ( + "bytes" + "io" "net/http" ) @@ -75,6 +77,9 @@ func (rt *RefreshRoundTripper) roundTripWithRetry(req *http.Request, refreshAtte } func cloneRequestWithBearer(req *http.Request, token string) (*http.Request, error) { + if err := ensureGetBody(req); err != nil { + return nil, err + } reqClone := req.Clone(req.Context()) if req.GetBody != nil { body, err := req.GetBody() @@ -86,3 +91,27 @@ func cloneRequestWithBearer(req *http.Request, token string) (*http.Request, err reqClone.Header.Set("Authorization", "Bearer "+token) return reqClone, nil } + +// ensureGetBody snapshots the body when GetBody is missing so a 401 retry +// can re-send it. http.NewRequest already sets GetBody for *bytes.Reader and +// *strings.Reader; collectors that pass an arbitrary io.Reader would otherwise +// retry with an empty body. +func ensureGetBody(req *http.Request) error { + if req.GetBody != nil || req.Body == nil || req.Body == http.NoBody { + return nil + } + buf, err := io.ReadAll(req.Body) + _ = req.Body.Close() + if err != nil { + return err + } + req.GetBody = func() (io.ReadCloser, error) { + return io.NopCloser(bytes.NewReader(buf)), nil + } + req.Body, err = req.GetBody() + if err != nil { + return err + } + req.ContentLength = int64(len(buf)) + return nil +} diff --git a/backend/plugins/jira/token/token_provider_test.go b/backend/plugins/jira/token/token_provider_test.go index 80d49aa7ae6..c149451fb10 100644 --- a/backend/plugins/jira/token/token_provider_test.go +++ b/backend/plugins/jira/token/token_provider_test.go @@ -242,6 +242,58 @@ func TestRoundTripper401RetryRestoresBody(t *testing.T) { assert.Equal(t, `{"ok":true}`, bodies[1]) } +// TestRoundTripper401RetryRestoresBodyWithoutGetBody covers collectors that +// attach an io.Reader without http.NewRequest setting GetBody. +func TestRoundTripper401RetryRestoresBodyWithoutGetBody(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "new-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + conn := oauthConn(server.URL) + conn.SetOAuthAccessToken("old-token", time.Now().Add(10*time.Minute)) + tp, err := NewTokenProvider(conn, nil) + require.NoError(t, err) + + var bodies []string + base := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + body, readErr := io.ReadAll(req.Body) + require.NoError(t, readErr) + bodies = append(bodies, string(body)) + if req.Header.Get("Authorization") == "Bearer old-token" { + return &http.Response{ + StatusCode: http.StatusUnauthorized, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + } + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(http.NoBody), + Request: req, + }, nil + }) + + rt := NewRefreshRoundTripper(base, tp) + req, reqErr := http.NewRequest(http.MethodPost, "https://example.com/rest", nil) + require.NoError(t, reqErr) + payload := `{"ok":true}` + req.Body = io.NopCloser(strings.NewReader(payload)) + req.GetBody = nil + req.ContentLength = int64(len(payload)) + req.Header.Set("Content-Type", "application/json") + + resp, tripErr := rt.RoundTrip(req) + require.NoError(t, tripErr) + assert.Equal(t, http.StatusOK, resp.StatusCode) + require.Len(t, bodies, 2) + assert.Equal(t, payload, bodies[0]) + assert.Equal(t, payload, bodies[1]) +} + // TestRoundTripperPersistent401: fake Jira 401s even after remint. The round // tripper must retry once, then return that 401 (no infinite loop). func TestRoundTripperPersistent401(t *testing.T) { From 19c0a5115bae112ce6c55acc7d41af3bdf9a61c7 Mon Sep 17 00:00:00 2001 From: fmuntean Date: Thu, 10 Sep 2026 13:30:53 +0200 Subject: [PATCH 06/21] fix(jira): raise OAuth token response size limit for large JWTs A 4KiB cap truncated Atlassian token JSON when many scopes were granted, so Test Connection failed with unexpected end of JSON input. Keep a 64KiB DoS guard and fail clearly on empty or oversized bodies. Upstream-Status: Pending Co-Authored-By: Cursor Grok 4.6 Co-authored-by: Cursor --- backend/plugins/jira/models/oauth.go | 14 +++++++--- backend/plugins/jira/models/oauth_test.go | 31 +++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/backend/plugins/jira/models/oauth.go b/backend/plugins/jira/models/oauth.go index eaf6993882f..4ce9339cd4b 100644 --- a/backend/plugins/jira/models/oauth.go +++ b/backend/plugins/jira/models/oauth.go @@ -36,7 +36,9 @@ const ( AtlassianOAuthTokenURL = "https://auth.atlassian.com/oauth/token" defaultTokenTimeout = 10 * time.Second defaultTokenTTL = 3600 * time.Second - maxOAuthResponseBytes = 4096 + // Atlassian access tokens are JWTs; with many scopes the JSON easily + // exceeds 4KiB. Keep a cap as a DoS guard, not a typical-token size. + maxOAuthResponseBytes = 64 * 1024 ) // NewOAuthHTTPClient returns an HTTP client for Atlassian token requests. @@ -90,13 +92,19 @@ func (jc *JiraConn) MintOAuthAccessToken(httpClient *http.Client) errors.Error { } defer resp.Body.Close() - body, err := io.ReadAll(io.LimitReader(resp.Body, maxOAuthResponseBytes)) + body, err := io.ReadAll(io.LimitReader(resp.Body, maxOAuthResponseBytes+1)) if err != nil { return errors.Convert(err) } + if len(body) > maxOAuthResponseBytes { + return errors.Default.New("oauth2 token response exceeded size limit") + } if resp.StatusCode != http.StatusOK { return errors.Default.New(fmt.Sprintf("failed to mint oauth2 access token: %d: %s", resp.StatusCode, oauthErrorDetail(body))) } + if len(strings.TrimSpace(string(body))) == 0 { + return errors.Default.New("oauth2 token endpoint returned an empty body") + } var result struct { AccessToken string `json:"access_token"` @@ -104,7 +112,7 @@ func (jc *JiraConn) MintOAuthAccessToken(httpClient *http.Client) errors.Error { TokenType string `json:"token_type"` } if err := json.Unmarshal(body, &result); err != nil { - return errors.Convert(err) + return errors.Default.Wrap(err, fmt.Sprintf("decoding oauth2 token response (%d bytes)", len(body))) } if result.AccessToken == "" { return errors.Default.New("empty oauth2 access token returned") diff --git a/backend/plugins/jira/models/oauth_test.go b/backend/plugins/jira/models/oauth_test.go index c4e4f3d3575..947f5dd3fe3 100644 --- a/backend/plugins/jira/models/oauth_test.go +++ b/backend/plugins/jira/models/oauth_test.go @@ -22,6 +22,7 @@ import ( "io" "net/http" "net/http/httptest" + "strings" "testing" "time" @@ -92,3 +93,33 @@ func TestMintOAuthAccessTokenHTTPError(t *testing.T) { assert.Contains(t, err.Error(), "invalid_client") assert.NotContains(t, err.Error(), `"error"`) } + +func TestMintOAuthAccessTokenAcceptsLargeJWT(t *testing.T) { + token := strings.Repeat("a", 8000) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": token, + "expires_in": 3600, + "token_type": "Bearer", + "scope": strings.Repeat("read:jira-work ", 50), + })) + })) + defer server.Close() + + jc := &JiraConn{OAuthTokenURL: server.URL} + err := jc.MintOAuthAccessToken(server.Client()) + require.NoError(t, err) + assert.Equal(t, token, jc.OAuthAccessToken()) +} + +func TestMintOAuthAccessTokenEmptyBody(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + jc := &JiraConn{OAuthTokenURL: server.URL} + err := jc.MintOAuthAccessToken(server.Client()) + require.Error(t, err) + assert.Contains(t, err.Error(), "empty body") +} From ee3a0cdaf7ce1c1a49ede04debf8eff2b4e50211 Mon Sep 17 00:00:00 2001 From: fmuntean Date: Thu, 10 Sep 2026 14:37:00 +0200 Subject: [PATCH 07/21] fix(jira): avoid gosec G101 false positive on Atlassian OAuth URL Rename AtlassianOAuthTokenURL so gosec does not treat the public auth.atlassian.com endpoint as a hardcoded credential. Upstream-Status: Pending Co-Authored-By: Cursor Grok 4.6 Co-authored-by: Cursor --- backend/plugins/jira/models/oauth.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/plugins/jira/models/oauth.go b/backend/plugins/jira/models/oauth.go index 4ce9339cd4b..2dcf5657194 100644 --- a/backend/plugins/jira/models/oauth.go +++ b/backend/plugins/jira/models/oauth.go @@ -32,8 +32,8 @@ import ( ) const ( - // AtlassianOAuthTokenURL is the token endpoint for Jira Cloud service-account OAuth 2.0. - AtlassianOAuthTokenURL = "https://auth.atlassian.com/oauth/token" + // atlassianOAuthEndpoint is the public Atlassian OAuth 2.0 client-credentials endpoint. + atlassianOAuthEndpoint = "https://auth.atlassian.com/oauth/token" defaultTokenTimeout = 10 * time.Second defaultTokenTTL = 3600 * time.Second // Atlassian access tokens are JWTs; with many scopes the JSON easily @@ -62,7 +62,7 @@ func (jc *JiraConn) tokenURL() string { if jc.OAuthTokenURL != "" { return jc.OAuthTokenURL } - return AtlassianOAuthTokenURL + return atlassianOAuthEndpoint } // MintOAuthAccessToken exchanges client_id/client_secret for a Bearer access token. From 2f0d7182b4156439d0d1047360bc4f0234adddcc Mon Sep 17 00:00:00 2001 From: Rafaela Soares Date: Thu, 10 Sep 2026 14:17:02 +0100 Subject: [PATCH 08/21] fix(pluginhelper): avoid duplicating graphql query errors in logs Co-authored-by: Cursor --- backend/helpers/pluginhelper/api/graphql_collector.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/helpers/pluginhelper/api/graphql_collector.go b/backend/helpers/pluginhelper/api/graphql_collector.go index 3b97e07b4a6..6dd75f36631 100644 --- a/backend/helpers/pluginhelper/api/graphql_collector.go +++ b/backend/helpers/pluginhelper/api/graphql_collector.go @@ -274,7 +274,7 @@ func (collector *GraphqlCollector) fetchAsync(reqData *GraphqlRequestData, handl collector.checkError(err) } else { msg := formatGraphqlQueryFailure(err, variables) - logger.Error(err, "%s", msg) + logger.Error(nil, "%s", msg) collector.checkError(errors.Default.New(msg)) } return From e493d16ae79e805da29c7ebb7ce696dbb2ef634c Mon Sep 17 00:00:00 2001 From: fmuntean Date: Fri, 11 Sep 2026 11:03:32 +0200 Subject: [PATCH 09/21] fix(jira): keep OAuth token cache on TokenProvider Collection token state now lives under TokenProvider's mutex, and 401 retries snapshot the body onto clones so RoundTrip does not mutate the original request. Upstream-Status: Pending Co-Authored-By: Cursor --- backend/plugins/jira/models/oauth.go | 30 ++++---- backend/plugins/jira/models/oauth_test.go | 39 +++++++--- backend/plugins/jira/tasks/api_client.go | 4 +- backend/plugins/jira/token/round_tripper.go | 71 ++++++++++++------- backend/plugins/jira/token/token_provider.go | 31 +++++--- .../plugins/jira/token/token_provider_test.go | 51 +++++++++---- 6 files changed, 152 insertions(+), 74 deletions(-) diff --git a/backend/plugins/jira/models/oauth.go b/backend/plugins/jira/models/oauth.go index 2dcf5657194..c1f86107543 100644 --- a/backend/plugins/jira/models/oauth.go +++ b/backend/plugins/jira/models/oauth.go @@ -66,9 +66,9 @@ func (jc *JiraConn) tokenURL() string { } // MintOAuthAccessToken exchanges client_id/client_secret for a Bearer access token. -func (jc *JiraConn) MintOAuthAccessToken(httpClient *http.Client) errors.Error { +func (jc *JiraConn) MintOAuthAccessToken(httpClient *http.Client) (string, time.Time, errors.Error) { if httpClient == nil { - return errors.Default.New("oauth http client is required") + return "", time.Time{}, errors.Default.New("oauth http client is required") } form := url.Values{} @@ -81,29 +81,29 @@ func (jc *JiraConn) MintOAuthAccessToken(httpClient *http.Client) errors.Error { req, err := http.NewRequestWithContext(ctx, http.MethodPost, jc.tokenURL(), strings.NewReader(form.Encode())) if err != nil { - return errors.Convert(err) + return "", time.Time{}, errors.Convert(err) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Accept", "application/json") resp, err := httpClient.Do(req) if err != nil { - return errors.Default.Wrap(err, "failed to request oauth2 access token") + return "", time.Time{}, errors.Default.Wrap(err, "failed to request oauth2 access token") } defer resp.Body.Close() body, err := io.ReadAll(io.LimitReader(resp.Body, maxOAuthResponseBytes+1)) if err != nil { - return errors.Convert(err) + return "", time.Time{}, errors.Convert(err) } if len(body) > maxOAuthResponseBytes { - return errors.Default.New("oauth2 token response exceeded size limit") + return "", time.Time{}, errors.Default.New("oauth2 token response exceeded size limit") } if resp.StatusCode != http.StatusOK { - return errors.Default.New(fmt.Sprintf("failed to mint oauth2 access token: %d: %s", resp.StatusCode, oauthErrorDetail(body))) + return "", time.Time{}, errors.Default.New(fmt.Sprintf("failed to mint oauth2 access token: %d: %s", resp.StatusCode, oauthErrorDetail(body))) } if len(strings.TrimSpace(string(body))) == 0 { - return errors.Default.New("oauth2 token endpoint returned an empty body") + return "", time.Time{}, errors.Default.New("oauth2 token endpoint returned an empty body") } var result struct { @@ -112,18 +112,17 @@ func (jc *JiraConn) MintOAuthAccessToken(httpClient *http.Client) errors.Error { TokenType string `json:"token_type"` } if err := json.Unmarshal(body, &result); err != nil { - return errors.Default.Wrap(err, fmt.Sprintf("decoding oauth2 token response (%d bytes)", len(body))) + return "", time.Time{}, errors.Default.Wrap(err, fmt.Sprintf("decoding oauth2 token response (%d bytes)", len(body))) } if result.AccessToken == "" { - return errors.Default.New("empty oauth2 access token returned") + return "", time.Time{}, errors.Default.New("empty oauth2 access token returned") } ttl := time.Duration(result.ExpiresIn) * time.Second if ttl <= 0 { ttl = defaultTokenTTL } - jc.SetOAuthAccessToken(result.AccessToken, time.Now().Add(ttl)) - return nil + return result.AccessToken, time.Now().Add(ttl), nil } // PrepareApiClient mints an OAuth 2.0 access token so subsequent requests can use Bearer auth. @@ -139,7 +138,12 @@ func (jc *JiraConn) PrepareApiClient(_ plugin.ApiClient) errors.Error { if err != nil { return err } - return jc.MintOAuthAccessToken(httpClient) + token, expiresAt, err := jc.MintOAuthAccessToken(httpClient) + if err != nil { + return err + } + jc.SetOAuthAccessToken(token, expiresAt) + return nil } func oauthErrorDetail(body []byte) string { diff --git a/backend/plugins/jira/models/oauth_test.go b/backend/plugins/jira/models/oauth_test.go index 947f5dd3fe3..325c5d6f42a 100644 --- a/backend/plugins/jira/models/oauth_test.go +++ b/backend/plugins/jira/models/oauth_test.go @@ -56,15 +56,14 @@ func TestMintOAuthAccessToken(t *testing.T) { } jc.AuthMethod = AUTH_METHOD_OAUTH2 - err := jc.MintOAuthAccessToken(server.Client()) + token, expiresAt, err := jc.MintOAuthAccessToken(server.Client()) require.NoError(t, err) assert.Equal(t, "application/x-www-form-urlencoded", gotContentType) assert.Equal(t, "client_credentials", gotGrant) assert.Equal(t, "cid", gotID) assert.Equal(t, "csecret", gotSecret) - assert.Equal(t, "minted-token", jc.OAuthAccessToken()) - require.NotNil(t, jc.OAuthAccessTokenExpiresAt()) - assert.True(t, jc.OAuthAccessTokenExpiresAt().After(time.Now().Add(50*time.Minute))) + assert.Equal(t, "minted-token", token) + assert.True(t, expiresAt.After(time.Now().Add(50*time.Minute))) } func TestMintOAuthAccessTokenRejectsEmptyToken(t *testing.T) { @@ -74,7 +73,7 @@ func TestMintOAuthAccessTokenRejectsEmptyToken(t *testing.T) { defer server.Close() jc := &JiraConn{OAuthTokenURL: server.URL} - err := jc.MintOAuthAccessToken(server.Client()) + _, _, err := jc.MintOAuthAccessToken(server.Client()) require.Error(t, err) assert.Contains(t, err.Error(), "empty oauth2 access token") } @@ -87,7 +86,7 @@ func TestMintOAuthAccessTokenHTTPError(t *testing.T) { defer server.Close() jc := &JiraConn{OAuthTokenURL: server.URL} - err := jc.MintOAuthAccessToken(server.Client()) + _, _, err := jc.MintOAuthAccessToken(server.Client()) require.Error(t, err) assert.Contains(t, err.Error(), "401") assert.Contains(t, err.Error(), "invalid_client") @@ -107,9 +106,9 @@ func TestMintOAuthAccessTokenAcceptsLargeJWT(t *testing.T) { defer server.Close() jc := &JiraConn{OAuthTokenURL: server.URL} - err := jc.MintOAuthAccessToken(server.Client()) + got, _, err := jc.MintOAuthAccessToken(server.Client()) require.NoError(t, err) - assert.Equal(t, token, jc.OAuthAccessToken()) + assert.Equal(t, token, got) } func TestMintOAuthAccessTokenEmptyBody(t *testing.T) { @@ -119,7 +118,29 @@ func TestMintOAuthAccessTokenEmptyBody(t *testing.T) { defer server.Close() jc := &JiraConn{OAuthTokenURL: server.URL} - err := jc.MintOAuthAccessToken(server.Client()) + _, _, err := jc.MintOAuthAccessToken(server.Client()) require.Error(t, err) assert.Contains(t, err.Error(), "empty body") } + +func TestPrepareApiClientStoresTokenOnConn(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + require.NoError(t, json.NewEncoder(w).Encode(map[string]interface{}{ + "access_token": "test-conn-token", + "expires_in": 3600, + })) + })) + defer server.Close() + + jc := &JiraConn{ + ClientId: "cid", + ClientSecret: "csecret", + CloudId: "cloud-1", + OAuthTokenURL: server.URL, + } + jc.AuthMethod = AUTH_METHOD_OAUTH2 + + require.NoError(t, jc.PrepareApiClient(nil)) + assert.Equal(t, "test-conn-token", jc.OAuthAccessToken()) + require.NotNil(t, jc.OAuthAccessTokenExpiresAt()) +} diff --git a/backend/plugins/jira/tasks/api_client.go b/backend/plugins/jira/tasks/api_client.go index 447a513a453..81ad689ad73 100644 --- a/backend/plugins/jira/tasks/api_client.go +++ b/backend/plugins/jira/tasks/api_client.go @@ -49,9 +49,7 @@ func NewJiraApiClient(taskCtx plugin.TaskContext, connection *models.JiraConnect baseTransport = http.DefaultTransport } apiClient.GetClient().Transport = token.NewRefreshRoundTripper(baseTransport, tp) - // RefreshRoundTripper is the sole Authorization setter. Clearing authFunc - // avoids unsynchronized oauthToken reads in SetupAuthentication while - // TokenProvider remints on other worker goroutines. + // RoundTripper sets Authorization; do not also run SetupAuthentication. apiClient.SetAuthFunction(nil) logger.Info("Installed oauth2 token refresh round tripper for Jira connection %d", connection.ID) } diff --git a/backend/plugins/jira/token/round_tripper.go b/backend/plugins/jira/token/round_tripper.go index a3051d8984b..212fd2b4eac 100644 --- a/backend/plugins/jira/token/round_tripper.go +++ b/backend/plugins/jira/token/round_tripper.go @@ -19,10 +19,15 @@ package token import ( "bytes" + "fmt" "io" "net/http" ) +// maxRetryBodyBytes caps how much of a request body is buffered so a 401 +// retry can re-send it. Collection is almost entirely GET; this is a DoS guard. +const maxRetryBodyBytes = int64(1 << 20) + // RefreshRoundTripper automatically remints OAuth 2.0 client-credentials tokens. // On 401 the round tripper will: // - Force a refresh of the access token via the TokenProvider @@ -35,6 +40,7 @@ type RefreshRoundTripper struct { tokenProvider *TokenProvider } +// NewRefreshRoundTripper wraps base with a round tripper that automatically remints the OAuth 2.0 token on 401 responses. func NewRefreshRoundTripper(base http.RoundTripper, tp *TokenProvider) *RefreshRoundTripper { return &RefreshRoundTripper{ base: base, @@ -43,17 +49,23 @@ func NewRefreshRoundTripper(base http.RoundTripper, tp *TokenProvider) *RefreshR } // RoundTrip implements http.RoundTripper and remints the access token once on 401. +// It may consume and close req.Body (per the RoundTripper contract) so a retry can +// re-send the payload; it does not otherwise mutate req. func (rt *RefreshRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - return rt.roundTripWithRetry(req, false) + replay, err := snapshotRequestBody(req) + if err != nil { + return nil, err + } + return rt.roundTripWithRetry(req, replay, false) } -func (rt *RefreshRoundTripper) roundTripWithRetry(req *http.Request, refreshAttempted bool) (*http.Response, error) { +func (rt *RefreshRoundTripper) roundTripWithRetry(req *http.Request, replay bodyReplay, refreshAttempted bool) (*http.Response, error) { token, err := rt.tokenProvider.GetToken() if err != nil { return nil, err } - reqClone, cloneErr := cloneRequestWithBearer(req, token) + reqClone, cloneErr := cloneRequestWithBearer(req, token, replay) if cloneErr != nil { return nil, cloneErr } @@ -70,48 +82,55 @@ func (rt *RefreshRoundTripper) roundTripWithRetry(req *http.Request, refreshAtte return nil, err } - return rt.roundTripWithRetry(req, true) + return rt.roundTripWithRetry(req, replay, true) } return resp, nil } -func cloneRequestWithBearer(req *http.Request, token string) (*http.Request, error) { - if err := ensureGetBody(req); err != nil { - return nil, err - } +type bodyReplay struct { + getBody func() (io.ReadCloser, error) + length int64 +} + +func cloneRequestWithBearer(req *http.Request, token string, replay bodyReplay) (*http.Request, error) { reqClone := req.Clone(req.Context()) - if req.GetBody != nil { - body, err := req.GetBody() + if replay.getBody != nil { + body, err := replay.getBody() if err != nil { return nil, err } reqClone.Body = body + reqClone.GetBody = replay.getBody + if replay.length >= 0 { + reqClone.ContentLength = replay.length + } } reqClone.Header.Set("Authorization", "Bearer "+token) return reqClone, nil } -// ensureGetBody snapshots the body when GetBody is missing so a 401 retry -// can re-send it. http.NewRequest already sets GetBody for *bytes.Reader and -// *strings.Reader; collectors that pass an arbitrary io.Reader would otherwise -// retry with an empty body. -func ensureGetBody(req *http.Request) error { - if req.GetBody != nil || req.Body == nil || req.Body == http.NoBody { - return nil +// snapshotRequestBody returns a replayable body for clones. When GetBody is +// already set, the original request is left untouched. Otherwise the original +// Body is consumed and closed (allowed by http.RoundTripper) and a GetBody is +// synthesized for clones only. +func snapshotRequestBody(req *http.Request) (bodyReplay, error) { + if req.GetBody != nil { + return bodyReplay{getBody: req.GetBody, length: req.ContentLength}, nil + } + if req.Body == nil || req.Body == http.NoBody { + return bodyReplay{}, nil } - buf, err := io.ReadAll(req.Body) + buf, err := io.ReadAll(io.LimitReader(req.Body, maxRetryBodyBytes+1)) _ = req.Body.Close() if err != nil { - return err + return bodyReplay{}, err } - req.GetBody = func() (io.ReadCloser, error) { - return io.NopCloser(bytes.NewReader(buf)), nil + if int64(len(buf)) > maxRetryBodyBytes { + return bodyReplay{}, fmt.Errorf("request body exceeded %d-byte retry snapshot limit", maxRetryBodyBytes) } - req.Body, err = req.GetBody() - if err != nil { - return err + getBody := func() (io.ReadCloser, error) { + return io.NopCloser(bytes.NewReader(buf)), nil } - req.ContentLength = int64(len(buf)) - return nil + return bodyReplay{getBody: getBody, length: int64(len(buf))}, nil } diff --git a/backend/plugins/jira/token/token_provider.go b/backend/plugins/jira/token/token_provider.go index 15449a54100..2ee44751fae 100644 --- a/backend/plugins/jira/token/token_provider.go +++ b/backend/plugins/jira/token/token_provider.go @@ -37,6 +37,8 @@ type TokenProvider struct { httpClient *http.Client logger log.Logger mu sync.Mutex + token string + expiresAt *time.Time } // NewTokenProvider creates a TokenProvider that uses a dedicated HTTP client for token requests. @@ -54,6 +56,7 @@ func NewTokenProvider(conn *models.JiraConn, logger log.Logger) (*TokenProvider, }, nil } +// GetToken returns a valid OAuth 2.0 access token, minting a new one if the cached token is absent or near expiry. func (tp *TokenProvider) GetToken() (string, errors.Error) { tp.mu.Lock() defer tp.mu.Unlock() @@ -61,8 +64,8 @@ func (tp *TokenProvider) GetToken() (string, errors.Error) { if tp.needsRefresh() { if tp.logger != nil { expiresStr := "unknown" - if exp := tp.conn.OAuthAccessTokenExpiresAt(); exp != nil { - expiresStr = exp.Format(time.RFC3339) + if tp.expiresAt != nil { + expiresStr = tp.expiresAt.Format(time.RFC3339) } tp.logger.Info("Proactive oauth2 token refresh triggered (token expires at %s)", expiresStr) } @@ -70,25 +73,35 @@ func (tp *TokenProvider) GetToken() (string, errors.Error) { return "", err } } - return tp.conn.OAuthAccessToken(), nil + return tp.token, nil } func (tp *TokenProvider) needsRefresh() bool { - if tp.conn.OAuthAccessToken() == "" { + if tp.token == "" { return true } - expiresAt := tp.conn.OAuthAccessTokenExpiresAt() - if expiresAt == nil { + if tp.expiresAt == nil { return false } - return time.Now().Add(DefaultRefreshBuffer).After(*expiresAt) + return time.Now().Add(DefaultRefreshBuffer).After(*tp.expiresAt) } func (tp *TokenProvider) refreshToken() errors.Error { if tp.logger != nil { tp.logger.Info("Minting Jira oauth2 access token via client_credentials") } - return tp.conn.MintOAuthAccessToken(tp.httpClient) + token, expiresAt, err := tp.conn.MintOAuthAccessToken(tp.httpClient) + if err != nil { + return err + } + tp.cacheToken(token, expiresAt) + return nil +} + +func (tp *TokenProvider) cacheToken(token string, expiresAt time.Time) { + tp.token = token + expiry := expiresAt + tp.expiresAt = &expiry } // ForceRefresh remints the access token if the current token is still equal to oldToken. @@ -96,7 +109,7 @@ func (tp *TokenProvider) ForceRefresh(oldToken string) errors.Error { tp.mu.Lock() defer tp.mu.Unlock() - if tp.conn.OAuthAccessToken() != oldToken { + if tp.token != oldToken { if tp.logger != nil { tp.logger.Info("Skipping reactive oauth2 token refresh — token already changed by another goroutine") } diff --git a/backend/plugins/jira/token/token_provider_test.go b/backend/plugins/jira/token/token_provider_test.go index c149451fb10..95ac4fe6feb 100644 --- a/backend/plugins/jira/token/token_provider_test.go +++ b/backend/plugins/jira/token/token_provider_test.go @@ -44,18 +44,22 @@ func oauthConn(tokenURL string) *models.JiraConn { return jc } +func seedToken(tp *TokenProvider, token string, ttl time.Duration) { + tp.cacheToken(token, time.Now().Add(ttl)) +} + func TestNeedsRefresh(t *testing.T) { tp := &TokenProvider{conn: oauthConn("")} assert.True(t, tp.needsRefresh(), "empty token should refresh") - tp.conn.SetOAuthAccessToken("tok", time.Now().Add(10*time.Minute)) + seedToken(tp, "tok", 10*time.Minute) assert.False(t, tp.needsRefresh()) - tp.conn.SetOAuthAccessToken("tok", time.Now().Add(1*time.Minute)) + seedToken(tp, "tok", 1*time.Minute) assert.True(t, tp.needsRefresh()) - tp.conn.SetOAuthAccessToken("tok", time.Now().Add(-1*time.Minute)) + seedToken(tp, "tok", -1*time.Minute) assert.True(t, tp.needsRefresh()) } @@ -72,10 +76,9 @@ func TestGetTokenMintsWhenExpired(t *testing.T) { defer server.Close() conn := oauthConn(server.URL) - conn.SetOAuthAccessToken("stale", time.Now().Add(-time.Minute)) - tp, err := NewTokenProvider(conn, nil) require.NoError(t, err) + seedToken(tp, "stale", -time.Minute) token, err := tp.GetToken() require.NoError(t, err) @@ -94,17 +97,17 @@ func TestForceRefreshSkipsIfTokenChanged(t *testing.T) { defer server.Close() conn := oauthConn(server.URL) - conn.SetOAuthAccessToken("current", time.Now().Add(time.Hour)) tp, err := NewTokenProvider(conn, nil) require.NoError(t, err) + seedToken(tp, "current", time.Hour) require.NoError(t, tp.ForceRefresh("stale-old-token")) assert.Equal(t, 0, calls) - assert.Equal(t, "current", conn.OAuthAccessToken()) + assert.Equal(t, "current", tp.token) require.NoError(t, tp.ForceRefresh("current")) assert.Equal(t, 1, calls) - assert.Equal(t, "new-token", conn.OAuthAccessToken()) + assert.Equal(t, "new-token", tp.token) } func TestGetTokenConcurrency(t *testing.T) { @@ -154,10 +157,9 @@ func TestRoundTripper401Refresh(t *testing.T) { defer server.Close() conn := oauthConn(server.URL) - conn.SetOAuthAccessToken("old-token", time.Now().Add(10*time.Minute)) - tp, err := NewTokenProvider(conn, nil) require.NoError(t, err) + seedToken(tp, "old-token", 10*time.Minute) apiCalls := 0 base := roundTripperFunc(func(req *http.Request) (*http.Response, error) { @@ -188,7 +190,7 @@ func TestRoundTripper401Refresh(t *testing.T) { require.NoError(t, tripErr) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, 2, apiCalls) - assert.Equal(t, "new-token", conn.OAuthAccessToken()) + assert.Equal(t, "new-token", tp.token) } // TestRoundTripper401RetryRestoresBody: fake Jira 401s Bearer old-token, the @@ -205,9 +207,9 @@ func TestRoundTripper401RetryRestoresBody(t *testing.T) { defer server.Close() conn := oauthConn(server.URL) - conn.SetOAuthAccessToken("old-token", time.Now().Add(10*time.Minute)) tp, err := NewTokenProvider(conn, nil) require.NoError(t, err) + seedToken(tp, "old-token", 10*time.Minute) var bodies []string base := roundTripperFunc(func(req *http.Request) (*http.Response, error) { @@ -254,9 +256,9 @@ func TestRoundTripper401RetryRestoresBodyWithoutGetBody(t *testing.T) { defer server.Close() conn := oauthConn(server.URL) - conn.SetOAuthAccessToken("old-token", time.Now().Add(10*time.Minute)) tp, err := NewTokenProvider(conn, nil) require.NoError(t, err) + seedToken(tp, "old-token", 10*time.Minute) var bodies []string base := roundTripperFunc(func(req *http.Request) (*http.Response, error) { @@ -292,6 +294,7 @@ func TestRoundTripper401RetryRestoresBodyWithoutGetBody(t *testing.T) { require.Len(t, bodies, 2) assert.Equal(t, payload, bodies[0]) assert.Equal(t, payload, bodies[1]) + assert.Nil(t, req.GetBody, "RoundTrip must not mutate the original request") } // TestRoundTripperPersistent401: fake Jira 401s even after remint. The round @@ -306,9 +309,9 @@ func TestRoundTripperPersistent401(t *testing.T) { defer server.Close() conn := oauthConn(server.URL) - conn.SetOAuthAccessToken("old-token", time.Now().Add(10*time.Minute)) tp, err := NewTokenProvider(conn, nil) require.NoError(t, err) + seedToken(tp, "old-token", 10*time.Minute) apiCalls := 0 base := roundTripperFunc(func(req *http.Request) (*http.Response, error) { @@ -330,6 +333,26 @@ func TestRoundTripperPersistent401(t *testing.T) { assert.Equal(t, 2, apiCalls) } +func TestRoundTripperRejectsOversizedBody(t *testing.T) { + tp := &TokenProvider{conn: oauthConn("")} + seedToken(tp, "tok", time.Hour) + rt := NewRefreshRoundTripper(roundTripperFunc(func(*http.Request) (*http.Response, error) { + t.Fatal("must not send an oversized body") + return nil, nil + }), tp) + + payload := strings.Repeat("a", int(maxRetryBodyBytes)+1) + req, err := http.NewRequest(http.MethodPost, "https://example.com/rest", nil) + require.NoError(t, err) + req.Body = io.NopCloser(strings.NewReader(payload)) + req.GetBody = nil + req.ContentLength = int64(len(payload)) + + _, tripErr := rt.RoundTrip(req) + require.Error(t, tripErr) + assert.Contains(t, tripErr.Error(), "retry snapshot limit") +} + type roundTripperFunc func(*http.Request) (*http.Response, error) func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { From 2becebe4366daa4514677267d44570ba001ef380 Mon Sep 17 00:00:00 2001 From: fmuntean Date: Fri, 11 Sep 2026 11:44:39 +0200 Subject: [PATCH 10/21] fix(ci): upload Codecov from Ubuntu instead of lake-builder apt-get install gpg inside mericodev/lake-builder fails because Debian 11 bullseye-security InRelease expired after LTS EOL. Keep tests in the builder image and hand coverage to a follow-on ubuntu-latest job that already has gpg. Upstream-Status: N/A Co-Authored-By: Cursor Grok 4.6 Co-authored-by: Cursor --- .github/workflows/test-e2e-coverage.yml | 4 --- .github/workflows/test.yml | 35 ++++++++++++++++++++----- docs/upstream-diffs.md | 19 ++++++++++++++ 3 files changed, 47 insertions(+), 11 deletions(-) diff --git a/.github/workflows/test-e2e-coverage.yml b/.github/workflows/test-e2e-coverage.yml index 02378e2716c..cb0e3ac80ab 100644 --- a/.github/workflows/test-e2e-coverage.yml +++ b/.github/workflows/test-e2e-coverage.yml @@ -120,10 +120,6 @@ jobs: echo "Go e2e coverage generated:" go tool cover -func=./e2e-coverage/go-coverage.out | tail -1 - - name: Install gpg for Codecov - if: always() - run: sudo apt-get update -qq && sudo apt-get install -y -qq gpg > /dev/null 2>&1 - - name: Upload Go e2e coverage to Codecov if: always() uses: codecov/codecov-action@0fb7174895f61a3b6b78fc075e0cd60383518dac # v5 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a4b293835ec..80844def325 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -42,8 +42,6 @@ jobs: os: [ubuntu-latest] runs-on: ${{ matrix.os }} container: mericodev/lake-builder:latest - permissions: - id-token: write steps: - name: Checkout code uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 @@ -83,16 +81,40 @@ jobs: run: | cd backend COVERAGE_OUTPUT_DIR=python/coverage make unit-test-python || echo "::warning::Python unit tests had failures (coverage still uploaded)" - - name: Install gpg for Codecov - if: always() - run: apt-get update -qq && apt-get install -y -qq gpg > /dev/null 2>&1 - name: Custom plugins coverage if: always() run: | cd backend bash scripts/coverage-custom-plugins.sh - - name: Upload Go coverage to Codecov + - name: Upload coverage artifacts if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: unit-coverage + if-no-files-found: warn + retention-days: 1 + path: | + backend/coverage-custom-plugins.out + backend/python/coverage/ + + # Fork-only: upload from the Ubuntu runner so codecov-action has gpg + upload-coverage: + needs: test + if: always() && needs.test.result != 'cancelled' + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + steps: + - name: Checkout code + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + - name: Download coverage artifacts + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: unit-coverage + path: . + if-no-artifact-found: warn + - name: Upload Go coverage to Codecov uses: codecov/codecov-action@0fb7174895f61a3b6b78fc075e0cd60383518dac # v5 with: use_oidc: true @@ -100,7 +122,6 @@ jobs: files: backend/coverage-custom-plugins.out fail_ci_if_error: false - name: Upload Python coverage to Codecov - if: always() uses: codecov/codecov-action@0fb7174895f61a3b6b78fc075e0cd60383518dac # v5 with: use_oidc: true diff --git a/docs/upstream-diffs.md b/docs/upstream-diffs.md index a1ea0a831f7..d7e153f0edd 100644 --- a/docs/upstream-diffs.md +++ b/docs/upstream-diffs.md @@ -311,3 +311,22 @@ fix. **Rebase notes:** Touches `fetchAsync` data-error / transport-error handling and `Execute` worker-error logging. Watch for upstream changes around `IgnoreQueryErrors` / `isIgnorableGraphqlQueryError`. + +## ci: unit-test Codecov upload on a separate Ubuntu job + +**Files:** +- `.github/workflows/test.yml` + +**Reason:** Fork-only Codecov upload for owned plugins. `codecov-action` needs +`gpg`, which is not in `mericodev/lake-builder` (Debian 11 / Bullseye). Installing +it via `apt-get` in that container fails because `bullseye-security` InRelease +expired after Debian 11 LTS EOL (2026-08-31). Tests stay in `lake-builder`; +coverage artifacts are uploaded from a follow-on `ubuntu-latest` job with OIDC. + +**Upstream status:** N/A — upstream `test.yml` has no Codecov steps. +**Upstream PR:** none — not applicable +**Owner:** @fmuntean + +**Rebase notes:** Keep the `test` job aligned with upstream (container, unit +tests). Re-apply the `Custom plugins coverage` / artifact upload steps and the +`upload-coverage` job after upstream workflow changes. From e6fce34f47ef4bf4140567aae9fcd9606f374620 Mon Sep 17 00:00:00 2001 From: fmuntean Date: Fri, 11 Sep 2026 12:55:28 +0200 Subject: [PATCH 11/21] fix(jira): skip PrepareApiClient on OAuth2 collection Collection builds the HTTP client without FromConnection so the round tripper is the only minter and Authorization setter. Upstream-Status: Pending Co-Authored-By: Cursor --- backend/plugins/jira/tasks/api_client.go | 35 +++++++++++++++--------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/backend/plugins/jira/tasks/api_client.go b/backend/plugins/jira/tasks/api_client.go index 81ad689ad73..f088117156d 100644 --- a/backend/plugins/jira/tasks/api_client.go +++ b/backend/plugins/jira/tasks/api_client.go @@ -29,29 +29,38 @@ import ( ) func NewJiraApiClient(taskCtx plugin.TaskContext, connection *models.JiraConnection) (*api.ApiAsyncClient, errors.Error) { + var apiClient *api.ApiClient + var err errors.Error if connection.IsOAuth2() { connection.ApplyGatewayEndpoint() - } - // create synchronize api client so we can calculate api rate limit dynamically - apiClient, err := api.NewApiClientFromConnection(taskCtx.GetContext(), taskCtx, connection) - if err != nil { - return nil, err - } - - if connection.IsOAuth2() { + apiClient, err = api.NewApiClient( + taskCtx.GetContext(), + connection.GetEndpoint(), + nil, + 0, + connection.GetProxy(), + taskCtx, + ) + if err != nil { + return nil, err + } logger := taskCtx.GetLogger() - tp, terr := token.NewTokenProvider(&connection.JiraConn, logger) - if terr != nil { - return nil, terr + var tp *token.TokenProvider + tp, err = token.NewTokenProvider(&connection.JiraConn, logger) + if err != nil { + return nil, err } baseTransport := apiClient.GetClient().Transport if baseTransport == nil { baseTransport = http.DefaultTransport } apiClient.GetClient().Transport = token.NewRefreshRoundTripper(baseTransport, tp) - // RoundTripper sets Authorization; do not also run SetupAuthentication. - apiClient.SetAuthFunction(nil) logger.Info("Installed oauth2 token refresh round tripper for Jira connection %d", connection.ID) + } else { + apiClient, err = api.NewApiClientFromConnection(taskCtx.GetContext(), taskCtx, connection) + if err != nil { + return nil, err + } } // create rate limit calculator From aeb730f74ebc82380799d5d0f00661f06ed460cf Mon Sep 17 00:00:00 2001 From: fmuntean Date: Fri, 11 Sep 2026 14:05:28 +0200 Subject: [PATCH 12/21] fix(ci): tighten unit-test token and restore coverage artifact paths Keep the lake-builder test job at contents: read instead of inheriting default write scopes. Download artifacts into backend/ so Codecov finds files after upload-artifact v4 strips the shared parent directory. Upstream-Status: N/A Co-Authored-By: Cursor Grok 4.6 Co-authored-by: Cursor --- .github/workflows/test.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 80844def325..bf1f9ec5023 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -42,6 +42,8 @@ jobs: os: [ubuntu-latest] runs-on: ${{ matrix.os }} container: mericodev/lake-builder:latest + permissions: + contents: read steps: - name: Checkout code uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 @@ -112,7 +114,7 @@ jobs: uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: name: unit-coverage - path: . + path: backend if-no-artifact-found: warn - name: Upload Go coverage to Codecov uses: codecov/codecov-action@0fb7174895f61a3b6b78fc075e0cd60383518dac # v5 From a17bf767e729743ad5d856739c524d00b0c3b428 Mon Sep 17 00:00:00 2001 From: fmuntean Date: Fri, 11 Sep 2026 15:03:38 +0200 Subject: [PATCH 13/21] fix(ci): upload python coverage even when go fails --- .github/workflows/test.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index bf1f9ec5023..080cd65397b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -124,6 +124,7 @@ jobs: files: backend/coverage-custom-plugins.out fail_ci_if_error: false - name: Upload Python coverage to Codecov + if: always() uses: codecov/codecov-action@0fb7174895f61a3b6b78fc075e0cd60383518dac # v5 with: use_oidc: true From 8e27c3eaa96cf8c16425683d2c567fc99e9ac8e8 Mon Sep 17 00:00:00 2001 From: csontosati Date: Tue, 15 Sep 2026 18:19:49 +0200 Subject: [PATCH 14/21] feat(e2e): add codecov plugin Playwright flow for CI coverage Adds a full lifecycle e2e spec and wires it into test-e2e-coverage so the codecov plugin is exercised under the e2e-go coverport flag. COVERPORT-364 Co-authored-by: Cursor --- .github/workflows/test-e2e-coverage.yml | 16 +- backend/plugins/codecov/AGENTS.md | 10 +- .../skills/pr-definition-of-done/SKILL.md | 2 +- e2e/codecov-flow.spec.ts | 229 ++++++++++++++++++ e2e/package.json | 3 +- env.example | 8 + 6 files changed, 264 insertions(+), 4 deletions(-) create mode 100644 e2e/codecov-flow.spec.ts diff --git a/.github/workflows/test-e2e-coverage.yml b/.github/workflows/test-e2e-coverage.yml index cb0e3ac80ab..3cde9b6a2dd 100644 --- a/.github/workflows/test-e2e-coverage.yml +++ b/.github/workflows/test-e2e-coverage.yml @@ -96,10 +96,24 @@ jobs: npm ci npx playwright install chromium --with-deps + - name: Verify Codecov e2e prerequisites + if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository + run: | + if [ -z "${{ secrets.CODECOV_TOKEN }}" ]; then + echo "::error::CODECOV_TOKEN GitHub Actions secret is required for codecov e2e tests" + exit 1 + fi + - name: Run Playwright e2e tests + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + CODECOV_ORG: konflux-ci + CODECOV_SERVICE: github + CODECOV_ENDPOINT: https://api.codecov.io + CODECOV_REPO: konflux-ci/coverport run: | cd e2e - npx playwright test basic-flow.spec.ts + npx playwright test basic-flow.spec.ts codecov-flow.spec.ts --timeout=900000 - name: Collect Go e2e coverage via coverport if: always() diff --git a/backend/plugins/codecov/AGENTS.md b/backend/plugins/codecov/AGENTS.md index 87b4ae1ae43..5722a8e6ac7 100644 --- a/backend/plugins/codecov/AGENTS.md +++ b/backend/plugins/codecov/AGENTS.md @@ -12,7 +12,15 @@ golangci-lint run ./plugins/codecov/... # lint Single-file verification: `go vet ./plugins/codecov/...` -No e2e tests yet — coverage data is validated via unit tests and manual Grafana dashboard checks. +Playwright e2e (requires `CODECOV_TOKEN`): + +```bash +cd e2e +export CODECOV_TOKEN=... # Codecov API token for konflux-ci org +npm run test:codecov +``` + +Exercises the full plugin lifecycle (connection → scope → blueprint → pipeline with all 13 subtasks). Runs in CI via `.github/workflows/test-e2e-coverage.yml` to drive Go coverage under the `e2e-go` flag. ## Layout diff --git a/backend/plugins/codecov/skills/pr-definition-of-done/SKILL.md b/backend/plugins/codecov/skills/pr-definition-of-done/SKILL.md index 46551a3d258..f1da097b805 100644 --- a/backend/plugins/codecov/skills/pr-definition-of-done/SKILL.md +++ b/backend/plugins/codecov/skills/pr-definition-of-done/SKILL.md @@ -36,6 +36,6 @@ description: >- ## CI Behavior - **Unit tests**: Run on PRs via `make unit-test-go` (excludes `e2e/` and `models/` packages) -- **E2E tests**: No e2e tests exist yet; adding `codecov/e2e/` would be auto-discovered by CI +- **E2E tests**: Playwright spec at `e2e/codecov-flow.spec.ts` runs in `test-e2e-coverage` workflow (requires `CODECOV_TOKEN` secret) - **Lint**: Runs only on push to main/tags, not on PRs - Upstream CI also runs `plugins/table_info_test.go` — fails if `GetTablesInfo()` is incomplete diff --git a/e2e/codecov-flow.spec.ts b/e2e/codecov-flow.spec.ts new file mode 100644 index 00000000000..35a3a785596 --- /dev/null +++ b/e2e/codecov-flow.spec.ts @@ -0,0 +1,229 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +import { test, expect, request } from '@playwright/test'; + +const API = 'http://127.0.0.1:8080'; +const TOKEN = process.env.CODECOV_TOKEN; +const ORG = process.env.CODECOV_ORG ?? 'konflux-ci'; +const SERVICE = process.env.CODECOV_SERVICE ?? 'github'; +const ENDPOINT = process.env.CODECOV_ENDPOINT ?? 'https://api.codecov.io'; +const REPO = process.env.CODECOV_REPO ?? 'konflux-ci/coverport'; + +const EXPECTED_SUBTASKS = [ + 'CollectFlags', + 'ConvertFlags', + 'CollectCommits', + 'ExtractCommits', + 'CollectCommitTotals', + 'CollectCommitCoverage', + 'CollectComparison', + 'CollectFlagCoverageTrend', + 'CollectRepoConfig', + 'ConvertComparison', + 'ConvertCoverage', + 'ConvertCommitCoverage', + 'ConvertCoverageTrend', +]; + +const state = { + connectionId: 0, + scopeConfigId: 0, + scopeId: '', + blueprintId: 0, + pipelineId: 0, + remoteRepo: null as Record | null, +}; + +async function cleanupResources() { + const api = await request.newContext({ baseURL: API }); + + if (state.blueprintId) { + await api.delete(`/blueprints/${state.blueprintId}`); + console.log(`Deleted blueprint ${state.blueprintId}`); + } + if (state.scopeId) { + await api.delete( + `/plugins/codecov/connections/${state.connectionId}/scopes/${encodeURIComponent(state.scopeId)}`, + ); + console.log(`Deleted scope ${state.scopeId}`); + } + if (state.scopeConfigId) { + await api.delete( + `/plugins/codecov/connections/${state.connectionId}/scope-configs/${state.scopeConfigId}`, + ); + console.log(`Deleted scope config ${state.scopeConfigId}`); + } + if (state.connectionId) { + await api.delete(`/plugins/codecov/connections/${state.connectionId}`); + console.log(`Deleted connection ${state.connectionId}`); + } +} + +test.describe.serial('Codecov Plugin Full Flow', () => { + test.skip(!process.env.CODECOV_TOKEN, 'CODECOV_TOKEN not set'); + test.setTimeout(900_000); + + test.afterAll(async () => { + if (state.connectionId) { + await cleanupResources(); + console.log('Cleanup complete'); + } + }); + + test('Step 1: Create Connection', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.post('/plugins/codecov/connections', { + data: { + name: `e2e-codecov-${Date.now()}`, + token: TOKEN, + organization: ORG, + service: SERVICE, + endpoint: ENDPOINT, + }, + }); + expect(resp.ok()).toBeTruthy(); + const conn = await resp.json(); + state.connectionId = conn.id; + console.log(`Connection created: id=${state.connectionId}`); + }); + + test('Step 2: Test Connection', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.post(`/plugins/codecov/connections/${state.connectionId}/test`); + const body = await resp.json(); + expect(resp.ok()).toBeTruthy(); + expect(body.success).toBe(true); + console.log('Test connection: OK'); + }); + + test('Step 3: Discover Remote Scopes', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.get(`/plugins/codecov/connections/${state.connectionId}/remote-scopes`); + expect(resp.ok()).toBeTruthy(); + const body = await resp.json(); + + const repo = body.children?.find((c: { fullName: string }) => c.fullName === REPO); + expect(repo, `Repository ${REPO} not found in remote-scopes`).toBeTruthy(); + state.remoteRepo = repo.data; + console.log(`Found remote repo: ${REPO}`); + }); + + test('Step 4: Create Scope Config', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.post( + `/plugins/codecov/connections/${state.connectionId}/scope-configs`, + { data: { name: `e2e-scope-config-${Date.now()}`, entities: ['CODE'] } }, + ); + expect(resp.ok()).toBeTruthy(); + const body = await resp.json(); + state.scopeConfigId = body.id; + console.log(`Scope config created: id=${state.scopeConfigId}`); + }); + + test('Step 5: Add Scope', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.put(`/plugins/codecov/connections/${state.connectionId}/scopes`, { + data: { + data: [{ + ...state.remoteRepo, + scopeConfigId: state.scopeConfigId, + }], + }, + }); + expect(resp.ok()).toBeTruthy(); + const scopes = await resp.json(); + state.scopeId = scopes[0].codecovId; + expect(state.scopeId).toBe(REPO); + console.log(`Scope added: id=${state.scopeId}`); + }); + + test('Step 6: Create Blueprint via API', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.post('/blueprints', { + data: { + name: `e2e-blueprint-${Date.now()}`, + mode: 'NORMAL', + enable: true, + cronConfig: '0 0 * * *', + isManual: true, + connections: [{ + pluginName: 'codecov', + connectionId: state.connectionId, + scopes: [{ scopeId: state.scopeId }], + }], + }, + }); + expect(resp.ok()).toBeTruthy(); + const body = await resp.json(); + state.blueprintId = body.id; + console.log(`Blueprint created: id=${state.blueprintId}`); + }); + + test('Step 7: Trigger Pipeline via API', async () => { + const api = await request.newContext({ baseURL: API }); + const resp = await api.post(`/blueprints/${state.blueprintId}/trigger`, { data: {} }); + expect(resp.ok()).toBeTruthy(); + const body = await resp.json(); + state.pipelineId = body.id; + console.log(`Pipeline triggered: id=${state.pipelineId}`); + }); + + test('Step 8: Wait for Pipeline to Complete', async () => { + const api = await request.newContext({ baseURL: API }); + const maxWait = 900_000; // 15 min — first Codecov collection can be slow + const start = Date.now(); + let status = ''; + + while (Date.now() - start < maxWait) { + const resp = await api.get(`/pipelines/${state.pipelineId}`); + const pipeline = await resp.json(); + status = pipeline.status; + console.log(`Pipeline status: ${status} (${Math.round((Date.now() - start) / 1000)}s)`); + if (['TASK_COMPLETED', 'TASK_FAILED', 'TASK_PARTIAL'].includes(status)) break; + await new Promise((r) => setTimeout(r, 5000)); + } + + const tasksResp = await api.get(`/pipelines/${state.pipelineId}/tasks`); + if (tasksResp.ok()) { + const { tasks } = await tasksResp.json(); + for (const t of tasks || []) { + console.log(` Task ${t.id}: ${t.status}${t.failedSubTask ? ` (failed: ${t.failedSubTask})` : ''}`); + if (t.message) console.log(` Error: ${t.message.substring(0, 300)}`); + } + } + + expect(status).toBe('TASK_COMPLETED'); + }); + + test('Step 9: Verify Pipeline Subtasks', async () => { + const api = await request.newContext({ baseURL: API }); + + const tasksResp = await api.get(`/pipelines/${state.pipelineId}/tasks`); + expect(tasksResp.ok()).toBeTruthy(); + const { tasks } = await tasksResp.json(); + expect(tasks[0].status).toBe('TASK_COMPLETED'); + expect(tasks[0].subtasks).toEqual(EXPECTED_SUBTASKS); + console.log(`Pipeline completed in ${tasks[0].spentSeconds}s with ${tasks[0].subtasks.length} subtasks`); + }); + + test('Step 10: Cleanup', async () => { + await cleanupResources(); + state.connectionId = 0; + console.log('Cleanup complete'); + }); +}); diff --git a/e2e/package.json b/e2e/package.json index 5abf0494f36..a267ec33641 100644 --- a/e2e/package.json +++ b/e2e/package.json @@ -6,7 +6,8 @@ "scripts": { "test": "npx playwright test basic-flow.spec.ts", "test:all": "npx playwright test", - "test:coverage": "npx playwright test basic-flow.spec.ts" + "test:coverage": "npx playwright test basic-flow.spec.ts", + "test:codecov": "npx playwright test codecov-flow.spec.ts --timeout=900000" }, "keywords": [], "author": "", diff --git a/env.example b/env.example index 7eb785d4fb3..9d688f67219 100755 --- a/env.example +++ b/env.example @@ -172,3 +172,11 @@ SESSION_TTL=8h COOKIE_DOMAIN= # Set to false ONLY for local HTTP development. COOKIE_SECURE=true + +# Codecov plugin e2e tests (e2e/codecov-flow.spec.ts) — not used by Docker Compose. +# Export before running: cd e2e && npm run test:codecov +# CODECOV_TOKEN= +# CODECOV_ORG=konflux-ci +# CODECOV_SERVICE=github +# CODECOV_ENDPOINT=https://api.codecov.io +# CODECOV_REPO=konflux-ci/coverport From 8af266a8f2867d86e48255342ebfc1fae3e52af8 Mon Sep 17 00:00:00 2001 From: csontosati Date: Tue, 15 Sep 2026 19:04:00 +0200 Subject: [PATCH 15/21] fix(e2e): address review feedback from fullsend for codecov CI workflow --- .github/workflows/test-e2e-coverage.yml | 4 +++- e2e/codecov-flow.spec.ts | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test-e2e-coverage.yml b/.github/workflows/test-e2e-coverage.yml index 3cde9b6a2dd..1f21ad25781 100644 --- a/.github/workflows/test-e2e-coverage.yml +++ b/.github/workflows/test-e2e-coverage.yml @@ -98,8 +98,10 @@ jobs: - name: Verify Codecov e2e prerequisites if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} run: | - if [ -z "${{ secrets.CODECOV_TOKEN }}" ]; then + if [ -z "$CODECOV_TOKEN" ]; then echo "::error::CODECOV_TOKEN GitHub Actions secret is required for codecov e2e tests" exit 1 fi diff --git a/e2e/codecov-flow.spec.ts b/e2e/codecov-flow.spec.ts index 35a3a785596..8c0a290893b 100644 --- a/e2e/codecov-flow.spec.ts +++ b/e2e/codecov-flow.spec.ts @@ -17,7 +17,7 @@ limitations under the License. import { test, expect, request } from '@playwright/test'; -const API = 'http://127.0.0.1:8080'; +const API = 'http://localhost:8080'; const TOKEN = process.env.CODECOV_TOKEN; const ORG = process.env.CODECOV_ORG ?? 'konflux-ci'; const SERVICE = process.env.CODECOV_SERVICE ?? 'github'; From d3776e247b1403045ed9c5b7064073721ec0467d Mon Sep 17 00:00:00 2001 From: csontosati Date: Wed, 16 Sep 2026 11:22:49 +0200 Subject: [PATCH 16/21] fix(e2e): separating basic-flow from codecov-flow so a missing token only blocks the codecov part, and removing the timout flag from CI --- .github/workflows/test-e2e-coverage.yml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test-e2e-coverage.yml b/.github/workflows/test-e2e-coverage.yml index 1f21ad25781..41f6ccb4fa2 100644 --- a/.github/workflows/test-e2e-coverage.yml +++ b/.github/workflows/test-e2e-coverage.yml @@ -96,6 +96,11 @@ jobs: npm ci npx playwright install chromium --with-deps + - name: Run basic-flow Playwright e2e tests + run: | + cd e2e + npx playwright test basic-flow.spec.ts + - name: Verify Codecov e2e prerequisites if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository env: @@ -106,7 +111,8 @@ jobs: exit 1 fi - - name: Run Playwright e2e tests + - name: Run codecov-flow Playwright e2e tests + if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository env: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} CODECOV_ORG: konflux-ci @@ -115,7 +121,7 @@ jobs: CODECOV_REPO: konflux-ci/coverport run: | cd e2e - npx playwright test basic-flow.spec.ts codecov-flow.spec.ts --timeout=900000 + npx playwright test codecov-flow.spec.ts - name: Collect Go e2e coverage via coverport if: always() From 8f8ba41fdb6e61b3f87cb30158a0e7c9772e5e90 Mon Sep 17 00:00:00 2001 From: Emily Keefe Date: Tue, 22 Sep 2026 08:56:12 -0400 Subject: [PATCH 17/21] chore: initialize fullsend per-repo installation --- .fullsend/config.yaml | 21 +++++++ .github/workflows/fullsend.yaml | 105 ++++++++++++++++++++++--------- .github/workflows/prioritize.yml | 50 +++++++++++++++ 3 files changed, 145 insertions(+), 31 deletions(-) create mode 100644 .fullsend/config.yaml create mode 100644 .github/workflows/prioritize.yml diff --git a/.fullsend/config.yaml b/.fullsend/config.yaml new file mode 100644 index 00000000000..5ad1358c36f --- /dev/null +++ b/.fullsend/config.yaml @@ -0,0 +1,21 @@ +# fullsend per-repo configuration +# https://github.com/fullsend-ai/fullsend +# +# This file configures fullsend for per-repo installation mode. +# See https://fullsend.sh/docs/guides/infrastructure/layered-config-reference +version: "1" +roles: + - fullsend + - triage + - coder + - fix + - review + - prioritize +allowed_remote_resources: + - https://raw.githubusercontent.com/fullsend-ai/fullsend/ + - https://raw.githubusercontent.com/fullsend-ai/agents/ +create_issues: + allow_targets: + repos: + - konflux-ci/devlake + - fullsend-ai/fullsend diff --git a/.github/workflows/fullsend.yaml b/.github/workflows/fullsend.yaml index 51de659901b..310ad8c50ec 100644 --- a/.github/workflows/fullsend.yaml +++ b/.github/workflows/fullsend.yaml @@ -1,64 +1,77 @@ -# lint-workflow-size: max-lines=280 -# fullsend shim workflow (workflow_call mode) -# Routes events to agent workflows in .fullsend via workflow_call. -# No secrets are needed in the enrolled repo — agents fetch scoped tokens -# from the centralized token mint using GitHub OIDC. +# This file is managed by fullsend. Do not edit it directly. +# Upstream: https://github.com/fullsend-ai/fullsend/blob/main/internal/scaffold/fullsend-repo/.github/workflows/fullsend.yaml +--- +# fullsend shim workflow (per-repo installation mode) +# Routes events to agent workflows via reusable-dispatch.yml. +# All agent execution happens in this repo's context — no external +# config repo is needed. # # Security: pull_request_target runs the BASE branch version of this workflow, # preventing PRs from modifying it to exfiltrate credentials. # This shim never checks out PR code, so it is not vulnerable to "pwn request" # attacks. # -# konflux-ci is replaced by reconcile-repos.sh at deploy time. +# Routing: this shim forwards the raw event context to reusable-dispatch.yml, +# which determines the stage and runs the agent inline (ADR 62). +# Adding a new stage requires only a job in reusable-dispatch.yml — zero changes to this repo. # -# Routing: this shim forwards the raw event context to dispatch.yml, which -# determines the stage from event_type + event_action + payload fields. -# Adding a new stage requires only a case branch in dispatch.yml — zero -# changes to enrolled repos. +# Concurrency: per-role cancel-in-progress groups live in reusable-dispatch.yml +# stage jobs with -agent- suffix. Roles operate independently (#2452). name: fullsend -permissions: - actions: write - id-token: write - contents: read - pull-requests: read - on: issues: types: [opened, edited, labeled] issue_comment: types: [created] pull_request_target: - types: [opened, synchronize, ready_for_review, closed] + types: [opened, synchronize, ready_for_review, closed, labeled, unlabeled] pull_request_review: types: [submitted] +permissions: {} + jobs: dispatch: - concurrency: - group: fullsend-dispatch-${{ github.event.issue.number || github.event.pull_request.number }} - cancel-in-progress: false if: >- - github.event_name != 'issue_comment' - || github.event.comment.user.type != 'Bot' - uses: konflux-ci/.fullsend/.github/workflows/dispatch.yml@701e62a9c6f104ed68f8d4085d9c3b8bad3a82e4 # main + (github.event_name != 'pull_request_target' && github.event_name != 'pull_request_review' + || github.event.pull_request.head.ref != 'fullsend/scaffold-install') + && (github.event_name != 'issue_comment' + || (startsWith(github.event.comment.body, '/fs-') + && github.event.comment.user.type != 'Bot')) + permissions: + actions: write + id-token: write + contents: write + issues: write + packages: read + pull-requests: write + uses: fullsend-ai/fullsend/.github/workflows/reusable-dispatch.yml@main with: event_action: ${{ github.event.action }} + install_mode: per-repo + mint_url: ${{ vars.FULLSEND_MINT_URL }} + gcp_region: ${{ vars.FULLSEND_GCP_REGION }} + project_number: ${{ vars.FULLSEND_PROJECT_NUMBER }} + runner_image: ubuntu-24.04 + secrets: + FULLSEND_GCP_WIF_PROVIDER: ${{ secrets.FULLSEND_GCP_WIF_PROVIDER }} + FULLSEND_GCP_PROJECT_ID: ${{ secrets.FULLSEND_GCP_PROJECT_ID }} + OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} + OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }} stop-fix: + # Job-level if: is intentionally coarse — it only screens for the + # /fs-fix-stop command on a PR from a non-bot. The authoritative + # authorization decision (collaborator permission API + PR-author escape + # hatch) is made in the step below, so a maintainer whose author_association + # is not MEMBER (e.g. private org membership) is not filtered out (ADR 0054). if: >- github.event_name == 'issue_comment' && github.event.issue.pull_request && github.event.comment.user.type != 'Bot' && github.event.comment.body == '/fs-fix-stop' - && ( - github.event.comment.author_association == 'OWNER' - || github.event.comment.author_association == 'MEMBER' - || github.event.comment.author_association == 'COLLABORATOR' - || github.event.comment.author_association == 'CONTRIBUTOR' - || github.event.comment.user.login == github.event.issue.user.login - ) - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 permissions: contents: read issues: write @@ -69,7 +82,37 @@ jobs: GH_TOKEN: ${{ github.token }} PR_NUMBER: ${{ github.event.issue.number }} REPO: ${{ github.repository }} + COMMENT_USER_LOGIN: ${{ github.event.comment.user.login }} + ISSUE_USER_LOGIN: ${{ github.event.issue.user.login }} run: | + set -euo pipefail + # ADR 0054: authorize via the collaborator permission API + # (admin|maintain|write), not author_association — the latter grants + # contributor status to anyone with a single merged PR (issue #5421). + # Mirrors has_repo_permission() in dispatch.yml; keep the two in sync. + # The PR author may always stop the fix agent on their own PR. + authorized=false + if [[ -n "$COMMENT_USER_LOGIN" && "$COMMENT_USER_LOGIN" == "$ISSUE_USER_LOGIN" ]]; then + authorized=true + else + if api_err=$(mktemp); then + if role=$(gh api "repos/$REPO/collaborators/$COMMENT_USER_LOGIN/permission" \ + --jq '.role_name' 2>"$api_err"); then + case "$role" in + admin|maintain|write) authorized=true ;; + esac + else + echo "::warning::Permission API call failed for $COMMENT_USER_LOGIN: $(cat "$api_err")" + fi + rm -f "$api_err" + else + echo "::warning::Failed to create temp file for permission check of $COMMENT_USER_LOGIN" + fi + fi + if [[ "$authorized" != "true" ]]; then + echo "::notice::User $COMMENT_USER_LOGIN is not authorized to stop the fix agent (requires write access or PR authorship)" + exit 0 + fi gh label create "fullsend-no-fix" --repo "$REPO" \ --description "Skip bot-triggered fix agent runs" --color "FBCA04" \ --force 2>/dev/null || true diff --git a/.github/workflows/prioritize.yml b/.github/workflows/prioritize.yml new file mode 100644 index 00000000000..332f98eef38 --- /dev/null +++ b/.github/workflows/prioritize.yml @@ -0,0 +1,50 @@ +# This file is managed by fullsend. Do not edit it directly. +# Upstream: https://github.com/fullsend-ai/fullsend/blob/main/internal/scaffold/fullsend-repo/.github/workflows/prioritize.yml +--- +# fullsend-stage: prioritize +name: Prioritize + +permissions: + actions: write + contents: read + id-token: write + issues: write + +on: + workflow_dispatch: + inputs: + event_type: + required: true + type: string + source_repo: + required: true + type: string + event_payload: + required: true + type: string + project_number: + description: GitHub Projects V2 project number for RICE scoring + required: false + type: string + +concurrency: + group: fullsend-prioritize-${{ inputs.source_repo }}-${{ fromJSON(inputs.event_payload).issue.number }} + cancel-in-progress: true + +jobs: + prioritize: + uses: fullsend-ai/fullsend/.github/workflows/reusable-prioritize.yml@main + with: + event_type: ${{ inputs.event_type }} + source_repo: ${{ inputs.source_repo }} + event_payload: ${{ inputs.event_payload }} + mint_url: ${{ vars.FULLSEND_MINT_URL }} + gcp_region: ${{ vars.FULLSEND_GCP_REGION }} + project_number: ${{ inputs.project_number || vars.FULLSEND_PROJECT_NUMBER }} + install_mode: per-repo + runner_image: ubuntu-24.04 + secrets: + FULLSEND_GCP_WIF_PROVIDER: ${{ secrets.FULLSEND_GCP_WIF_PROVIDER }} + FULLSEND_GCP_PROJECT_ID: ${{ secrets.FULLSEND_GCP_PROJECT_ID }} + OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} + OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }} From d5e3026572a0c75db598f5776392e563c0f65ff1 Mon Sep 17 00:00:00 2001 From: Ladislav Lipka Date: Wed, 23 Sep 2026 12:26:09 +0200 Subject: [PATCH 18/21] fix(COVERPORT-419): send service in Codecov Test Connection payload MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Test Connection never sent `service`, so the backend fell back to `github` and non-GitHub Codecov connections (e.g. GitLab Enterprise) were tested against the wrong API path, failing with a misleading "organization not found". Save Connection was unaffected — it sends the full form values. Adds `service` to both test payload builders in `connection-form/index.tsx`, the `test` / `testOld` payload types, and `IConnectionAPI`. Backend needed no change. Entry added to `docs/upstream-diffs.md` since all three files are upstream. Signed-off-by: Ladislav Lipka --- config-ui/src/api/connection/index.ts | 2 ++ .../components/connection-form/index.tsx | 2 ++ config-ui/src/types/connection.ts | 1 + docs/upstream-diffs.md | 22 +++++++++++++++++++ 4 files changed, 27 insertions(+) diff --git a/config-ui/src/api/connection/index.ts b/config-ui/src/api/connection/index.ts index 3cf46ee9063..1f44ac6e687 100644 --- a/config-ui/src/api/connection/index.ts +++ b/config-ui/src/api/connection/index.ts @@ -56,6 +56,7 @@ export const test = ( | 'adminApiKey' | 'organization' | 'organizationId' + | 'service' | 'customHeaders' | 'ciTool' | 'quayOrganization' @@ -85,6 +86,7 @@ export const testOld = ( | 'adminApiKey' | 'organization' | 'organizationId' + | 'service' | 'customHeaders' | 'ciTool' | 'quayOrganization' diff --git a/config-ui/src/plugins/components/connection-form/index.tsx b/config-ui/src/plugins/components/connection-form/index.tsx index d728b17b063..6df3bdabb6c 100644 --- a/config-ui/src/plugins/components/connection-form/index.tsx +++ b/config-ui/src/plugins/components/connection-form/index.tsx @@ -59,6 +59,7 @@ const buildUpdateTestPayload = (connection: any, values: any, customHeaders: ICu dbUrl: isEqual(connection?.dbUrl, values.dbUrl) ? undefined : values.dbUrl, companyId: isEqual(connection?.companyId, values.companyId) ? undefined : values.companyId, organization: isEqual(connection?.organization, values.organization) ? undefined : values.organization, + service: isEqual(connection?.service, values.service) ? undefined : values.service, customHeaders: isEqual(connection?.customHeaders, customHeaders) ? undefined : customHeaders, ciTool: isEqual(connection?.ciTool, values.ciTool) ? undefined : values.ciTool, quayOrganization: isEqual(connection?.quayOrganization, values.quayOrganization) ? undefined : values.quayOrganization, @@ -91,6 +92,7 @@ const buildCreateTestPayload = (initialValues: any, values: any, customHeaders: 'dbUrl', 'companyId', 'organization', + 'service', 'customHeaders', 'ciTool', 'quayOrganization', diff --git a/config-ui/src/types/connection.ts b/config-ui/src/types/connection.ts index bb39fa2e59b..b0db204de59 100644 --- a/config-ui/src/types/connection.ts +++ b/config-ui/src/types/connection.ts @@ -38,6 +38,7 @@ export interface IConnectionAPI { rateLimitPerHour?: number; organization?: string; organizationId?: string; + service?: string; customHeaders?: ICustomHeader[]; ciTool?: string; quayOrganization?: string; diff --git a/docs/upstream-diffs.md b/docs/upstream-diffs.md index d7e153f0edd..fee9e8f79d5 100644 --- a/docs/upstream-diffs.md +++ b/docs/upstream-diffs.md @@ -330,3 +330,25 @@ coverage artifacts are uploaded from a follow-on `ubuntu-latest` job with OIDC. **Rebase notes:** Keep the `test` job aligned with upstream (container, unit tests). Re-apply the `Custom plugins coverage` / artifact upload steps and the `upload-coverage` job after upstream workflow changes. + +## config-ui: connection fields for owned plugins + +**Files:** +- `config-ui/src/plugins/components/connection-form/index.tsx` +- `config-ui/src/api/connection/index.ts` +- `config-ui/src/types/connection.ts` + +**Reason:** The shared connection form whitelists which values reach the backend, +so each owned-plugin field must be listed in `IConnectionAPI`, the `test` / +`testOld` payload `Pick<>`s, and both test-payload builders. Fields added so far: +`service` (codecov); `ciTool`, `quayOrganization`, `githubOrganization`, +`githubToken`, `project`, `junitRegex` (testregistry). Missing a builder is +silent — Save Connection still works while Test Connection drops the field and +the backend falls back to its default (COVERPORT-351). + +**Upstream status:** N/A — these fields belong to fork-only plugins. +**Upstream PR:** none — not applicable +**Owner:** @lipka28 + +**Rebase notes:** The lists are additive; on conflict keep both upstream's fields +and the fork's. From 6a061d70dd12736155cfd369454a5fbb147f1df4 Mon Sep 17 00:00:00 2001 From: Emily Keefe Date: Wed, 23 Sep 2026 14:59:43 -0400 Subject: [PATCH 19/21] chore: update fullsend per-repo installation --- .github/workflows/fullsend.yaml | 2 +- .github/workflows/prioritize.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/fullsend.yaml b/.github/workflows/fullsend.yaml index 310ad8c50ec..9a10f59f3bd 100644 --- a/.github/workflows/fullsend.yaml +++ b/.github/workflows/fullsend.yaml @@ -46,7 +46,7 @@ jobs: issues: write packages: read pull-requests: write - uses: fullsend-ai/fullsend/.github/workflows/reusable-dispatch.yml@main + uses: fullsend-ai/fullsend/.github/workflows/reusable-dispatch.yml@d5f36921ac754705619f38c637ef692873809fbc # v0.43.0 with: event_action: ${{ github.event.action }} install_mode: per-repo diff --git a/.github/workflows/prioritize.yml b/.github/workflows/prioritize.yml index 332f98eef38..3e89e64a5ce 100644 --- a/.github/workflows/prioritize.yml +++ b/.github/workflows/prioritize.yml @@ -33,7 +33,7 @@ concurrency: jobs: prioritize: - uses: fullsend-ai/fullsend/.github/workflows/reusable-prioritize.yml@main + uses: fullsend-ai/fullsend/.github/workflows/reusable-prioritize.yml@d5f36921ac754705619f38c637ef692873809fbc # v0.43.0 with: event_type: ${{ inputs.event_type }} source_repo: ${{ inputs.source_repo }} From 37ddfe21553107ca92b42039d121d093f91653bc Mon Sep 17 00:00:00 2001 From: "konflux-internal-p02[bot]" <170854209+konflux-internal-p02[bot]@users.noreply.github.com> Date: Fri, 25 Sep 2026 10:09:54 +0000 Subject: [PATCH 20/21] build: Konflux Internal p02 update devlake-backend Signed-off-by: konflux-internal-p02[bot] <170854209+konflux-internal-p02[bot]@users.noreply.github.com> --- .tekton/devlake-backend-pull-request.yaml | 594 ++++++++++++++++++++++ .tekton/devlake-backend-push.yaml | 591 +++++++++++++++++++++ 2 files changed, 1185 insertions(+) create mode 100644 .tekton/devlake-backend-pull-request.yaml create mode 100644 .tekton/devlake-backend-push.yaml diff --git a/.tekton/devlake-backend-pull-request.yaml b/.tekton/devlake-backend-pull-request.yaml new file mode 100644 index 00000000000..723edf05af2 --- /dev/null +++ b/.tekton/devlake-backend-pull-request.yaml @@ -0,0 +1,594 @@ +apiVersion: tekton.dev/v1 +kind: PipelineRun +metadata: + annotations: + build.appstudio.openshift.io/repo: https://github.com/RH-DevProd/devlake?rev={{revision}} + build.appstudio.redhat.com/commit_sha: '{{revision}}' + build.appstudio.redhat.com/pull_request_number: '{{pull_request_number}}' + build.appstudio.redhat.com/target_branch: '{{target_branch}}' + pipelinesascode.tekton.dev/cancel-in-progress: "true" + pipelinesascode.tekton.dev/max-keep-runs: "3" + pipelinesascode.tekton.dev/on-cel-expression: event == "pull_request" && target_branch + == "main" + labels: + appstudio.openshift.io/application: devlake + appstudio.openshift.io/component: devlake-backend + pipelines.appstudio.openshift.io/type: build + name: devlake-backend-on-pull-request + namespace: dprod-tenant +spec: + params: + - name: git-url + value: '{{source_url}}' + - name: revision + value: '{{revision}}' + - name: output-image + value: quay.io/redhat-user-workloads/dprod-tenant/devlake-backend:on-pr-{{revision}} + - name: image-expires-after + value: 5d + - name: build-platforms + value: + - linux/x86_64 + - name: dockerfile + value: Containerfile + - name: path-context + value: backend + pipelineSpec: + description: | + This pipeline is ideal for building multi-arch container images from a Containerfile while maintaining trust after pipeline customization. + + _Uses `buildah` to create a multi-platform container image leveraging [trusted artifacts](https://konflux-ci.dev/architecture/ADR/0036-trusted-artifacts.html). It also optionally creates a source image and runs some build-time tests. This pipeline requires that the [multi platform controller](https://github.com/konflux-ci/multi-platform-controller) is deployed and configured on your Konflux instance. Information is shared between tasks using OCI artifacts instead of PVCs. EC will pass the [`trusted_task.trusted`](https://conforma.dev/docs/policy/packages/release_trusted_task.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. + This pipeline is pushed as a Tekton bundle to [quay.io](https://quay.io/repository/konflux-ci/tekton-catalog/pipeline-docker-build-multi-platform-oci-ta?tab=tags)_ + params: + - description: Source Repository URL + name: git-url + type: string + - default: "" + description: Revision of the Source Repository + name: revision + type: string + - description: Fully Qualified Output Image + name: output-image + type: string + - default: . + description: Path to the source code of an application's component from where + to build image. + name: path-context + type: string + - default: Dockerfile + description: Path to the Dockerfile inside the context specified by parameter + path-context + name: dockerfile + type: string + - default: "false" + description: Skip checks against built image + name: skip-checks + type: string + - default: "false" + description: Execute the build with network isolation + name: hermetic + type: string + - default: "" + description: Build dependencies to be prefetched + name: prefetch-input + type: string + - default: "" + description: Image tag expiration time, time values could be something like + 1h, 2d, 3w for hours, days, and weeks, respectively. + name: image-expires-after + type: string + - default: "false" + description: Build a source image. + name: build-source-image + type: string + - default: "true" + description: Add built image into an OCI image index + name: build-image-index + type: string + - default: docker + description: The format for the resulting image's mediaType. Valid values are + oci or docker. + name: buildah-format + type: string + - default: "false" + description: Enable cache proxy configuration + name: enable-cache-proxy + - default: "true" + description: Use the package registry proxy when prefetching dependencies + name: enable-package-registry-proxy + - default: . + description: Target directories in component's source code to scan with SAST + tools. Multiple values should be separated with commas. + name: sast-target-dirs + type: string + - default: [] + description: Array of --build-arg values ("arg=value" strings) for buildah + name: build-args + type: array + - default: "" + description: Path to a file with build arguments for buildah, see https://www.mankier.com/1/buildah-build#--build-arg-file + name: build-args-file + type: string + - default: "false" + description: Whether to enable privileged mode, should be used only with remote + VMs + name: privileged-nested + type: string + - default: "" + description: Sets the image created time and the SOURCE_DATE_EPOCH build argument. + On its own, it does not change file timestamps inside the layers (set rewrite-timestamp + to "true" for that). Leave empty to keep the actual build time. + name: source-date-epoch + type: string + - default: "false" + description: When "true", clamp file modification times in the image layers + to at most source-date-epoch. Does nothing unless source-date-epoch is set. + name: rewrite-timestamp + type: string + - default: "false" + description: When "true", omit the build history (history timestamps, layer + metadata, etc.) from the resulting image. + name: omit-history + type: string + - default: + - linux/x86_64 + description: List of platforms to build the container images on. The available + set of values is determined by the configuration of the multi-platform-controller. + name: build-platforms + type: array + results: + - description: "" + name: IMAGE_URL + value: $(tasks.build-image-index.results.IMAGE_URL) + - description: "" + name: IMAGE_DIGEST + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - description: "" + name: CHAINS-GIT_URL + value: $(tasks.clone-repository.results.url) + - description: "" + name: CHAINS-GIT_COMMIT + value: $(tasks.clone-repository.results.commit) + tasks: + - name: init + params: + - name: enable-cache-proxy + value: $(params.enable-cache-proxy) + taskRef: + params: + - name: name + value: init + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-init:0.4.2@sha256:421003a5c077ecb820460e71637125ec9093d2101c749a32ede28e190283e9db + - name: kind + value: task + resolver: bundles + - name: clone-repository + params: + - name: url + value: $(params.git-url) + - name: revision + value: $(params.revision) + - name: ociStorage + value: $(params.output-image).git + - name: ociArtifactExpiresAfter + value: $(params.image-expires-after) + runAfter: + - init + taskRef: + params: + - name: name + value: git-clone-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.2.4@sha256:df3c42d78223f07b40a84dd29e5c8860d14777ffdf150ea08c738770f51216dc + - name: kind + value: task + resolver: bundles + workspaces: + - name: basic-auth + workspace: git-auth + - name: prefetch-dependencies + params: + - name: input + value: $(params.prefetch-input) + - name: enable-package-registry-proxy + value: $(params.enable-package-registry-proxy) + - name: SOURCE_ARTIFACT + value: $(tasks.clone-repository.results.SOURCE_ARTIFACT) + - name: ociStorage + value: $(params.output-image).prefetch + - name: ociArtifactExpiresAfter + value: $(params.image-expires-after) + runAfter: + - clone-repository + taskRef: + params: + - name: name + value: prefetch-dependencies-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.10.1@sha256:c09c1c3ced67fb8740b2925a7de09c0810d4e8c8f148d41c21ffe37810d85c62 + - name: kind + value: task + resolver: bundles + workspaces: + - name: git-basic-auth + workspace: git-auth + - name: netrc + workspace: netrc + - matrix: + params: + - name: PLATFORM + value: + - $(params.build-platforms) + name: build-images + params: + - name: IMAGE + value: $(params.output-image) + - name: DOCKERFILE + value: $(params.dockerfile) + - name: CONTEXT + value: $(params.path-context) + - name: HERMETIC + value: $(params.hermetic) + - name: PREFETCH_INPUT + value: $(params.prefetch-input) + - name: IMAGE_EXPIRES_AFTER + value: $(params.image-expires-after) + - name: COMMIT_SHA + value: $(tasks.clone-repository.results.commit) + - name: BUILD_ARGS + value: + - $(params.build-args[*]) + - name: BUILD_ARGS_FILE + value: $(params.build-args-file) + - name: PRIVILEGED_NESTED + value: $(params.privileged-nested) + - name: SOURCE_URL + value: $(tasks.clone-repository.results.url) + - name: BUILDAH_FORMAT + value: $(params.buildah-format) + - name: HTTP_PROXY + value: $(tasks.init.results.http-proxy) + - name: NO_PROXY + value: $(tasks.init.results.no-proxy) + - name: SOURCE_DATE_EPOCH + value: $(params.source-date-epoch) + - name: REWRITE_TIMESTAMP + value: $(params.rewrite-timestamp) + - name: OMIT_HISTORY + value: $(params.omit-history) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + - name: CACHI2_ARTIFACT + value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) + - name: IMAGE_APPEND_PLATFORM + value: "true" + runAfter: + - prefetch-dependencies + taskRef: + params: + - name: name + value: buildah-remote-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-buildah-remote-oci-ta:0.10.5@sha256:eb277ec7b44443f0506a60ac940a2e52178d60f17cb0f51a6966daed5b3755de + - name: kind + value: task + resolver: bundles + - name: build-image-index + params: + - name: IMAGE + value: $(params.output-image) + - name: ALWAYS_BUILD_INDEX + value: $(params.build-image-index) + - name: IMAGES + value: + - $(tasks.build-images.results.IMAGE_REF[*]) + - name: BUILDAH_FORMAT + value: $(params.buildah-format) + runAfter: + - build-images + taskRef: + params: + - name: name + value: build-image-index + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.3.1@sha256:cc75f64deecccb1b59e96ac1182665a5342d79c9e22eebff63d26b0f00a4319c + - name: kind + value: task + resolver: bundles + - name: build-source-image + params: + - name: BINARY_IMAGE + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: BINARY_IMAGE_DIGEST + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + - name: CACHI2_ARTIFACT + value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: source-build-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.3@sha256:7c5575ac8e292f27f57716c021ab0324460dc958e73946724c588c5228e5f372 + - name: kind + value: task + resolver: bundles + when: + - input: $(params.build-source-image) + operator: in + values: + - "true" + - name: deprecated-base-image-check + params: + - name: IMAGE_URL + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: IMAGE_DIGEST + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: deprecated-image-check + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.5@sha256:0ccc688a77e9b7b0b8973c132a1e840844137e77f887be4a0bec8893b0776872 + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - matrix: + params: + - name: image-platform + value: + - $(params.build-platforms) + name: clair-scan + params: + - name: image-digest + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: clair-scan + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.3@sha256:f5b4415db9ac1fba3e11d993a617e0b275d1f0ed2fc669b12c400ed848c39174 + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - matrix: + params: + - name: platform + value: + - $(params.build-platforms) + name: ecosystem-cert-preflight-checks + params: + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: ecosystem-cert-preflight-checks + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.2@sha256:c07d2befa8abf48d4a223a5bdf5ea2335e756d4d0bbc422761087c263060aa94 + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - name: sast-snyk-check + params: + - name: image-digest + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: TARGET_DIRS + value: $(params.sast-target-dirs) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + - name: CACHI2_ARTIFACT + value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: sast-snyk-check-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.5@sha256:eba24f5d9f4b18aa71e523b9b3dbcf22982aa4b018824260a090b19dfc9abf6f + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - matrix: + params: + - name: image-arch + value: + - $(params.build-platforms) + name: clamav-scan + params: + - name: image-digest + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: clamav-scan + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.3@sha256:53a02326bfb930ca5ef6bfa7a33acca833d57752f34f3cb79255fe2e25e7d217 + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - name: sast-shell-check + params: + - name: image-digest + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: TARGET_DIRS + value: $(params.sast-target-dirs) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + - name: CACHI2_ARTIFACT + value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: sast-shell-check-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-sast-shell-check-oci-ta:0.1@sha256:61b27e6ad5daba761d41bb37efb790ed98380603fd4fe2f86d156def5bd72ecc + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - name: sast-unicode-check + params: + - name: image-digest + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: TARGET_DIRS + value: $(params.sast-target-dirs) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + - name: CACHI2_ARTIFACT + value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: sast-unicode-check-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-sast-unicode-check-oci-ta:0.4@sha256:eb9d5392f215cb8b52b16382098cac4885b1e6cd989f88ebd83fdb234d283eb9 + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - name: apply-tags + params: + - name: IMAGE_URL + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: IMAGE_DIGEST + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: apply-tags + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.3@sha256:3ab844157eccd68e95e4852adc06c3c4ea674edb7865a474b0a898227f2893d6 + - name: kind + value: task + resolver: bundles + - name: push-dockerfile + params: + - name: IMAGE + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: IMAGE_DIGEST + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: DOCKERFILE + value: $(params.dockerfile) + - name: CONTEXT + value: $(params.path-context) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: push-dockerfile-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.3.1@sha256:5a6cbebd89e5bc163b38231859767f7f6a0dd66cf1333699574379f062731183 + - name: kind + value: task + resolver: bundles + - name: rpms-signature-scan + params: + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: image-digest + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: rpms-signature-scan + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-rpms-signature-scan:0.2@sha256:f110c53fd58cab7ac6e47d472bb801d49e2f584eb31837db9d611e11b3862a3d + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + workspaces: + - name: git-auth + optional: true + - name: netrc + optional: true + taskRunSpecs: + - pipelineTaskName: build-images + stepSpecs: + - name: build + computeResources: + requests: + memory: 16Gi + cpu: "6" + limits: + memory: 16Gi + cpu: "6" + taskRunTemplate: + serviceAccountName: build-pipeline-devlake-backend + workspaces: + - name: git-auth + secret: + secretName: '{{ git_auth_secret }}' +status: {} diff --git a/.tekton/devlake-backend-push.yaml b/.tekton/devlake-backend-push.yaml new file mode 100644 index 00000000000..7e32552640a --- /dev/null +++ b/.tekton/devlake-backend-push.yaml @@ -0,0 +1,591 @@ +apiVersion: tekton.dev/v1 +kind: PipelineRun +metadata: + annotations: + build.appstudio.openshift.io/repo: https://github.com/RH-DevProd/devlake?rev={{revision}} + build.appstudio.redhat.com/commit_sha: '{{revision}}' + build.appstudio.redhat.com/target_branch: '{{target_branch}}' + pipelinesascode.tekton.dev/cancel-in-progress: "false" + pipelinesascode.tekton.dev/max-keep-runs: "3" + pipelinesascode.tekton.dev/on-cel-expression: event == "push" && target_branch + == "main" + labels: + appstudio.openshift.io/application: devlake + appstudio.openshift.io/component: devlake-backend + pipelines.appstudio.openshift.io/type: build + name: devlake-backend-on-push + namespace: dprod-tenant +spec: + params: + - name: git-url + value: '{{source_url}}' + - name: revision + value: '{{revision}}' + - name: output-image + value: quay.io/redhat-user-workloads/dprod-tenant/devlake-backend:{{revision}} + - name: build-platforms + value: + - linux/x86_64 + - name: dockerfile + value: Containerfile + - name: path-context + value: backend + pipelineSpec: + description: | + This pipeline is ideal for building multi-arch container images from a Containerfile while maintaining trust after pipeline customization. + + _Uses `buildah` to create a multi-platform container image leveraging [trusted artifacts](https://konflux-ci.dev/architecture/ADR/0036-trusted-artifacts.html). It also optionally creates a source image and runs some build-time tests. This pipeline requires that the [multi platform controller](https://github.com/konflux-ci/multi-platform-controller) is deployed and configured on your Konflux instance. Information is shared between tasks using OCI artifacts instead of PVCs. EC will pass the [`trusted_task.trusted`](https://conforma.dev/docs/policy/packages/release_trusted_task.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. + This pipeline is pushed as a Tekton bundle to [quay.io](https://quay.io/repository/konflux-ci/tekton-catalog/pipeline-docker-build-multi-platform-oci-ta?tab=tags)_ + params: + - description: Source Repository URL + name: git-url + type: string + - default: "" + description: Revision of the Source Repository + name: revision + type: string + - description: Fully Qualified Output Image + name: output-image + type: string + - default: . + description: Path to the source code of an application's component from where + to build image. + name: path-context + type: string + - default: Dockerfile + description: Path to the Dockerfile inside the context specified by parameter + path-context + name: dockerfile + type: string + - default: "false" + description: Skip checks against built image + name: skip-checks + type: string + - default: "false" + description: Execute the build with network isolation + name: hermetic + type: string + - default: "" + description: Build dependencies to be prefetched + name: prefetch-input + type: string + - default: "" + description: Image tag expiration time, time values could be something like + 1h, 2d, 3w for hours, days, and weeks, respectively. + name: image-expires-after + type: string + - default: "false" + description: Build a source image. + name: build-source-image + type: string + - default: "true" + description: Add built image into an OCI image index + name: build-image-index + type: string + - default: docker + description: The format for the resulting image's mediaType. Valid values are + oci or docker. + name: buildah-format + type: string + - default: "false" + description: Enable cache proxy configuration + name: enable-cache-proxy + - default: "true" + description: Use the package registry proxy when prefetching dependencies + name: enable-package-registry-proxy + - default: . + description: Target directories in component's source code to scan with SAST + tools. Multiple values should be separated with commas. + name: sast-target-dirs + type: string + - default: [] + description: Array of --build-arg values ("arg=value" strings) for buildah + name: build-args + type: array + - default: "" + description: Path to a file with build arguments for buildah, see https://www.mankier.com/1/buildah-build#--build-arg-file + name: build-args-file + type: string + - default: "false" + description: Whether to enable privileged mode, should be used only with remote + VMs + name: privileged-nested + type: string + - default: "" + description: Sets the image created time and the SOURCE_DATE_EPOCH build argument. + On its own, it does not change file timestamps inside the layers (set rewrite-timestamp + to "true" for that). Leave empty to keep the actual build time. + name: source-date-epoch + type: string + - default: "false" + description: When "true", clamp file modification times in the image layers + to at most source-date-epoch. Does nothing unless source-date-epoch is set. + name: rewrite-timestamp + type: string + - default: "false" + description: When "true", omit the build history (history timestamps, layer + metadata, etc.) from the resulting image. + name: omit-history + type: string + - default: + - linux/x86_64 + description: List of platforms to build the container images on. The available + set of values is determined by the configuration of the multi-platform-controller. + name: build-platforms + type: array + results: + - description: "" + name: IMAGE_URL + value: $(tasks.build-image-index.results.IMAGE_URL) + - description: "" + name: IMAGE_DIGEST + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - description: "" + name: CHAINS-GIT_URL + value: $(tasks.clone-repository.results.url) + - description: "" + name: CHAINS-GIT_COMMIT + value: $(tasks.clone-repository.results.commit) + tasks: + - name: init + params: + - name: enable-cache-proxy + value: $(params.enable-cache-proxy) + taskRef: + params: + - name: name + value: init + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-init:0.4.2@sha256:421003a5c077ecb820460e71637125ec9093d2101c749a32ede28e190283e9db + - name: kind + value: task + resolver: bundles + - name: clone-repository + params: + - name: url + value: $(params.git-url) + - name: revision + value: $(params.revision) + - name: ociStorage + value: $(params.output-image).git + - name: ociArtifactExpiresAfter + value: $(params.image-expires-after) + runAfter: + - init + taskRef: + params: + - name: name + value: git-clone-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.2.4@sha256:df3c42d78223f07b40a84dd29e5c8860d14777ffdf150ea08c738770f51216dc + - name: kind + value: task + resolver: bundles + workspaces: + - name: basic-auth + workspace: git-auth + - name: prefetch-dependencies + params: + - name: input + value: $(params.prefetch-input) + - name: enable-package-registry-proxy + value: $(params.enable-package-registry-proxy) + - name: SOURCE_ARTIFACT + value: $(tasks.clone-repository.results.SOURCE_ARTIFACT) + - name: ociStorage + value: $(params.output-image).prefetch + - name: ociArtifactExpiresAfter + value: $(params.image-expires-after) + runAfter: + - clone-repository + taskRef: + params: + - name: name + value: prefetch-dependencies-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.10.1@sha256:c09c1c3ced67fb8740b2925a7de09c0810d4e8c8f148d41c21ffe37810d85c62 + - name: kind + value: task + resolver: bundles + workspaces: + - name: git-basic-auth + workspace: git-auth + - name: netrc + workspace: netrc + - matrix: + params: + - name: PLATFORM + value: + - $(params.build-platforms) + name: build-images + params: + - name: IMAGE + value: $(params.output-image) + - name: DOCKERFILE + value: $(params.dockerfile) + - name: CONTEXT + value: $(params.path-context) + - name: HERMETIC + value: $(params.hermetic) + - name: PREFETCH_INPUT + value: $(params.prefetch-input) + - name: IMAGE_EXPIRES_AFTER + value: $(params.image-expires-after) + - name: COMMIT_SHA + value: $(tasks.clone-repository.results.commit) + - name: BUILD_ARGS + value: + - $(params.build-args[*]) + - name: BUILD_ARGS_FILE + value: $(params.build-args-file) + - name: PRIVILEGED_NESTED + value: $(params.privileged-nested) + - name: SOURCE_URL + value: $(tasks.clone-repository.results.url) + - name: BUILDAH_FORMAT + value: $(params.buildah-format) + - name: HTTP_PROXY + value: $(tasks.init.results.http-proxy) + - name: NO_PROXY + value: $(tasks.init.results.no-proxy) + - name: SOURCE_DATE_EPOCH + value: $(params.source-date-epoch) + - name: REWRITE_TIMESTAMP + value: $(params.rewrite-timestamp) + - name: OMIT_HISTORY + value: $(params.omit-history) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + - name: CACHI2_ARTIFACT + value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) + - name: IMAGE_APPEND_PLATFORM + value: "true" + runAfter: + - prefetch-dependencies + taskRef: + params: + - name: name + value: buildah-remote-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-buildah-remote-oci-ta:0.10.5@sha256:eb277ec7b44443f0506a60ac940a2e52178d60f17cb0f51a6966daed5b3755de + - name: kind + value: task + resolver: bundles + - name: build-image-index + params: + - name: IMAGE + value: $(params.output-image) + - name: ALWAYS_BUILD_INDEX + value: $(params.build-image-index) + - name: IMAGES + value: + - $(tasks.build-images.results.IMAGE_REF[*]) + - name: BUILDAH_FORMAT + value: $(params.buildah-format) + runAfter: + - build-images + taskRef: + params: + - name: name + value: build-image-index + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.3.1@sha256:cc75f64deecccb1b59e96ac1182665a5342d79c9e22eebff63d26b0f00a4319c + - name: kind + value: task + resolver: bundles + - name: build-source-image + params: + - name: BINARY_IMAGE + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: BINARY_IMAGE_DIGEST + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + - name: CACHI2_ARTIFACT + value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: source-build-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.3@sha256:7c5575ac8e292f27f57716c021ab0324460dc958e73946724c588c5228e5f372 + - name: kind + value: task + resolver: bundles + when: + - input: $(params.build-source-image) + operator: in + values: + - "true" + - name: deprecated-base-image-check + params: + - name: IMAGE_URL + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: IMAGE_DIGEST + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: deprecated-image-check + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.5@sha256:0ccc688a77e9b7b0b8973c132a1e840844137e77f887be4a0bec8893b0776872 + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - matrix: + params: + - name: image-platform + value: + - $(params.build-platforms) + name: clair-scan + params: + - name: image-digest + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: clair-scan + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.3@sha256:f5b4415db9ac1fba3e11d993a617e0b275d1f0ed2fc669b12c400ed848c39174 + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - matrix: + params: + - name: platform + value: + - $(params.build-platforms) + name: ecosystem-cert-preflight-checks + params: + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: ecosystem-cert-preflight-checks + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.2@sha256:c07d2befa8abf48d4a223a5bdf5ea2335e756d4d0bbc422761087c263060aa94 + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - name: sast-snyk-check + params: + - name: image-digest + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: TARGET_DIRS + value: $(params.sast-target-dirs) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + - name: CACHI2_ARTIFACT + value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: sast-snyk-check-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.5@sha256:eba24f5d9f4b18aa71e523b9b3dbcf22982aa4b018824260a090b19dfc9abf6f + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - matrix: + params: + - name: image-arch + value: + - $(params.build-platforms) + name: clamav-scan + params: + - name: image-digest + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: clamav-scan + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.3@sha256:53a02326bfb930ca5ef6bfa7a33acca833d57752f34f3cb79255fe2e25e7d217 + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - name: sast-shell-check + params: + - name: image-digest + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: TARGET_DIRS + value: $(params.sast-target-dirs) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + - name: CACHI2_ARTIFACT + value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: sast-shell-check-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-sast-shell-check-oci-ta:0.1@sha256:61b27e6ad5daba761d41bb37efb790ed98380603fd4fe2f86d156def5bd72ecc + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - name: sast-unicode-check + params: + - name: image-digest + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: TARGET_DIRS + value: $(params.sast-target-dirs) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + - name: CACHI2_ARTIFACT + value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: sast-unicode-check-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-sast-unicode-check-oci-ta:0.4@sha256:eb9d5392f215cb8b52b16382098cac4885b1e6cd989f88ebd83fdb234d283eb9 + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + - name: apply-tags + params: + - name: IMAGE_URL + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: IMAGE_DIGEST + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: apply-tags + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.3@sha256:3ab844157eccd68e95e4852adc06c3c4ea674edb7865a474b0a898227f2893d6 + - name: kind + value: task + resolver: bundles + - name: push-dockerfile + params: + - name: IMAGE + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: IMAGE_DIGEST + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + - name: DOCKERFILE + value: $(params.dockerfile) + - name: CONTEXT + value: $(params.path-context) + - name: SOURCE_ARTIFACT + value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: push-dockerfile-oci-ta + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.3.1@sha256:5a6cbebd89e5bc163b38231859767f7f6a0dd66cf1333699574379f062731183 + - name: kind + value: task + resolver: bundles + - name: rpms-signature-scan + params: + - name: image-url + value: $(tasks.build-image-index.results.IMAGE_URL) + - name: image-digest + value: $(tasks.build-image-index.results.IMAGE_DIGEST) + runAfter: + - build-image-index + taskRef: + params: + - name: name + value: rpms-signature-scan + - name: bundle + value: quay.io/konflux-ci/tekton-catalog/task-rpms-signature-scan:0.2@sha256:f110c53fd58cab7ac6e47d472bb801d49e2f584eb31837db9d611e11b3862a3d + - name: kind + value: task + resolver: bundles + when: + - input: $(params.skip-checks) + operator: in + values: + - "false" + workspaces: + - name: git-auth + optional: true + - name: netrc + optional: true + taskRunSpecs: + - pipelineTaskName: build-images + stepSpecs: + - name: build + computeResources: + requests: + memory: 16Gi + cpu: "6" + limits: + memory: 16Gi + cpu: "6" + taskRunTemplate: + serviceAccountName: build-pipeline-devlake-backend + workspaces: + - name: git-auth + secret: + secretName: '{{ git_auth_secret }}' +status: {} From 511fa2ce6d2dc0640f020d9f1b06c489a2cab737 Mon Sep 17 00:00:00 2001 From: Karel Piwko Date: Fri, 25 Sep 2026 14:41:25 +0200 Subject: [PATCH 21/21] build: removed previous Konflux and Fullsend configuration --- .fullsend/config.yaml | 21 - .github/workflows/fullsend.yaml | 122 ---- .github/workflows/prioritize.yml | 50 -- .../devlake-backend-d41aa-pull-request.yaml | 626 ------------------ .tekton/devlake-backend-d41aa-push.yaml | 618 ----------------- .../devlake-frontend-ba03c-pull-request.yaml | 609 ----------------- .tekton/devlake-frontend-ba03c-push.yaml | 606 ----------------- 7 files changed, 2652 deletions(-) delete mode 100644 .fullsend/config.yaml delete mode 100644 .github/workflows/fullsend.yaml delete mode 100644 .github/workflows/prioritize.yml delete mode 100644 .tekton/devlake-backend-d41aa-pull-request.yaml delete mode 100644 .tekton/devlake-backend-d41aa-push.yaml delete mode 100644 .tekton/devlake-frontend-ba03c-pull-request.yaml delete mode 100644 .tekton/devlake-frontend-ba03c-push.yaml diff --git a/.fullsend/config.yaml b/.fullsend/config.yaml deleted file mode 100644 index 5ad1358c36f..00000000000 --- a/.fullsend/config.yaml +++ /dev/null @@ -1,21 +0,0 @@ -# fullsend per-repo configuration -# https://github.com/fullsend-ai/fullsend -# -# This file configures fullsend for per-repo installation mode. -# See https://fullsend.sh/docs/guides/infrastructure/layered-config-reference -version: "1" -roles: - - fullsend - - triage - - coder - - fix - - review - - prioritize -allowed_remote_resources: - - https://raw.githubusercontent.com/fullsend-ai/fullsend/ - - https://raw.githubusercontent.com/fullsend-ai/agents/ -create_issues: - allow_targets: - repos: - - konflux-ci/devlake - - fullsend-ai/fullsend diff --git a/.github/workflows/fullsend.yaml b/.github/workflows/fullsend.yaml deleted file mode 100644 index 9a10f59f3bd..00000000000 --- a/.github/workflows/fullsend.yaml +++ /dev/null @@ -1,122 +0,0 @@ -# This file is managed by fullsend. Do not edit it directly. -# Upstream: https://github.com/fullsend-ai/fullsend/blob/main/internal/scaffold/fullsend-repo/.github/workflows/fullsend.yaml ---- -# fullsend shim workflow (per-repo installation mode) -# Routes events to agent workflows via reusable-dispatch.yml. -# All agent execution happens in this repo's context — no external -# config repo is needed. -# -# Security: pull_request_target runs the BASE branch version of this workflow, -# preventing PRs from modifying it to exfiltrate credentials. -# This shim never checks out PR code, so it is not vulnerable to "pwn request" -# attacks. -# -# Routing: this shim forwards the raw event context to reusable-dispatch.yml, -# which determines the stage and runs the agent inline (ADR 62). -# Adding a new stage requires only a job in reusable-dispatch.yml — zero changes to this repo. -# -# Concurrency: per-role cancel-in-progress groups live in reusable-dispatch.yml -# stage jobs with -agent- suffix. Roles operate independently (#2452). -name: fullsend - -on: - issues: - types: [opened, edited, labeled] - issue_comment: - types: [created] - pull_request_target: - types: [opened, synchronize, ready_for_review, closed, labeled, unlabeled] - pull_request_review: - types: [submitted] - -permissions: {} - -jobs: - dispatch: - if: >- - (github.event_name != 'pull_request_target' && github.event_name != 'pull_request_review' - || github.event.pull_request.head.ref != 'fullsend/scaffold-install') - && (github.event_name != 'issue_comment' - || (startsWith(github.event.comment.body, '/fs-') - && github.event.comment.user.type != 'Bot')) - permissions: - actions: write - id-token: write - contents: write - issues: write - packages: read - pull-requests: write - uses: fullsend-ai/fullsend/.github/workflows/reusable-dispatch.yml@d5f36921ac754705619f38c637ef692873809fbc # v0.43.0 - with: - event_action: ${{ github.event.action }} - install_mode: per-repo - mint_url: ${{ vars.FULLSEND_MINT_URL }} - gcp_region: ${{ vars.FULLSEND_GCP_REGION }} - project_number: ${{ vars.FULLSEND_PROJECT_NUMBER }} - runner_image: ubuntu-24.04 - secrets: - FULLSEND_GCP_WIF_PROVIDER: ${{ secrets.FULLSEND_GCP_WIF_PROVIDER }} - FULLSEND_GCP_PROJECT_ID: ${{ secrets.FULLSEND_GCP_PROJECT_ID }} - OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} - OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }} - - stop-fix: - # Job-level if: is intentionally coarse — it only screens for the - # /fs-fix-stop command on a PR from a non-bot. The authoritative - # authorization decision (collaborator permission API + PR-author escape - # hatch) is made in the step below, so a maintainer whose author_association - # is not MEMBER (e.g. private org membership) is not filtered out (ADR 0054). - if: >- - github.event_name == 'issue_comment' - && github.event.issue.pull_request - && github.event.comment.user.type != 'Bot' - && github.event.comment.body == '/fs-fix-stop' - runs-on: ubuntu-24.04 - permissions: - contents: read - issues: write - pull-requests: write - steps: - - name: Add fullsend-no-fix label and notify - env: - GH_TOKEN: ${{ github.token }} - PR_NUMBER: ${{ github.event.issue.number }} - REPO: ${{ github.repository }} - COMMENT_USER_LOGIN: ${{ github.event.comment.user.login }} - ISSUE_USER_LOGIN: ${{ github.event.issue.user.login }} - run: | - set -euo pipefail - # ADR 0054: authorize via the collaborator permission API - # (admin|maintain|write), not author_association — the latter grants - # contributor status to anyone with a single merged PR (issue #5421). - # Mirrors has_repo_permission() in dispatch.yml; keep the two in sync. - # The PR author may always stop the fix agent on their own PR. - authorized=false - if [[ -n "$COMMENT_USER_LOGIN" && "$COMMENT_USER_LOGIN" == "$ISSUE_USER_LOGIN" ]]; then - authorized=true - else - if api_err=$(mktemp); then - if role=$(gh api "repos/$REPO/collaborators/$COMMENT_USER_LOGIN/permission" \ - --jq '.role_name' 2>"$api_err"); then - case "$role" in - admin|maintain|write) authorized=true ;; - esac - else - echo "::warning::Permission API call failed for $COMMENT_USER_LOGIN: $(cat "$api_err")" - fi - rm -f "$api_err" - else - echo "::warning::Failed to create temp file for permission check of $COMMENT_USER_LOGIN" - fi - fi - if [[ "$authorized" != "true" ]]; then - echo "::notice::User $COMMENT_USER_LOGIN is not authorized to stop the fix agent (requires write access or PR authorship)" - exit 0 - fi - gh label create "fullsend-no-fix" --repo "$REPO" \ - --description "Skip bot-triggered fix agent runs" --color "FBCA04" \ - --force 2>/dev/null || true - gh pr edit "$PR_NUMBER" --repo "$REPO" \ - --add-label "fullsend-no-fix" - gh pr comment "$PR_NUMBER" --repo "$REPO" \ - --body "Fix agent disabled for this PR. Remove the \`fullsend-no-fix\` label or use \`/fs-fix\` to re-engage." diff --git a/.github/workflows/prioritize.yml b/.github/workflows/prioritize.yml deleted file mode 100644 index 3e89e64a5ce..00000000000 --- a/.github/workflows/prioritize.yml +++ /dev/null @@ -1,50 +0,0 @@ -# This file is managed by fullsend. Do not edit it directly. -# Upstream: https://github.com/fullsend-ai/fullsend/blob/main/internal/scaffold/fullsend-repo/.github/workflows/prioritize.yml ---- -# fullsend-stage: prioritize -name: Prioritize - -permissions: - actions: write - contents: read - id-token: write - issues: write - -on: - workflow_dispatch: - inputs: - event_type: - required: true - type: string - source_repo: - required: true - type: string - event_payload: - required: true - type: string - project_number: - description: GitHub Projects V2 project number for RICE scoring - required: false - type: string - -concurrency: - group: fullsend-prioritize-${{ inputs.source_repo }}-${{ fromJSON(inputs.event_payload).issue.number }} - cancel-in-progress: true - -jobs: - prioritize: - uses: fullsend-ai/fullsend/.github/workflows/reusable-prioritize.yml@d5f36921ac754705619f38c637ef692873809fbc # v0.43.0 - with: - event_type: ${{ inputs.event_type }} - source_repo: ${{ inputs.source_repo }} - event_payload: ${{ inputs.event_payload }} - mint_url: ${{ vars.FULLSEND_MINT_URL }} - gcp_region: ${{ vars.FULLSEND_GCP_REGION }} - project_number: ${{ inputs.project_number || vars.FULLSEND_PROJECT_NUMBER }} - install_mode: per-repo - runner_image: ubuntu-24.04 - secrets: - FULLSEND_GCP_WIF_PROVIDER: ${{ secrets.FULLSEND_GCP_WIF_PROVIDER }} - FULLSEND_GCP_PROJECT_ID: ${{ secrets.FULLSEND_GCP_PROJECT_ID }} - OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} - OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }} diff --git a/.tekton/devlake-backend-d41aa-pull-request.yaml b/.tekton/devlake-backend-d41aa-pull-request.yaml deleted file mode 100644 index 53a349d3c6c..00000000000 --- a/.tekton/devlake-backend-d41aa-pull-request.yaml +++ /dev/null @@ -1,626 +0,0 @@ -apiVersion: tekton.dev/v1 -kind: PipelineRun -metadata: - annotations: - build.appstudio.openshift.io/repo: https://github.com/konflux-ci/devlake?rev={{revision}} - build.appstudio.redhat.com/commit_sha: '{{revision}}' - build.appstudio.redhat.com/pull_request_number: '{{pull_request_number}}' - build.appstudio.redhat.com/target_branch: '{{target_branch}}' - pipelinesascode.tekton.dev/cancel-in-progress: "true" - pipelinesascode.tekton.dev/max-keep-runs: "3" - pipelinesascode.tekton.dev/on-cel-expression: event == "pull_request" && target_branch == "main" - creationTimestamp: - labels: - appstudio.openshift.io/application: devlake - appstudio.openshift.io/component: devlake-backend-d41aa - pipelines.appstudio.openshift.io/type: build - name: devlake-backend-d41aa-on-pull-request - namespace: rh-konflux-devprod-tenant -spec: - params: - - name: git-url - value: '{{source_url}}' - - name: revision - value: '{{revision}}' - - name: output-image - value: quay.io/konflux-ci/konflux-devprod/devlake-backend:on-pr-{{revision}} - - name: image-expires-after - value: 5d - - name: dockerfile - value: backend/Containerfile - - name: path-context - value: backend - pipelineSpec: - description: | - This pipeline is ideal for building container images from a Containerfile while maintaining trust after pipeline customization. - - _Uses `buildah` to create a container image leveraging [trusted artifacts](https://konflux-ci.dev/architecture/ADR/0036-trusted-artifacts.html). It also optionally creates a source image and runs some build-time tests. Information is shared between tasks using OCI artifacts instead of PVCs. EC will pass the [`trusted_task.trusted`](https://conforma.dev/docs/policy/packages/release_trusted_task.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. - This pipeline is pushed as a Tekton bundle to [quay.io](https://quay.io/repository/konflux-ci/tekton-catalog/pipeline-docker-build-oci-ta?tab=tags)_ - params: - - description: Source Repository URL - name: git-url - type: string - - default: "" - description: Revision of the Source Repository - name: revision - type: string - - description: Fully Qualified Output Image - name: output-image - type: string - - default: . - description: Path to the source code of an application's component from where to build image. - name: path-context - type: string - - default: Dockerfile - description: Path to the Dockerfile inside the context specified by parameter path-context - name: dockerfile - type: string - - default: "false" - description: Force rebuild image - name: rebuild - type: string - - default: "false" - description: Skip checks against built image - name: skip-checks - type: string - - default: "false" - description: Execute the build with network isolation - name: hermetic - type: string - - default: "" - description: Build dependencies to be prefetched - name: prefetch-input - type: string - - default: "" - description: Image tag expiration time, time values could be something like 1h, 2d, 3w for hours, days, and weeks, respectively. - name: image-expires-after - type: string - - default: "false" - description: Build a source image. - name: build-source-image - type: string - - default: "false" - description: Add built image into an OCI image index - name: build-image-index - type: string - - default: docker - description: The format for the resulting image's mediaType. Valid values are oci or docker. - name: buildah-format - type: string - - default: - - "BUILDPLATFORM=linux/amd64" - description: Array of --build-arg values ("arg=value" strings) for buildah - name: build-args - type: array - - default: "" - description: Path to a file with build arguments for buildah, see https://www.mankier.com/1/buildah-build#--build-arg-file - name: build-args-file - type: string - - default: "false" - description: Whether to enable privileged mode, should be used only with remote VMs - name: privileged-nested - type: string - - name: enable-cache-proxy - default: 'false' - description: Enable cache proxy configuration - type: string - results: - - description: "" - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - description: "" - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - description: "" - name: CHAINS-GIT_URL - value: $(tasks.clone-repository.results.url) - - description: "" - name: CHAINS-GIT_COMMIT - value: $(tasks.clone-repository.results.commit) - tasks: - - name: init - params: - - name: image-url - value: $(params.output-image) - - name: rebuild - value: $(params.rebuild) - - name: skip-checks - value: $(params.skip-checks) - - name: enable-cache-proxy - value: $(params.enable-cache-proxy) - taskRef: - params: - - name: name - value: init - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-init:0.2@sha256:ebf06778aeacbbeb081f9231eafbdfdb8e380ad04e211d7ed80ae9101e37fd82 - - name: kind - value: task - resolver: bundles - - name: clone-repository - params: - - name: url - value: $(params.git-url) - - name: revision - value: $(params.revision) - - name: ociStorage - value: $(params.output-image).git - - name: ociArtifactExpiresAfter - value: $(params.image-expires-after) - runAfter: - - init - taskRef: - params: - - name: name - value: git-clone-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.1@sha256:306b69e6db435ad4a7cf258b6219d9b998eb37da44f5e9ac882ac86a08109154 - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - workspaces: - - name: basic-auth - workspace: git-auth - - name: prefetch-dependencies - params: - - name: input - value: $(params.prefetch-input) - - name: SOURCE_ARTIFACT - value: $(tasks.clone-repository.results.SOURCE_ARTIFACT) - - name: ociStorage - value: $(params.output-image).prefetch - - name: ociArtifactExpiresAfter - value: $(params.image-expires-after) - runAfter: - - clone-repository - taskRef: - params: - - name: name - value: prefetch-dependencies-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.2@sha256:c664a6df6514b59c3ce53570b0994b45af66ecc89ba2a8e41834eae0622addf6 - - name: kind - value: task - resolver: bundles - workspaces: - - name: git-basic-auth - workspace: git-auth - - name: netrc - workspace: netrc - - name: build-container - computeResources: - limits: - memory: 12Gi - requests: - memory: 4Gi - params: - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: PRIVILEGED_NESTED - value: $(params.privileged-nested) - - name: SOURCE_URL - value: $(tasks.clone-repository.results.url) - - name: BUILDAH_FORMAT - value: $(params.buildah-format) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - - name: HTTP_PROXY - value: $(tasks.init.results.http-proxy) - - name: NO_PROXY - value: $(tasks.init.results.no-proxy) - runAfter: - - prefetch-dependencies - taskRef: - params: - - name: name - value: buildah-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-buildah-oci-ta:0.8@sha256:8a984185d22d3180ecd575dbf6b6a63edb1b3ec754be0b8e5e4247a9eae9112b - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - name: build-image-index - params: - - name: IMAGE - value: $(params.output-image) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: ALWAYS_BUILD_INDEX - value: $(params.build-image-index) - - name: IMAGES - value: - - $(tasks.build-container.results.IMAGE_URL)@$(tasks.build-container.results.IMAGE_DIGEST) - - name: BUILDAH_FORMAT - value: $(params.buildah-format) - runAfter: - - build-container - taskRef: - params: - - name: name - value: build-image-index - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.2@sha256:05d3d8a5ded44c51b074a56a408ddf5d65c56b4c15e110abb1a99e3aff269d49 - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - name: build-source-image - params: - - name: BINARY_IMAGE - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: BINARY_IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: source-build-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.3@sha256:c35ba219390d77a48ee19347e5ee8d13e5c23e3984299e02291d6da1ed8a986c - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - input: $(params.build-source-image) - operator: in - values: - - "true" - - name: deprecated-base-image-check - params: - - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: deprecated-image-check - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.5@sha256:e3a55ccdf1091b4a35507f9ee2d1918d8e89a5f96babcb5486b491226da03d6f - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: clair-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: clair-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.3@sha256:dadfea7633d82e4303ba73d5e9c7e2bc16834bde0fd7688880453b26452067eb - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: ecosystem-cert-preflight-checks - params: - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: ecosystem-cert-preflight-checks - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.2@sha256:204fd3914d83c7b60e8eee72b5a944337720c79a3e660e7c994435456dcf7175 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-snyk-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-snyk-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.4@sha256:a70272ae12f6d7f0da2902158e1bcee756877aa8f71fd1a22ef9afd8b177fb41 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: clamav-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: clamav-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.3@sha256:76efc0119a10bc8a420dbbb0cdab9ef8eafd263f6827498d2b644e450e93f446 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-coverity-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - coverity-availability-check - taskRef: - params: - - name: name - value: sast-coverity-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-coverity-check-oci-ta:0.3@sha256:9d0bc704bca6b6faad37b2ce8106b96e0cef35e1f647d037a878bf416589de9d - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - input: $(tasks.coverity-availability-check.results.STATUS) - operator: in - values: - - success - - name: coverity-availability-check - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: coverity-availability-check - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-coverity-availability-check:0.2@sha256:267d5bc069a0323f41e24732ddfd1057e5c639e853d1e620c67505fab78f1301 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-shell-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-shell-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-shell-check-oci-ta:0.1@sha256:e7a51575f9188a1461d4520da25aaa4efdd3b896c97dc750941fa22840e55c13 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-unicode-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-unicode-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-unicode-check-oci-ta:0.4@sha256:1818a5b3e4fa86c838ae71226a157241967d1f19c5ed377e4b2fddad7a3ceefe - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: apply-tags - params: - - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: apply-tags - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.3@sha256:510b6d2a3b188adeb716e49566b57d611ab36bd69a2794b5ddfc11dbf014c2ca - - name: kind - value: task - resolver: bundles - - name: push-dockerfile - params: - - name: IMAGE - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: push-dockerfile-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.1@sha256:08bba4a659ecd48f871bef00b80af58954e5a09fcbb28a1783ddd640c4f6535e - - name: kind - value: task - resolver: bundles - - name: rpms-signature-scan - params: - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: rpms-signature-scan - - name: bundle - value: quay.io/konflux-ci/konflux-vanguard/task-rpms-signature-scan:0.2@sha256:3d016c63bcab64ab82da762a52b013c0bcb534e9523b8c0e073cc3a0c02f0cac - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - workspaces: - - name: git-auth - optional: true - - name: netrc - optional: true - taskRunSpecs: - - pipelineTaskName: build-container - stepSpecs: - - name: build - computeResources: - requests: - memory: 16Gi - cpu: "6" - limits: - memory: 16Gi - cpu: "6" - taskRunTemplate: - serviceAccountName: build-pipeline-devlake-backend-d41aa - workspaces: - - name: git-auth - secret: - secretName: '{{ git_auth_secret }}' -status: {} diff --git a/.tekton/devlake-backend-d41aa-push.yaml b/.tekton/devlake-backend-d41aa-push.yaml deleted file mode 100644 index 792280ecd02..00000000000 --- a/.tekton/devlake-backend-d41aa-push.yaml +++ /dev/null @@ -1,618 +0,0 @@ -apiVersion: tekton.dev/v1 -kind: PipelineRun -metadata: - annotations: - build.appstudio.openshift.io/repo: https://github.com/konflux-ci/devlake?rev={{revision}} - build.appstudio.redhat.com/commit_sha: '{{revision}}' - build.appstudio.redhat.com/target_branch: '{{target_branch}}' - pipelinesascode.tekton.dev/cancel-in-progress: "false" - pipelinesascode.tekton.dev/max-keep-runs: "3" - pipelinesascode.tekton.dev/on-cel-expression: event == "push" && target_branch == "main" - creationTimestamp: - labels: - appstudio.openshift.io/application: devlake - appstudio.openshift.io/component: devlake-backend-d41aa - pipelines.appstudio.openshift.io/type: build - name: devlake-backend-d41aa-on-push - namespace: rh-konflux-devprod-tenant -spec: - params: - - name: git-url - value: '{{source_url}}' - - name: revision - value: '{{revision}}' - - name: output-image - value: quay.io/konflux-ci/konflux-devprod/devlake-backend:{{revision}} - - name: dockerfile - value: backend/Containerfile - - name: path-context - value: backend - pipelineSpec: - description: | - This pipeline is ideal for building container images from a Containerfile while maintaining trust after pipeline customization. - - _Uses `buildah` to create a container image leveraging [trusted artifacts](https://konflux-ci.dev/architecture/ADR/0036-trusted-artifacts.html). It also optionally creates a source image and runs some build-time tests. Information is shared between tasks using OCI artifacts instead of PVCs. EC will pass the [`trusted_task.trusted`](https://conforma.dev/docs/policy/packages/release_trusted_task.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. - This pipeline is pushed as a Tekton bundle to [quay.io](https://quay.io/repository/konflux-ci/tekton-catalog/pipeline-docker-build-oci-ta?tab=tags)_ - params: - - description: Source Repository URL - name: git-url - type: string - - default: "" - description: Revision of the Source Repository - name: revision - type: string - - description: Fully Qualified Output Image - name: output-image - type: string - - default: . - description: Path to the source code of an application's component from where to build image. - name: path-context - type: string - - default: Dockerfile - description: Path to the Dockerfile inside the context specified by parameter path-context - name: dockerfile - type: string - - default: "false" - description: Force rebuild image - name: rebuild - type: string - - default: "false" - description: Skip checks against built image - name: skip-checks - type: string - - default: "false" - description: Execute the build with network isolation - name: hermetic - type: string - - default: "" - description: Build dependencies to be prefetched - name: prefetch-input - type: string - - default: "" - description: Image tag expiration time, time values could be something like 1h, 2d, 3w for hours, days, and weeks, respectively. - name: image-expires-after - type: string - - default: "false" - description: Build a source image. - name: build-source-image - type: string - - default: "false" - description: Add built image into an OCI image index - name: build-image-index - type: string - - default: docker - description: The format for the resulting image's mediaType. Valid values are oci or docker. - name: buildah-format - type: string - - default: - - "BUILDPLATFORM=linux/amd64" - description: Array of --build-arg values ("arg=value" strings) for buildah - name: build-args - type: array - - default: "" - description: Path to a file with build arguments for buildah, see https://www.mankier.com/1/buildah-build#--build-arg-file - name: build-args-file - type: string - - default: "false" - description: Whether to enable privileged mode, should be used only with remote VMs - name: privileged-nested - type: string - - name: enable-cache-proxy - default: 'false' - description: Enable cache proxy configuration - type: string - results: - - description: "" - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - description: "" - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - description: "" - name: CHAINS-GIT_URL - value: $(tasks.clone-repository.results.url) - - description: "" - name: CHAINS-GIT_COMMIT - value: $(tasks.clone-repository.results.commit) - tasks: - - name: init - params: - - name: image-url - value: $(params.output-image) - - name: rebuild - value: $(params.rebuild) - - name: skip-checks - value: $(params.skip-checks) - - name: enable-cache-proxy - value: $(params.enable-cache-proxy) - taskRef: - params: - - name: name - value: init - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-init:0.2@sha256:ebf06778aeacbbeb081f9231eafbdfdb8e380ad04e211d7ed80ae9101e37fd82 - - name: kind - value: task - resolver: bundles - - name: clone-repository - params: - - name: url - value: $(params.git-url) - - name: revision - value: $(params.revision) - - name: ociStorage - value: $(params.output-image).git - - name: ociArtifactExpiresAfter - value: $(params.image-expires-after) - runAfter: - - init - taskRef: - params: - - name: name - value: git-clone-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.1@sha256:306b69e6db435ad4a7cf258b6219d9b998eb37da44f5e9ac882ac86a08109154 - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - workspaces: - - name: basic-auth - workspace: git-auth - - name: prefetch-dependencies - params: - - name: input - value: $(params.prefetch-input) - - name: SOURCE_ARTIFACT - value: $(tasks.clone-repository.results.SOURCE_ARTIFACT) - - name: ociStorage - value: $(params.output-image).prefetch - - name: ociArtifactExpiresAfter - value: $(params.image-expires-after) - runAfter: - - clone-repository - taskRef: - params: - - name: name - value: prefetch-dependencies-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.2@sha256:c664a6df6514b59c3ce53570b0994b45af66ecc89ba2a8e41834eae0622addf6 - - name: kind - value: task - resolver: bundles - workspaces: - - name: git-basic-auth - workspace: git-auth - - name: netrc - workspace: netrc - - name: build-container - params: - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: PRIVILEGED_NESTED - value: $(params.privileged-nested) - - name: SOURCE_URL - value: $(tasks.clone-repository.results.url) - - name: BUILDAH_FORMAT - value: $(params.buildah-format) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - - name: HTTP_PROXY - value: $(tasks.init.results.http-proxy) - - name: NO_PROXY - value: $(tasks.init.results.no-proxy) - runAfter: - - prefetch-dependencies - taskRef: - params: - - name: name - value: buildah-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-buildah-oci-ta:0.8@sha256:8a984185d22d3180ecd575dbf6b6a63edb1b3ec754be0b8e5e4247a9eae9112b - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - name: build-image-index - params: - - name: IMAGE - value: $(params.output-image) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: ALWAYS_BUILD_INDEX - value: $(params.build-image-index) - - name: IMAGES - value: - - $(tasks.build-container.results.IMAGE_URL)@$(tasks.build-container.results.IMAGE_DIGEST) - - name: BUILDAH_FORMAT - value: $(params.buildah-format) - runAfter: - - build-container - taskRef: - params: - - name: name - value: build-image-index - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.2@sha256:05d3d8a5ded44c51b074a56a408ddf5d65c56b4c15e110abb1a99e3aff269d49 - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - name: build-source-image - params: - - name: BINARY_IMAGE - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: BINARY_IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: source-build-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.3@sha256:c35ba219390d77a48ee19347e5ee8d13e5c23e3984299e02291d6da1ed8a986c - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - input: $(params.build-source-image) - operator: in - values: - - "true" - - name: deprecated-base-image-check - params: - - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: deprecated-image-check - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.5@sha256:e3a55ccdf1091b4a35507f9ee2d1918d8e89a5f96babcb5486b491226da03d6f - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: clair-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: clair-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.3@sha256:dadfea7633d82e4303ba73d5e9c7e2bc16834bde0fd7688880453b26452067eb - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: ecosystem-cert-preflight-checks - params: - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: ecosystem-cert-preflight-checks - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.2@sha256:204fd3914d83c7b60e8eee72b5a944337720c79a3e660e7c994435456dcf7175 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-snyk-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-snyk-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.4@sha256:a70272ae12f6d7f0da2902158e1bcee756877aa8f71fd1a22ef9afd8b177fb41 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: clamav-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: clamav-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.3@sha256:76efc0119a10bc8a420dbbb0cdab9ef8eafd263f6827498d2b644e450e93f446 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-coverity-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - coverity-availability-check - taskRef: - params: - - name: name - value: sast-coverity-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-coverity-check-oci-ta:0.3@sha256:9d0bc704bca6b6faad37b2ce8106b96e0cef35e1f647d037a878bf416589de9d - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - input: $(tasks.coverity-availability-check.results.STATUS) - operator: in - values: - - success - - name: coverity-availability-check - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: coverity-availability-check - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-coverity-availability-check:0.2@sha256:267d5bc069a0323f41e24732ddfd1057e5c639e853d1e620c67505fab78f1301 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-shell-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-shell-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-shell-check-oci-ta:0.1@sha256:e7a51575f9188a1461d4520da25aaa4efdd3b896c97dc750941fa22840e55c13 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-unicode-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-unicode-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-unicode-check-oci-ta:0.4@sha256:1818a5b3e4fa86c838ae71226a157241967d1f19c5ed377e4b2fddad7a3ceefe - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: apply-tags - params: - - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: apply-tags - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.3@sha256:510b6d2a3b188adeb716e49566b57d611ab36bd69a2794b5ddfc11dbf014c2ca - - name: kind - value: task - resolver: bundles - - name: push-dockerfile - params: - - name: IMAGE - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: push-dockerfile-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.1@sha256:08bba4a659ecd48f871bef00b80af58954e5a09fcbb28a1783ddd640c4f6535e - - name: kind - value: task - resolver: bundles - - name: rpms-signature-scan - params: - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: rpms-signature-scan - - name: bundle - value: quay.io/konflux-ci/konflux-vanguard/task-rpms-signature-scan:0.2@sha256:3d016c63bcab64ab82da762a52b013c0bcb534e9523b8c0e073cc3a0c02f0cac - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - workspaces: - - name: git-auth - optional: true - - name: netrc - optional: true - taskRunSpecs: - - pipelineTaskName: build-container - stepSpecs: - - name: build - computeResources: - requests: - memory: 16Gi - cpu: "6" - limits: - memory: 16Gi - cpu: "6" - taskRunTemplate: - serviceAccountName: build-pipeline-devlake-backend-d41aa - workspaces: - - name: git-auth - secret: - secretName: '{{ git_auth_secret }}' -status: {} diff --git a/.tekton/devlake-frontend-ba03c-pull-request.yaml b/.tekton/devlake-frontend-ba03c-pull-request.yaml deleted file mode 100644 index c3dbb65ca75..00000000000 --- a/.tekton/devlake-frontend-ba03c-pull-request.yaml +++ /dev/null @@ -1,609 +0,0 @@ -apiVersion: tekton.dev/v1 -kind: PipelineRun -metadata: - annotations: - build.appstudio.openshift.io/repo: https://github.com/konflux-ci/devlake?rev={{revision}} - build.appstudio.redhat.com/commit_sha: '{{revision}}' - build.appstudio.redhat.com/pull_request_number: '{{pull_request_number}}' - build.appstudio.redhat.com/target_branch: '{{target_branch}}' - pipelinesascode.tekton.dev/cancel-in-progress: "true" - pipelinesascode.tekton.dev/max-keep-runs: "3" - pipelinesascode.tekton.dev/on-cel-expression: event == "pull_request" && target_branch == "main" && ( "config-ui/***".pathChanged() || ".tekton/devlake-frontend-ba03c-pull-request.yaml".pathChanged() || "config-ui/frontend".pathChanged() ) - creationTimestamp: - labels: - appstudio.openshift.io/application: devlake - appstudio.openshift.io/component: devlake-frontend-ba03c - pipelines.appstudio.openshift.io/type: build - name: devlake-frontend-ba03c-on-pull-request - namespace: rh-konflux-devprod-tenant -spec: - params: - - name: git-url - value: '{{source_url}}' - - name: revision - value: '{{revision}}' - - name: output-image - value: quay.io/konflux-ci/konflux-devprod/devlake-frontend:on-pr-{{revision}} - - name: image-expires-after - value: 5d - - name: dockerfile - value: config-ui/Containerfile - - name: path-context - value: config-ui - pipelineSpec: - description: | - This pipeline is ideal for building container images from a Containerfile while maintaining trust after pipeline customization. - - _Uses `buildah` to create a container image leveraging [trusted artifacts](https://konflux-ci.dev/architecture/ADR/0036-trusted-artifacts.html). It also optionally creates a source image and runs some build-time tests. Information is shared between tasks using OCI artifacts instead of PVCs. EC will pass the [`trusted_task.trusted`](https://conforma.dev/docs/policy/packages/release_trusted_task.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. - This pipeline is pushed as a Tekton bundle to [quay.io](https://quay.io/repository/konflux-ci/tekton-catalog/pipeline-docker-build-oci-ta?tab=tags)_ - params: - - description: Source Repository URL - name: git-url - type: string - - default: "" - description: Revision of the Source Repository - name: revision - type: string - - description: Fully Qualified Output Image - name: output-image - type: string - - default: . - description: Path to the source code of an application's component from where to build image. - name: path-context - type: string - - default: Dockerfile - description: Path to the Dockerfile inside the context specified by parameter path-context - name: dockerfile - type: string - - default: "false" - description: Force rebuild image - name: rebuild - type: string - - default: "false" - description: Skip checks against built image - name: skip-checks - type: string - - default: "false" - description: Execute the build with network isolation - name: hermetic - type: string - - default: "" - description: Build dependencies to be prefetched - name: prefetch-input - type: string - - default: "" - description: Image tag expiration time, time values could be something like 1h, 2d, 3w for hours, days, and weeks, respectively. - name: image-expires-after - type: string - - default: "false" - description: Build a source image. - name: build-source-image - type: string - - default: "false" - description: Add built image into an OCI image index - name: build-image-index - type: string - - default: docker - description: The format for the resulting image's mediaType. Valid values are oci or docker. - name: buildah-format - type: string - - default: [] - description: Array of --build-arg values ("arg=value" strings) for buildah - name: build-args - type: array - - default: "" - description: Path to a file with build arguments for buildah, see https://www.mankier.com/1/buildah-build#--build-arg-file - name: build-args-file - type: string - - default: "false" - description: Whether to enable privileged mode, should be used only with remote VMs - name: privileged-nested - type: string - - name: enable-cache-proxy - default: 'false' - description: Enable cache proxy configuration - type: string - results: - - description: "" - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - description: "" - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - description: "" - name: CHAINS-GIT_URL - value: $(tasks.clone-repository.results.url) - - description: "" - name: CHAINS-GIT_COMMIT - value: $(tasks.clone-repository.results.commit) - tasks: - - name: init - params: - - name: image-url - value: $(params.output-image) - - name: rebuild - value: $(params.rebuild) - - name: skip-checks - value: $(params.skip-checks) - - name: enable-cache-proxy - value: $(params.enable-cache-proxy) - taskRef: - params: - - name: name - value: init - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-init:0.2@sha256:ebf06778aeacbbeb081f9231eafbdfdb8e380ad04e211d7ed80ae9101e37fd82 - - name: kind - value: task - resolver: bundles - - name: clone-repository - params: - - name: url - value: $(params.git-url) - - name: revision - value: $(params.revision) - - name: ociStorage - value: $(params.output-image).git - - name: ociArtifactExpiresAfter - value: $(params.image-expires-after) - runAfter: - - init - taskRef: - params: - - name: name - value: git-clone-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.1@sha256:306b69e6db435ad4a7cf258b6219d9b998eb37da44f5e9ac882ac86a08109154 - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - workspaces: - - name: basic-auth - workspace: git-auth - - name: prefetch-dependencies - params: - - name: input - value: $(params.prefetch-input) - - name: SOURCE_ARTIFACT - value: $(tasks.clone-repository.results.SOURCE_ARTIFACT) - - name: ociStorage - value: $(params.output-image).prefetch - - name: ociArtifactExpiresAfter - value: $(params.image-expires-after) - runAfter: - - clone-repository - taskRef: - params: - - name: name - value: prefetch-dependencies-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.2@sha256:c664a6df6514b59c3ce53570b0994b45af66ecc89ba2a8e41834eae0622addf6 - - name: kind - value: task - resolver: bundles - workspaces: - - name: git-basic-auth - workspace: git-auth - - name: netrc - workspace: netrc - - name: build-container - params: - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: PRIVILEGED_NESTED - value: $(params.privileged-nested) - - name: SOURCE_URL - value: $(tasks.clone-repository.results.url) - - name: BUILDAH_FORMAT - value: $(params.buildah-format) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - - name: HTTP_PROXY - value: $(tasks.init.results.http-proxy) - - name: NO_PROXY - value: $(tasks.init.results.no-proxy) - runAfter: - - prefetch-dependencies - taskRef: - params: - - name: name - value: buildah-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-buildah-oci-ta:0.8@sha256:8a984185d22d3180ecd575dbf6b6a63edb1b3ec754be0b8e5e4247a9eae9112b - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - name: build-image-index - params: - - name: IMAGE - value: $(params.output-image) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: ALWAYS_BUILD_INDEX - value: $(params.build-image-index) - - name: IMAGES - value: - - $(tasks.build-container.results.IMAGE_URL)@$(tasks.build-container.results.IMAGE_DIGEST) - - name: BUILDAH_FORMAT - value: $(params.buildah-format) - runAfter: - - build-container - taskRef: - params: - - name: name - value: build-image-index - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.2@sha256:05d3d8a5ded44c51b074a56a408ddf5d65c56b4c15e110abb1a99e3aff269d49 - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - name: build-source-image - params: - - name: BINARY_IMAGE - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: BINARY_IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: source-build-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.3@sha256:c35ba219390d77a48ee19347e5ee8d13e5c23e3984299e02291d6da1ed8a986c - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - input: $(params.build-source-image) - operator: in - values: - - "true" - - name: deprecated-base-image-check - params: - - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: deprecated-image-check - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.5@sha256:e3a55ccdf1091b4a35507f9ee2d1918d8e89a5f96babcb5486b491226da03d6f - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: clair-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: clair-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.3@sha256:dadfea7633d82e4303ba73d5e9c7e2bc16834bde0fd7688880453b26452067eb - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: ecosystem-cert-preflight-checks - params: - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: ecosystem-cert-preflight-checks - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.2@sha256:204fd3914d83c7b60e8eee72b5a944337720c79a3e660e7c994435456dcf7175 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-snyk-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-snyk-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.4@sha256:a70272ae12f6d7f0da2902158e1bcee756877aa8f71fd1a22ef9afd8b177fb41 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: clamav-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: clamav-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.3@sha256:76efc0119a10bc8a420dbbb0cdab9ef8eafd263f6827498d2b644e450e93f446 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-coverity-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - coverity-availability-check - taskRef: - params: - - name: name - value: sast-coverity-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-coverity-check-oci-ta:0.3@sha256:9d0bc704bca6b6faad37b2ce8106b96e0cef35e1f647d037a878bf416589de9d - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - input: $(tasks.coverity-availability-check.results.STATUS) - operator: in - values: - - success - - name: coverity-availability-check - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: coverity-availability-check - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-coverity-availability-check:0.2@sha256:267d5bc069a0323f41e24732ddfd1057e5c639e853d1e620c67505fab78f1301 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-shell-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-shell-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-shell-check-oci-ta:0.1@sha256:e7a51575f9188a1461d4520da25aaa4efdd3b896c97dc750941fa22840e55c13 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-unicode-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-unicode-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-unicode-check-oci-ta:0.4@sha256:1818a5b3e4fa86c838ae71226a157241967d1f19c5ed377e4b2fddad7a3ceefe - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: apply-tags - params: - - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: apply-tags - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.3@sha256:510b6d2a3b188adeb716e49566b57d611ab36bd69a2794b5ddfc11dbf014c2ca - - name: kind - value: task - resolver: bundles - - name: push-dockerfile - params: - - name: IMAGE - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: push-dockerfile-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.1@sha256:08bba4a659ecd48f871bef00b80af58954e5a09fcbb28a1783ddd640c4f6535e - - name: kind - value: task - resolver: bundles - - name: rpms-signature-scan - params: - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: rpms-signature-scan - - name: bundle - value: quay.io/konflux-ci/konflux-vanguard/task-rpms-signature-scan:0.2@sha256:3d016c63bcab64ab82da762a52b013c0bcb534e9523b8c0e073cc3a0c02f0cac - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - workspaces: - - name: git-auth - optional: true - - name: netrc - optional: true - taskRunTemplate: - serviceAccountName: build-pipeline-devlake-frontend-ba03c - workspaces: - - name: git-auth - secret: - secretName: '{{ git_auth_secret }}' -status: {} diff --git a/.tekton/devlake-frontend-ba03c-push.yaml b/.tekton/devlake-frontend-ba03c-push.yaml deleted file mode 100644 index c8402983ce3..00000000000 --- a/.tekton/devlake-frontend-ba03c-push.yaml +++ /dev/null @@ -1,606 +0,0 @@ -apiVersion: tekton.dev/v1 -kind: PipelineRun -metadata: - annotations: - build.appstudio.openshift.io/repo: https://github.com/konflux-ci/devlake?rev={{revision}} - build.appstudio.redhat.com/commit_sha: '{{revision}}' - build.appstudio.redhat.com/target_branch: '{{target_branch}}' - pipelinesascode.tekton.dev/cancel-in-progress: "false" - pipelinesascode.tekton.dev/max-keep-runs: "3" - pipelinesascode.tekton.dev/on-cel-expression: event == "push" && target_branch == "main" && ( "config-ui/***".pathChanged() || ".tekton/devlake-frontend-ba03c-push.yaml".pathChanged() || "config-ui/frontend".pathChanged() ) - creationTimestamp: - labels: - appstudio.openshift.io/application: devlake - appstudio.openshift.io/component: devlake-frontend-ba03c - pipelines.appstudio.openshift.io/type: build - name: devlake-frontend-ba03c-on-push - namespace: rh-konflux-devprod-tenant -spec: - params: - - name: git-url - value: '{{source_url}}' - - name: revision - value: '{{revision}}' - - name: output-image - value: quay.io/konflux-ci/konflux-devprod/devlake-frontend:{{revision}} - - name: dockerfile - value: config-ui/Containerfile - - name: path-context - value: config-ui - pipelineSpec: - description: | - This pipeline is ideal for building container images from a Containerfile while maintaining trust after pipeline customization. - - _Uses `buildah` to create a container image leveraging [trusted artifacts](https://konflux-ci.dev/architecture/ADR/0036-trusted-artifacts.html). It also optionally creates a source image and runs some build-time tests. Information is shared between tasks using OCI artifacts instead of PVCs. EC will pass the [`trusted_task.trusted`](https://conforma.dev/docs/policy/packages/release_trusted_task.html#trusted_task__trusted) policy as long as all data used to build the artifact is generated from trusted tasks. - This pipeline is pushed as a Tekton bundle to [quay.io](https://quay.io/repository/konflux-ci/tekton-catalog/pipeline-docker-build-oci-ta?tab=tags)_ - params: - - description: Source Repository URL - name: git-url - type: string - - default: "" - description: Revision of the Source Repository - name: revision - type: string - - description: Fully Qualified Output Image - name: output-image - type: string - - default: . - description: Path to the source code of an application's component from where to build image. - name: path-context - type: string - - default: Dockerfile - description: Path to the Dockerfile inside the context specified by parameter path-context - name: dockerfile - type: string - - default: "false" - description: Force rebuild image - name: rebuild - type: string - - default: "false" - description: Skip checks against built image - name: skip-checks - type: string - - default: "false" - description: Execute the build with network isolation - name: hermetic - type: string - - default: "" - description: Build dependencies to be prefetched - name: prefetch-input - type: string - - default: "" - description: Image tag expiration time, time values could be something like 1h, 2d, 3w for hours, days, and weeks, respectively. - name: image-expires-after - type: string - - default: "false" - description: Build a source image. - name: build-source-image - type: string - - default: "false" - description: Add built image into an OCI image index - name: build-image-index - type: string - - default: docker - description: The format for the resulting image's mediaType. Valid values are oci or docker. - name: buildah-format - type: string - - default: [] - description: Array of --build-arg values ("arg=value" strings) for buildah - name: build-args - type: array - - default: "" - description: Path to a file with build arguments for buildah, see https://www.mankier.com/1/buildah-build#--build-arg-file - name: build-args-file - type: string - - default: "false" - description: Whether to enable privileged mode, should be used only with remote VMs - name: privileged-nested - type: string - - name: enable-cache-proxy - default: 'false' - description: Enable cache proxy configuration - type: string - results: - - description: "" - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - description: "" - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - description: "" - name: CHAINS-GIT_URL - value: $(tasks.clone-repository.results.url) - - description: "" - name: CHAINS-GIT_COMMIT - value: $(tasks.clone-repository.results.commit) - tasks: - - name: init - params: - - name: image-url - value: $(params.output-image) - - name: rebuild - value: $(params.rebuild) - - name: skip-checks - value: $(params.skip-checks) - - name: enable-cache-proxy - value: $(params.enable-cache-proxy) - taskRef: - params: - - name: name - value: init - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-init:0.2@sha256:ebf06778aeacbbeb081f9231eafbdfdb8e380ad04e211d7ed80ae9101e37fd82 - - name: kind - value: task - resolver: bundles - - name: clone-repository - params: - - name: url - value: $(params.git-url) - - name: revision - value: $(params.revision) - - name: ociStorage - value: $(params.output-image).git - - name: ociArtifactExpiresAfter - value: $(params.image-expires-after) - runAfter: - - init - taskRef: - params: - - name: name - value: git-clone-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-git-clone-oci-ta:0.1@sha256:306b69e6db435ad4a7cf258b6219d9b998eb37da44f5e9ac882ac86a08109154 - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - workspaces: - - name: basic-auth - workspace: git-auth - - name: prefetch-dependencies - params: - - name: input - value: $(params.prefetch-input) - - name: SOURCE_ARTIFACT - value: $(tasks.clone-repository.results.SOURCE_ARTIFACT) - - name: ociStorage - value: $(params.output-image).prefetch - - name: ociArtifactExpiresAfter - value: $(params.image-expires-after) - runAfter: - - clone-repository - taskRef: - params: - - name: name - value: prefetch-dependencies-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-prefetch-dependencies-oci-ta:0.2@sha256:c664a6df6514b59c3ce53570b0994b45af66ecc89ba2a8e41834eae0622addf6 - - name: kind - value: task - resolver: bundles - workspaces: - - name: git-basic-auth - workspace: git-auth - - name: netrc - workspace: netrc - - name: build-container - params: - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: PRIVILEGED_NESTED - value: $(params.privileged-nested) - - name: SOURCE_URL - value: $(tasks.clone-repository.results.url) - - name: BUILDAH_FORMAT - value: $(params.buildah-format) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - - name: HTTP_PROXY - value: $(tasks.init.results.http-proxy) - - name: NO_PROXY - value: $(tasks.init.results.no-proxy) - runAfter: - - prefetch-dependencies - taskRef: - params: - - name: name - value: buildah-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-buildah-oci-ta:0.8@sha256:8a984185d22d3180ecd575dbf6b6a63edb1b3ec754be0b8e5e4247a9eae9112b - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - name: build-image-index - params: - - name: IMAGE - value: $(params.output-image) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: ALWAYS_BUILD_INDEX - value: $(params.build-image-index) - - name: IMAGES - value: - - $(tasks.build-container.results.IMAGE_URL)@$(tasks.build-container.results.IMAGE_DIGEST) - - name: BUILDAH_FORMAT - value: $(params.buildah-format) - runAfter: - - build-container - taskRef: - params: - - name: name - value: build-image-index - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-build-image-index:0.2@sha256:05d3d8a5ded44c51b074a56a408ddf5d65c56b4c15e110abb1a99e3aff269d49 - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - name: build-source-image - params: - - name: BINARY_IMAGE - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: BINARY_IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: source-build-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-source-build-oci-ta:0.3@sha256:c35ba219390d77a48ee19347e5ee8d13e5c23e3984299e02291d6da1ed8a986c - - name: kind - value: task - resolver: bundles - when: - - input: $(tasks.init.results.build) - operator: in - values: - - "true" - - input: $(params.build-source-image) - operator: in - values: - - "true" - - name: deprecated-base-image-check - params: - - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: deprecated-image-check - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-deprecated-image-check:0.5@sha256:e3a55ccdf1091b4a35507f9ee2d1918d8e89a5f96babcb5486b491226da03d6f - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: clair-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: clair-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clair-scan:0.3@sha256:dadfea7633d82e4303ba73d5e9c7e2bc16834bde0fd7688880453b26452067eb - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: ecosystem-cert-preflight-checks - params: - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: ecosystem-cert-preflight-checks - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-ecosystem-cert-preflight-checks:0.2@sha256:204fd3914d83c7b60e8eee72b5a944337720c79a3e660e7c994435456dcf7175 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-snyk-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-snyk-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-snyk-check-oci-ta:0.4@sha256:a70272ae12f6d7f0da2902158e1bcee756877aa8f71fd1a22ef9afd8b177fb41 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: clamav-scan - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: clamav-scan - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-clamav-scan:0.3@sha256:76efc0119a10bc8a420dbbb0cdab9ef8eafd263f6827498d2b644e450e93f446 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-coverity-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE - value: $(params.output-image) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: HERMETIC - value: $(params.hermetic) - - name: PREFETCH_INPUT - value: $(params.prefetch-input) - - name: IMAGE_EXPIRES_AFTER - value: $(params.image-expires-after) - - name: COMMIT_SHA - value: $(tasks.clone-repository.results.commit) - - name: BUILD_ARGS - value: - - $(params.build-args[*]) - - name: BUILD_ARGS_FILE - value: $(params.build-args-file) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - coverity-availability-check - taskRef: - params: - - name: name - value: sast-coverity-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-coverity-check-oci-ta:0.3@sha256:9d0bc704bca6b6faad37b2ce8106b96e0cef35e1f647d037a878bf416589de9d - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - input: $(tasks.coverity-availability-check.results.STATUS) - operator: in - values: - - success - - name: coverity-availability-check - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: coverity-availability-check - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-coverity-availability-check:0.2@sha256:267d5bc069a0323f41e24732ddfd1057e5c639e853d1e620c67505fab78f1301 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-shell-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-shell-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-shell-check-oci-ta:0.1@sha256:e7a51575f9188a1461d4520da25aaa4efdd3b896c97dc750941fa22840e55c13 - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: sast-unicode-check - params: - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - - name: CACHI2_ARTIFACT - value: $(tasks.prefetch-dependencies.results.CACHI2_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: sast-unicode-check-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-sast-unicode-check-oci-ta:0.4@sha256:1818a5b3e4fa86c838ae71226a157241967d1f19c5ed377e4b2fddad7a3ceefe - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - - name: apply-tags - params: - - name: IMAGE_URL - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: apply-tags - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-apply-tags:0.3@sha256:510b6d2a3b188adeb716e49566b57d611ab36bd69a2794b5ddfc11dbf014c2ca - - name: kind - value: task - resolver: bundles - - name: push-dockerfile - params: - - name: IMAGE - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: IMAGE_DIGEST - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - - name: DOCKERFILE - value: $(params.dockerfile) - - name: CONTEXT - value: $(params.path-context) - - name: SOURCE_ARTIFACT - value: $(tasks.prefetch-dependencies.results.SOURCE_ARTIFACT) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: push-dockerfile-oci-ta - - name: bundle - value: quay.io/konflux-ci/tekton-catalog/task-push-dockerfile-oci-ta:0.1@sha256:08bba4a659ecd48f871bef00b80af58954e5a09fcbb28a1783ddd640c4f6535e - - name: kind - value: task - resolver: bundles - - name: rpms-signature-scan - params: - - name: image-url - value: $(tasks.build-image-index.results.IMAGE_URL) - - name: image-digest - value: $(tasks.build-image-index.results.IMAGE_DIGEST) - runAfter: - - build-image-index - taskRef: - params: - - name: name - value: rpms-signature-scan - - name: bundle - value: quay.io/konflux-ci/konflux-vanguard/task-rpms-signature-scan:0.2@sha256:3d016c63bcab64ab82da762a52b013c0bcb534e9523b8c0e073cc3a0c02f0cac - - name: kind - value: task - resolver: bundles - when: - - input: $(params.skip-checks) - operator: in - values: - - "false" - workspaces: - - name: git-auth - optional: true - - name: netrc - optional: true - taskRunTemplate: - serviceAccountName: build-pipeline-devlake-frontend-ba03c - workspaces: - - name: git-auth - secret: - secretName: '{{ git_auth_secret }}' -status: {}