Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions server/githuberrors/saml.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright (c) 2018-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

package githuberrors

import (
"net/http"
"strings"

"github.com/google/go-github/v54/github"
"github.com/pkg/errors"
)

const samlEnforcementMessage = "organization saml enforcement"

// IsSAMLSSORequired reports whether err indicates GitHub rejected the request
// because the OAuth token lacks SAML SSO authorization for an organization.
func IsSAMLSSORequired(err error) bool {
if err == nil {
return false
}

var ghErr *github.ErrorResponse
if errors.As(err, &ghErr) && ghErr.Response != nil {
if ssoHeader := ghErr.Response.Header.Get("X-GitHub-SSO"); ssoHeader != "" {
lower := strings.ToLower(ssoHeader)
if strings.Contains(lower, "required") || strings.Contains(lower, "partial-results") {
return true
}
}

if ghErr.Response.StatusCode == http.StatusForbidden && containsSAMLMessage(ghErr.Message) {
return true
}
}

return containsSAMLMessage(errorMessage(err))
}

func errorMessage(err error) string {
var ghErr *github.ErrorResponse
if errors.As(err, &ghErr) && ghErr.Message != "" {
return ghErr.Message
}

return err.Error()
}

func containsSAMLMessage(message string) bool {
return strings.Contains(strings.ToLower(message), samlEnforcementMessage)
}
62 changes: 62 additions & 0 deletions server/githuberrors/saml_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright (c) 2018-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

package githuberrors

import (
"net/http"
"testing"

"github.com/google/go-github/v54/github"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
)

func TestIsSAMLSSORequired(t *testing.T) {
t.Run("nil error", func(t *testing.T) {
assert.False(t, IsSAMLSSORequired(nil))
})

t.Run("unrelated error", func(t *testing.T) {
assert.False(t, IsSAMLSSORequired(errors.New("something went wrong")))
})

t.Run("403 github error with SAML message", func(t *testing.T) {
err := &github.ErrorResponse{
Response: &http.Response{StatusCode: http.StatusForbidden},
Message: "Resource protected by organization SAML enforcement. You must grant your personal token access to this organization.",
}
assert.True(t, IsSAMLSSORequired(err))
})

t.Run("403 github error without SAML message", func(t *testing.T) {
err := &github.ErrorResponse{
Response: &http.Response{StatusCode: http.StatusForbidden},
Message: "Resource not accessible by integration",
}
assert.False(t, IsSAMLSSORequired(err))
})

t.Run("X-GitHub-SSO required header", func(t *testing.T) {
resp := &http.Response{
StatusCode: http.StatusForbidden,
Header: http.Header{"X-Github-Sso": {"required; url=https://github.com/orgs/acme/sso"}},
}
err := &github.ErrorResponse{Response: resp, Message: "Forbidden"}
assert.True(t, IsSAMLSSORequired(err))
})

t.Run("X-GitHub-SSO partial-results header", func(t *testing.T) {
resp := &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"X-Github-Sso": {"partial-results; organizations=123,456"}},
}
err := &github.ErrorResponse{Response: resp}
assert.True(t, IsSAMLSSORequired(err))
})

t.Run("graphql wrapped SAML error", func(t *testing.T) {
err := errors.Wrap(errors.New("GraphQL: Resource protected by organization SAML enforcement. You must grant your Personal Access token access to this organization."), "error in executing query")
assert.True(t, IsSAMLSSORequired(err))
})
}
45 changes: 34 additions & 11 deletions server/plugin/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,11 @@ type FilteredNotification struct {
}

type SidebarContent struct {
PRs []*graphql.GithubPRDetails `json:"prs"`
Reviews []*graphql.GithubPRDetails `json:"reviews"`
Assignments []*github.Issue `json:"assignments"`
Unreads []*FilteredNotification `json:"unreads"`
PRs []*graphql.GithubPRDetails `json:"prs"`
Reviews []*graphql.GithubPRDetails `json:"reviews"`
Assignments []*github.Issue `json:"assignments"`
Unreads []*FilteredNotification `json:"unreads"`
SAMLSSOMessage string `json:"saml_sso_message,omitempty"`
}

type Context struct {
Expand Down Expand Up @@ -463,6 +464,8 @@ func (p *Plugin) completeConnectUserToGitHub(c *Context, w http.ResponseWriter,
return
}

p.clearSAMLSSONotification(state.UserID)

if err = p.storeGitHubToUserIDMapping(gitUser.GetLogin(), state.UserID); err != nil {
c.Log.WithError(err).Warnf("Failed to store GitHub user info mapping")
}
Expand Down Expand Up @@ -815,6 +818,7 @@ func (p *Plugin) fetchPRDetails(c *UserContext, client *github.Client, prURL str
wg.Go(func() {
fetchedReviews, err := fetchReviews(c, client, repoOwner, repoName, prNumber)
if err != nil {
p.handleGitHubAPIError(c, err)
c.Log.WithError(err).Warnf("Failed to fetch reviews for PR details")
return
}
Expand All @@ -825,6 +829,7 @@ func (p *Plugin) fetchPRDetails(c *UserContext, client *github.Client, prURL str
wg.Go(func() {
prInfo, _, err := client.PullRequests.Get(c.Ctx, repoOwner, repoName, prNumber)
if err != nil {
p.handleGitHubAPIError(c, err)
c.Log.WithError(err).Warnf("Failed to fetch PR for PR details")
return
}
Expand All @@ -836,6 +841,7 @@ func (p *Plugin) fetchPRDetails(c *UserContext, client *github.Client, prURL str
}
statuses, _, err := client.Repositories.GetCombinedStatus(c.Ctx, repoOwner, repoName, prInfo.GetHead().GetSHA(), nil)
if err != nil {
p.handleGitHubAPIError(c, err)
c.Log.WithError(err).Warnf("Failed to fetch combined status")
return
}
Expand Down Expand Up @@ -1096,31 +1102,40 @@ func (p *Plugin) createIssueComment(c *UserContext, w http.ResponseWriter, r *ht
p.writeJSON(w, result)
}

func (p *Plugin) getLHSData(c *UserContext) (reviewResp []*graphql.GithubPRDetails, assignmentResp []*github.Issue, openPRResp []*graphql.GithubPRDetails, err error) {
func (p *Plugin) getLHSData(c *UserContext) (reviewResp []*graphql.GithubPRDetails, assignmentResp []*github.Issue, openPRResp []*graphql.GithubPRDetails, samlSSORequired bool, err error) {
graphQLClient := p.graphQLConnect(c.GHInfo)

reviewResp, assignmentResp, openPRResp, err = graphQLClient.GetLHSData(c.Ctx)
reviewResp, assignmentResp, openPRResp, samlSSORequired, err = graphQLClient.GetLHSData(c.Ctx)
if err != nil {
return []*graphql.GithubPRDetails{}, []*github.Issue{}, []*graphql.GithubPRDetails{}, err
return []*graphql.GithubPRDetails{}, []*github.Issue{}, []*graphql.GithubPRDetails{}, samlSSORequired, err
}

if samlSSORequired {
p.notifySAMLSSORequired(c.UserID)
}

return reviewResp, assignmentResp, openPRResp, nil
return reviewResp, assignmentResp, openPRResp, samlSSORequired, nil
}

func (p *Plugin) getSidebarData(c *UserContext) (*SidebarContent, error) {
reviewResp, assignmentResp, openPRResp, err := p.getLHSData(c)
reviewResp, assignmentResp, openPRResp, samlSSORequired, err := p.getLHSData(c)
if err != nil {
return nil, err
}

p.enrichReviewsWithSLAStart(reviewResp, c.GHInfo.GitHubUsername)

return &SidebarContent{
content := &SidebarContent{
PRs: openPRResp,
Assignments: assignmentResp,
Reviews: reviewResp,
Unreads: p.getUnreadsData(c),
}, nil
}
if samlSSORequired {
content.SAMLSSOMessage = samlSSOUserMessage
}

return content, nil
}

func (p *Plugin) getSidebarContent(c *UserContext, w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -1212,6 +1227,10 @@ func (p *Plugin) getIssueByNumber(c *UserContext, w http.ResponseWriter, r *http
return
}

if p.writeSAMLSSOErrorIfNeeded(c, w, cErr) {
return
}

c.Log.WithError(cErr).With(logger.LogContext{
"owner": owner,
"repo": repo,
Expand Down Expand Up @@ -1260,6 +1279,10 @@ func (p *Plugin) getPrByNumber(c *UserContext, w http.ResponseWriter, r *http.Re
return
}

if p.writeSAMLSSOErrorIfNeeded(c, w, cErr) {
return
}

c.Log.WithError(cErr).With(logger.LogContext{
"owner": owner,
"repo": repo,
Expand Down
22 changes: 15 additions & 7 deletions server/plugin/graphql/lhs_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"github.com/google/go-github/v54/github"
"github.com/pkg/errors"
"github.com/shurcooL/githubv4"

"github.com/mattermost/mattermost-plugin-github/server/githuberrors"
)

const (
Expand All @@ -31,24 +33,25 @@ type GithubPRDetails struct {
ReviewSLAStartAt *string `json:"review_sla_start,omitempty"`
}

func (c *Client) GetLHSData(ctx context.Context) ([]*GithubPRDetails, []*github.Issue, []*GithubPRDetails, error) {
func (c *Client) GetLHSData(ctx context.Context) ([]*GithubPRDetails, []*github.Issue, []*GithubPRDetails, bool, error) {
orgsList := c.getOrganizations()
var resultAssignee []*github.Issue
var resultReview, resultOpenPR []*GithubPRDetails
var samlSSORequired bool

var err error
for _, org := range orgsList {
resultReview, resultAssignee, resultOpenPR, err = c.fetchLHSData(ctx, resultReview, resultAssignee, resultOpenPR, org, c.username)
resultReview, resultAssignee, resultOpenPR, samlSSORequired, err = c.fetchLHSData(ctx, resultReview, resultAssignee, resultOpenPR, org, c.username, samlSSORequired)
if err != nil {
c.logger.Error("Error fetching LHS data for org", "org", org, "error", err.Error())
}
}

if len(orgsList) == 0 {
return c.fetchLHSData(ctx, resultReview, resultAssignee, resultOpenPR, "", c.username)
return c.fetchLHSData(ctx, resultReview, resultAssignee, resultOpenPR, "", c.username, samlSSORequired)
}

return resultReview, resultAssignee, resultOpenPR, nil
return resultReview, resultAssignee, resultOpenPR, samlSSORequired, nil
}

func (c *Client) fetchLHSData(
Expand All @@ -58,7 +61,8 @@ func (c *Client) fetchLHSData(
resultOpenPR []*GithubPRDetails,
org string,
username string,
) ([]*GithubPRDetails, []*github.Issue, []*GithubPRDetails, error) {
samlSSORequired bool,
) ([]*GithubPRDetails, []*github.Issue, []*GithubPRDetails, bool, error) {
baseOpenPR := fmt.Sprintf("author:%s is:pr is:%s archived:false", username, githubv4.PullRequestStateOpen)
baseReviewPR := fmt.Sprintf("review-requested:%s is:pr is:%s archived:false", username, githubv4.PullRequestStateOpen)
baseAssignee := fmt.Sprintf("assignee:%s is:%s archived:false", username, githubv4.PullRequestStateOpen)
Expand All @@ -82,7 +86,11 @@ func (c *Client) fetchLHSData(

for !allReviewRequestsFetched || !allAssignmentsFetched || !allOpenPRsFetched {
if err := c.executeQuery(ctx, &mainQuery, params); err != nil {
return nil, nil, nil, errors.Wrap(err, "Not able to execute the query")
if githuberrors.IsSAMLSSORequired(err) {
samlSSORequired = true
return resultReview, resultAssignee, resultOpenPR, samlSSORequired, nil
}
return nil, nil, nil, samlSSORequired, errors.Wrap(err, "Not able to execute the query")
}

if !allReviewRequestsFetched {
Expand Down Expand Up @@ -128,7 +136,7 @@ func (c *Client) fetchLHSData(
}
}

return resultReview, resultAssignee, resultOpenPR, nil
return resultReview, resultAssignee, resultOpenPR, samlSSORequired, nil
}

func getPR(prResp *prSearchNodes) *GithubPRDetails {
Expand Down
6 changes: 6 additions & 0 deletions server/plugin/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,8 @@ func (p *Plugin) getGitHubToUsernameMapping(githubUsername string) string {
}

func (p *Plugin) disconnectGitHubAccount(userID string) {
p.clearSAMLSSONotification(userID)

userInfo, apiErr := p.getGitHubUserInfo(userID)
if apiErr != nil {
if apiErr.ID == apiErrorIDNotConnected {
Expand Down Expand Up @@ -1353,6 +1355,10 @@ func (p *Plugin) useGitHubClient(info *GitHubUserInfo, toRun func(info *GitHubUs
p.handleRevokedToken(info)
}

if err != nil {
p.handleGitHubAPIError(&UserContext{Context: Context{UserID: info.UserID}, GHInfo: info}, err)
}

return err
}

Expand Down
56 changes: 56 additions & 0 deletions server/plugin/saml_sso.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright (c) 2018-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

package plugin

import (
"net/http"

"github.com/mattermost/mattermost-plugin-github/server/githuberrors"
)

const (
apiErrorIDSAMLSSORequired = "saml_sso_required"
samlSSONotifiedKey = "_samlSSONotified"

samlSSOUserMessage = "GitHub is rejecting API requests because SAML SSO authorization is required for one or more organizations. Run `/github disconnect` and then `/github connect` again. When prompted on GitHub, authorize access for your organizations."
)

func (p *Plugin) notifySAMLSSORequired(userID string) {
key := userID + samlSSONotifiedKey
var notified bool
if err := p.store.Get(key, &notified); err == nil && notified {
return
}

p.CreateBotDMPost(userID, samlSSOUserMessage, "custom_git_saml_sso")
if _, err := p.store.Set(key, true); err != nil {
p.client.Log.Warn("Failed to store SAML SSO notification state", "userID", userID, "error", err.Error())
}
Comment on lines +19 to +29

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Make the notification claim atomic.

notifySAMLSSORequired does GetCreateBotDMPostSet, so two concurrent SAML failures can both observe "not notified" and each send a DM before either writes the flag. server/plugin/api.go, Lines 818-845 already invoke this path from parallel goroutines, so the dedup guarantee is racy. Claim the KV key atomically, or otherwise serialize this section across callers, before posting.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@server/plugin/saml_sso.go` around lines 19 - 29, The SAML SSO notification
flow in notifySAMLSSORequired is racy because it does Get, then CreateBotDMPost,
then Set, allowing concurrent callers from the API path to send duplicate DMs.
Update the logic to atomically claim the samlSSONotifiedKey before posting, or
otherwise serialize access around the check-and-set sequence, so only one
goroutine can proceed to CreateBotDMPost. Keep the existing store and logging
flow in the Plugin method, but make the notification state transition happen as
a single guarded operation.

}

func (p *Plugin) clearSAMLSSONotification(userID string) {
if err := p.store.Delete(userID + samlSSONotifiedKey); err != nil {
p.client.Log.Debug("Failed to clear SAML SSO notification state", "userID", userID, "error", err.Error())
}
}

func (p *Plugin) writeSAMLSSOErrorIfNeeded(c *UserContext, w http.ResponseWriter, err error) bool {
if !githuberrors.IsSAMLSSORequired(err) {
return false
}

p.notifySAMLSSORequired(c.UserID)
p.writeAPIError(w, &APIErrorResponse{
ID: apiErrorIDSAMLSSORequired,
Message: samlSSOUserMessage,
StatusCode: http.StatusForbidden,
})
return true
}

func (p *Plugin) handleGitHubAPIError(c *UserContext, err error) {
if githuberrors.IsSAMLSSORequired(err) {
p.notifySAMLSSORequired(c.UserID)
}
}
Loading
Loading