-
-
Notifications
You must be signed in to change notification settings - Fork 766
XOAUTH2 Authentication Mechanism for SMTP #1432
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
FreakIsTea
wants to merge
5
commits into
getfider:main
Choose a base branch
from
keeValue:feature/smtp-oauth
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a1cef65
feat: add xoauth2 for smtp with client credentials flow
FreakIsTea 0ad0940
Merge branch 'getfider:main' into feature/smtp-oauth
FreakIsTea 60068c2
fix: change naming to match correct naming for agnostic auth
FreakIsTea b6e1e35
feat: add token caching with ReuseTokenSource
FreakIsTea 24b2223
Merge branch 'main' into feature/smtp-oauth
FreakIsTea File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| package smtp | ||
|
|
||
| import ( | ||
| "fmt" | ||
| gosmtp "net/smtp" | ||
|
|
||
| "github.com/getfider/fider/app/pkg/errors" | ||
| ) | ||
|
|
||
| type xoauth2Auth struct { | ||
| user string | ||
| token string | ||
| host string | ||
| } | ||
|
|
||
| func XOAuth2Auth(user, token, host string) gosmtp.Auth { | ||
| return &xoauth2Auth{ | ||
| user: user, | ||
| token: token, | ||
| host: host, | ||
| } | ||
| } | ||
|
|
||
| func (a *xoauth2Auth) Start(server *gosmtp.ServerInfo) (proto string, toServer []byte, err error) { | ||
| if server.Name != a.host { | ||
| return "", nil, errors.New("smtp: wrong host name") | ||
| } | ||
|
|
||
| if !server.TLS { | ||
| return "", nil, errors.New("smtp: XOAUTH2 requires TLS") | ||
| } | ||
|
Comment on lines
+29
to
+31
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. XOAUTH2 requires TLS, but EMAIL_SMTP_ENABLE_STARTTLS can be disabled. Would be nice to verify this all in case "smtp":
mustBeSet("EMAIL_SMTP_HOST")
mustBeSet("EMAIL_SMTP_PORT")
// Validate auth mechanism if explicitly set
authMech := strings.ToUpper(strings.TrimSpace(Config.Email.SMTP.AuthMechanism))
switch authMech {
case "", "AGNOSTIC":
// Username/password are optional - supports unauthenticated SMTP
case "XOAUTH2":
// If explicitly choosing XOAUTH2, OAuth credentials are required
mustBeSet("EMAIL_SMTP_OAUTH_CLIENT_ID")
mustBeSet("EMAIL_SMTP_OAUTH_CLIENT_SECRET")
mustBeSet("EMAIL_SMTP_OAUTH_TOKEN_URL")
mustBeSet("EMAIL_SMTP_USERNAME") // Used as the OAuth user
if !Config.Email.SMTP.EnableStartTLS {
panic("XOAUTH2 requires STARTTLS to be enabled (set EMAIL_SMTP_ENABLE_STARTTLS=true)")
}
default:
// Fail fast on typos like "XOATH2" or "OAUTH2"
panic(fmt.Sprintf("invalid EMAIL_SMTP_AUTH_MECHANISM '%s' (valid options: AGNOSTIC, XOAUTH2)", authMech))
}
} |
||
|
|
||
| resp := fmt.Sprintf("user=%s\x01auth=Bearer %s\x01\x01", a.user, a.token) | ||
| return "XOAUTH2", []byte(resp), nil | ||
| } | ||
|
|
||
| func (a *xoauth2Auth) Next(fromServer []byte, more bool) ([]byte, error) { | ||
| if more { | ||
| return nil, errors.New("smtp: unexpected server challenge for XOAUTH2") | ||
| } | ||
| return nil, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| package smtp | ||
|
|
||
| import ( | ||
| "context" | ||
| "strings" | ||
|
|
||
| "golang.org/x/oauth2" | ||
| "golang.org/x/oauth2/clientcredentials" | ||
|
|
||
| "github.com/getfider/fider/app/pkg/errors" | ||
| ) | ||
|
|
||
| func splitCommaScopes(raw string) []string { | ||
| if strings.TrimSpace(raw) == "" { | ||
| return nil | ||
| } | ||
| parts := strings.Split(raw, ",") | ||
| out := make([]string, 0, len(parts)) | ||
| for _, p := range parts { | ||
| p = strings.TrimSpace(p) | ||
| if p != "" { | ||
| out = append(out, p) | ||
| } | ||
| } | ||
| return out | ||
| } | ||
|
|
||
| func getClientCredentialsToken(ctx context.Context, tokenURL, clientID, clientSecret string, scopes []string) (string, error) { | ||
| if tokenURL == "" { | ||
| return "", errors.New("smtp: oauth token url is required") | ||
| } | ||
| if clientID == "" || clientSecret == "" { | ||
| return "", errors.New("smtp: oauth client id/secret are required") | ||
| } | ||
|
|
||
| key := tokenSourceKey(tokenURL, clientID, scopes) | ||
|
|
||
| tokenSourceMu.Lock() | ||
| tokenSource, ok := tokenSourceByKey[key] | ||
| if !ok { | ||
| conf := clientcredentials.Config{ | ||
| ClientID: clientID, | ||
| ClientSecret: clientSecret, | ||
| TokenURL: tokenURL, | ||
| Scopes: scopes, | ||
| } | ||
|
|
||
| base := conf.TokenSource(ctx) | ||
| tokenSource = oauth2.ReuseTokenSource(nil, base) | ||
| tokenSourceByKey[key] = tokenSource | ||
| } | ||
| tokenSourceMu.Unlock() | ||
|
|
||
| tok, err := tokenSource.Token() | ||
| if err != nil { | ||
| return "", errors.Wrap(err, "smtp: failed to fetch oauth token") | ||
| } | ||
| if tok == nil || tok.AccessToken == "" { | ||
| return "", errors.New("smtp: oauth returned empty access token") | ||
| } | ||
| return tok.AccessToken, nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| package smtp | ||
|
|
||
| import ( | ||
| "crypto/sha256" | ||
| "encoding/hex" | ||
| "sort" | ||
| "strings" | ||
| "sync" | ||
|
|
||
| "golang.org/x/oauth2" | ||
| ) | ||
|
|
||
| var ( | ||
| tokenSourceMu sync.Mutex | ||
| tokenSourceByKey = map[string]oauth2.TokenSource{} | ||
| ) | ||
|
|
||
| func tokenSourceKey(tokenURL, clientID string, scopes []string) string { | ||
| normalized := make([]string, 0, len(scopes)) | ||
| for _, scope := range scopes { | ||
| scope = strings.TrimSpace(scope) | ||
| if scope != "" { | ||
| normalized = append(normalized, scope) | ||
| } | ||
| } | ||
| sort.Strings(normalized) | ||
|
|
||
| sum := sha256.Sum256([]byte(tokenURL + "|" + clientID + "|" + strings.Join(normalized, ","))) | ||
| return hex.EncodeToString(sum[:]) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would you mind changing the suffix to be upper case, e.g
ClientIDandTokenURL- for consistency, ta