From 0df253964123537b91e5a7364c83cc52f0e88df4 Mon Sep 17 00:00:00 2001 From: Wim Date: Sat, 28 Mar 2020 23:44:49 +0100 Subject: Use upstream yaegashi/msgraph.go/msauth (msteams) (#1067) --- bridge/msteams/msteams.go | 3 +- go.mod | 1 - go.sum | 4 - vendor/github.com/matterbridge/msgraph.go/LICENSE | 201 --------------------- .../matterbridge/msgraph.go/msauth/README.md | 70 ------- .../msgraph.go/msauth/client_credentials_grant.go | 27 --- .../msauth/device_authorization_grant.go | 96 ---------- .../matterbridge/msgraph.go/msauth/msauth.go | 148 --------------- .../yaegashi/msgraph.go/msauth/README.md | 70 +++++++ .../msgraph.go/msauth/client_credentials_grant.go | 27 +++ .../msauth/device_authorization_grant.go | 96 ++++++++++ .../yaegashi/msgraph.go/msauth/msauth.go | 148 +++++++++++++++ vendor/modules.txt | 3 +- 13 files changed, 343 insertions(+), 551 deletions(-) delete mode 100644 vendor/github.com/matterbridge/msgraph.go/LICENSE delete mode 100644 vendor/github.com/matterbridge/msgraph.go/msauth/README.md delete mode 100644 vendor/github.com/matterbridge/msgraph.go/msauth/client_credentials_grant.go delete mode 100644 vendor/github.com/matterbridge/msgraph.go/msauth/device_authorization_grant.go delete mode 100644 vendor/github.com/matterbridge/msgraph.go/msauth/msauth.go create mode 100644 vendor/github.com/yaegashi/msgraph.go/msauth/README.md create mode 100644 vendor/github.com/yaegashi/msgraph.go/msauth/client_credentials_grant.go create mode 100644 vendor/github.com/yaegashi/msgraph.go/msauth/device_authorization_grant.go create mode 100644 vendor/github.com/yaegashi/msgraph.go/msauth/msauth.go diff --git a/bridge/msteams/msteams.go b/bridge/msteams/msteams.go index 06964085..b3540d08 100644 --- a/bridge/msteams/msteams.go +++ b/bridge/msteams/msteams.go @@ -11,10 +11,9 @@ import ( "github.com/42wim/matterbridge/bridge" "github.com/42wim/matterbridge/bridge/config" - // "github.com/davecgh/go-spew/spew" - "github.com/matterbridge/msgraph.go/msauth" "github.com/mattn/godown" msgraph "github.com/yaegashi/msgraph.go/beta" + "github.com/yaegashi/msgraph.go/msauth" "golang.org/x/oauth2" ) diff --git a/go.mod b/go.mod index 272958cf..cd77f53e 100644 --- a/go.mod +++ b/go.mod @@ -28,7 +28,6 @@ require ( github.com/matterbridge/gomatrix v0.0.0-20200209224845-c2104d7936a6 github.com/matterbridge/gozulipbot v0.0.0-20190212232658-7aa251978a18 github.com/matterbridge/logrus-prefixed-formatter v0.0.0-20180806162718-01618749af61 - github.com/matterbridge/msgraph.go v0.0.0-20200308150230-9e043fe9dbaa github.com/mattermost/mattermost-server v5.5.0+incompatible github.com/mattn/go-runewidth v0.0.7 // indirect github.com/mattn/godown v0.0.0-20180312012330-2e9e17e0ea51 diff --git a/go.sum b/go.sum index e4db1b30..94488e8d 100644 --- a/go.sum +++ b/go.sum @@ -138,8 +138,6 @@ github.com/matterbridge/gozulipbot v0.0.0-20190212232658-7aa251978a18 h1:fLhwXtW github.com/matterbridge/gozulipbot v0.0.0-20190212232658-7aa251978a18/go.mod h1:yAjnZ34DuDyPHMPHHjOsTk/FefW4JJjoMMCGt/8uuQA= github.com/matterbridge/logrus-prefixed-formatter v0.0.0-20180806162718-01618749af61 h1:R/MgM/eUyRBQx2FiH6JVmXck8PaAuKfe2M1tWIzW7nE= github.com/matterbridge/logrus-prefixed-formatter v0.0.0-20180806162718-01618749af61/go.mod h1:iXGEotOvwI1R1SjLxRc+BF5rUORTMtE0iMZBT2lxqAU= -github.com/matterbridge/msgraph.go v0.0.0-20200308150230-9e043fe9dbaa h1:ZP87nK5Mhgvt6Rpgbztdmq9+6cb3aZ6MgW/JWKbnMrI= -github.com/matterbridge/msgraph.go v0.0.0-20200308150230-9e043fe9dbaa/go.mod h1:l0kx9L8Z+NbBCGrQ/y+ldKZ/fiwBZjPoXwDS55LTumI= github.com/mattermost/mattermost-server v5.5.0+incompatible h1:0wcLGgYtd+YImtLDPf2AOfpBHxbU4suATx+6XKw1XbU= github.com/mattermost/mattermost-server v5.5.0+incompatible/go.mod h1:5L6MjAec+XXQwMIt791Ganu45GKsSiM+I0tLR9wUj8Y= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= @@ -290,8 +288,6 @@ golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553 h1:efeOvDhwQ29Dj3SdAV/MJf8oukgn+8D8WgaCaRMchF8= golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= diff --git a/vendor/github.com/matterbridge/msgraph.go/LICENSE b/vendor/github.com/matterbridge/msgraph.go/LICENSE deleted file mode 100644 index 261eeb9e..00000000 --- a/vendor/github.com/matterbridge/msgraph.go/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed 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. diff --git a/vendor/github.com/matterbridge/msgraph.go/msauth/README.md b/vendor/github.com/matterbridge/msgraph.go/msauth/README.md deleted file mode 100644 index 43aead20..00000000 --- a/vendor/github.com/matterbridge/msgraph.go/msauth/README.md +++ /dev/null @@ -1,70 +0,0 @@ -# msauth - -## Introduction - -Very simple package to authorize applications against [Microsoft identity platform]. - -It utilizes [v2.0 endpoint] so that it can authorize users using both personal (Microsoft) and organizational (Azure AD) account. - -## Usage - -### Device authorization grant - -- [OAuth 2.0 device authorization grant flow] - -```go -const ( - tenantID = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" - clientID = "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY" - tokenCachePath = "token_cache.json" -) - -var scopes = []string{"openid", "profile", "offline_access", "User.Read", "Files.Read"} - - ctx := context.Background() - m := msauth.NewManager() - m.LoadFile(tokenCachePath) - ts, err := m.DeviceAuthorizationGrant(ctx, tenantID, clientID, scopes, nil) - if err != nil { - log.Fatal(err) - } - m.SaveFile(tokenCachePath) - - httpClient := oauth2.NewClient(ctx, ts) - ... -``` - -### Client credentials grant - -- [OAuth 2.0 client credentials grant flow] - -```go -const ( - tenantID = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" - clientID = "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY" - clientSecret = "ZZZZZZZZZZZZZZZZZZZZZZZZ" -) - -var scopes = []string{msauth.DefaultMSGraphScope} - - ctx := context.Background() - m := msauth.NewManager() - ts, err := m.ClientCredentialsGrant(ctx, tenantID, clientID, clientSecret, scopes) - if err != nil { - log.Fatal(err) - } - - httpClient := oauth2.NewClient(ctx, ts) - ... -``` - -### Authorization code grant - -- [OAuth 2.0 authorization code grant flow] -- Not yet implemented. - -[Microsoft identity platform]: https://docs.microsoft.com/en-us/azure/active-directory/develop/ -[v2.0 endpoint]: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-overview -[OAuth 2.0 device authorization grant flow]: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code -[OAuth 2.0 client credentials grant flow]: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow -[OAuth 2.0 authorization code grant flow]: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow \ No newline at end of file diff --git a/vendor/github.com/matterbridge/msgraph.go/msauth/client_credentials_grant.go b/vendor/github.com/matterbridge/msgraph.go/msauth/client_credentials_grant.go deleted file mode 100644 index bc50883d..00000000 --- a/vendor/github.com/matterbridge/msgraph.go/msauth/client_credentials_grant.go +++ /dev/null @@ -1,27 +0,0 @@ -package msauth - -import ( - "context" - - "golang.org/x/oauth2" - "golang.org/x/oauth2/clientcredentials" - "golang.org/x/oauth2/microsoft" -) - -// ClientCredentialsGrant performs OAuth 2.0 client credentials grant and returns auto-refreshing TokenSource -func (m *Manager) ClientCredentialsGrant(ctx context.Context, tenantID, clientID, clientSecret string, scopes []string) (oauth2.TokenSource, error) { - config := &clientcredentials.Config{ - ClientID: clientID, - ClientSecret: clientSecret, - TokenURL: microsoft.AzureADEndpoint(tenantID).TokenURL, - Scopes: scopes, - AuthStyle: oauth2.AuthStyleInParams, - } - var err error - ts := config.TokenSource(ctx) - _, err = ts.Token() - if err != nil { - return nil, err - } - return ts, nil -} diff --git a/vendor/github.com/matterbridge/msgraph.go/msauth/device_authorization_grant.go b/vendor/github.com/matterbridge/msgraph.go/msauth/device_authorization_grant.go deleted file mode 100644 index 4baafd8d..00000000 --- a/vendor/github.com/matterbridge/msgraph.go/msauth/device_authorization_grant.go +++ /dev/null @@ -1,96 +0,0 @@ -package msauth - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "os" - "strings" - "time" - - "golang.org/x/oauth2" - "golang.org/x/oauth2/microsoft" -) - -const ( - deviceCodeGrantType = "urn:ietf:params:oauth:grant-type:device_code" - authorizationPendingError = "authorization_pending" -) - -// DeviceCode is returned on device auth initiation -type DeviceCode struct { - DeviceCode string `json:"device_code"` - UserCode string `json:"user_code"` - VerificationURL string `json:"verification_url"` - ExpiresIn int `json:"expires_in"` - Interval int `json:"interval"` - Message string `json:"message"` -} - -// DeviceAuthorizationGrant performs OAuth 2.0 device authorization grant and returns auto-refreshing TokenSource -func (m *Manager) DeviceAuthorizationGrant(ctx context.Context, tenantID, clientID string, scopes []string, callback func(*DeviceCode) error) (oauth2.TokenSource, error) { - endpoint := microsoft.AzureADEndpoint(tenantID) - endpoint.AuthStyle = oauth2.AuthStyleInParams - config := &oauth2.Config{ - ClientID: clientID, - Endpoint: endpoint, - Scopes: scopes, - } - if t, ok := m.TokenCache[generateKey(tenantID, clientID)]; ok { - tt, err := config.TokenSource(ctx, t).Token() - if err == nil { - return config.TokenSource(ctx, tt), nil - } - if _, ok := err.(*oauth2.RetrieveError); !ok { - return nil, err - } - } - scope := strings.Join(scopes, " ") - res, err := http.PostForm(deviceCodeURL(tenantID), url.Values{"client_id": {clientID}, "scope": {scope}}) - if err != nil { - return nil, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - b, _ := ioutil.ReadAll(res.Body) - return nil, fmt.Errorf("%s: %s", res.Status, string(b)) - } - dc := &DeviceCode{} - dec := json.NewDecoder(res.Body) - err = dec.Decode(&dc) - if err != nil { - return nil, err - } - if callback != nil { - err = callback(dc) - if err != nil { - return nil, err - } - } else { - fmt.Fprintln(os.Stderr, dc.Message) - } - values := url.Values{ - "client_id": {clientID}, - "grant_type": {deviceCodeGrantType}, - "device_code": {dc.DeviceCode}, - } - interval := dc.Interval - if interval == 0 { - interval = 5 - } - for { - time.Sleep(time.Second * time.Duration(interval)) - token, err := m.requestToken(ctx, tenantID, clientID, values) - if err == nil { - m.Cache(tenantID, clientID, token) - return config.TokenSource(ctx, token), nil - } - tokenError, ok := err.(*TokenError) - if !ok || tokenError.ErrorObject != authorizationPendingError { - return nil, err - } - } -} diff --git a/vendor/github.com/matterbridge/msgraph.go/msauth/msauth.go b/vendor/github.com/matterbridge/msgraph.go/msauth/msauth.go deleted file mode 100644 index c2a86985..00000000 --- a/vendor/github.com/matterbridge/msgraph.go/msauth/msauth.go +++ /dev/null @@ -1,148 +0,0 @@ -// Package msauth implements a library to authorize against Microsoft identity platform: -// https://docs.microsoft.com/en-us/azure/active-directory/develop/ -// -// It utilizes v2.0 endpoint -// so it can authorize users with both personal (Microsoft) and organizational (Azure AD) account. -package msauth - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "sync" - "time" - - "golang.org/x/oauth2" -) - -const ( - // DefaultMSGraphScope is the default scope for MS Graph API - DefaultMSGraphScope = "https://graph.microsoft.com/.default" - endpointURLFormat = "https://login.microsoftonline.com/%s/oauth2/v2.0/%s" -) - -// TokenError is returned on failed authentication -type TokenError struct { - ErrorObject string `json:"error"` - ErrorDescription string `json:"error_description"` -} - -// Error implements error interface -func (t *TokenError) Error() string { - return fmt.Sprintf("%s: %s", t.ErrorObject, t.ErrorDescription) -} - -func generateKey(tenantID, clientID string) string { - return fmt.Sprintf("%s:%s", tenantID, clientID) -} - -func deviceCodeURL(tenantID string) string { - return fmt.Sprintf(endpointURLFormat, tenantID, "devicecode") -} - -func tokenURL(tenantID string) string { - return fmt.Sprintf(endpointURLFormat, tenantID, "token") -} - -type tokenJSON struct { - AccessToken string `json:"access_token"` - TokenType string `json:"token_type"` - RefreshToken string `json:"refresh_token"` - ExpiresIn int `json:"expires_in"` -} - -func (e *tokenJSON) expiry() (t time.Time) { - if v := e.ExpiresIn; v != 0 { - return time.Now().Add(time.Duration(v) * time.Second) - } - return -} - -// Manager is oauth2 token cache manager -type Manager struct { - mu sync.Mutex - TokenCache map[string]*oauth2.Token -} - -// NewManager returns a new Manager instance -func NewManager() *Manager { - return &Manager{TokenCache: map[string]*oauth2.Token{}} -} - -// LoadBytes loads token cache from opaque bytes (it's actually JSON) -func (m *Manager) LoadBytes(b []byte) error { - m.mu.Lock() - defer m.mu.Unlock() - return json.Unmarshal(b, &m.TokenCache) -} - -// SaveBytes saves token cache to opaque bytes (it's actually JSON) -func (m *Manager) SaveBytes() ([]byte, error) { - m.mu.Lock() - defer m.mu.Unlock() - return json.Marshal(m.TokenCache) -} - -// LoadFile loads token cache from file -func (m *Manager) LoadFile(path string) error { - b, err := ioutil.ReadFile(path) - if err != nil { - return err - } - return m.LoadBytes(b) -} - -// SaveFile saves token cache to file -func (m *Manager) SaveFile(path string) error { - b, err := m.SaveBytes() - if err != nil { - return err - } - return ioutil.WriteFile(path, b, 0644) -} - -// Cache stores a token into token cache -func (m *Manager) Cache(tenantID, clientID string, token *oauth2.Token) { - m.TokenCache[generateKey(tenantID, clientID)] = token -} - -// requestToken requests a token from the token endpoint -// TODO(ctx): use http client from ctx -func (m *Manager) requestToken(ctx context.Context, tenantID, clientID string, values url.Values) (*oauth2.Token, error) { - res, err := http.PostForm(tokenURL(tenantID), values) - if err != nil { - return nil, err - } - defer res.Body.Close() - b, err := ioutil.ReadAll(res.Body) - if err != nil { - return nil, err - } - if res.StatusCode != http.StatusOK { - var terr *TokenError - err = json.Unmarshal(b, &terr) - if err != nil { - return nil, err - } - return nil, terr - } - var tj *tokenJSON - err = json.Unmarshal(b, &tj) - if err != nil { - return nil, err - } - token := &oauth2.Token{ - AccessToken: tj.AccessToken, - TokenType: tj.TokenType, - RefreshToken: tj.RefreshToken, - Expiry: tj.expiry(), - } - if token.AccessToken == "" { - return nil, errors.New("msauth: server response missing access_token") - } - return token, nil -} diff --git a/vendor/github.com/yaegashi/msgraph.go/msauth/README.md b/vendor/github.com/yaegashi/msgraph.go/msauth/README.md new file mode 100644 index 00000000..43aead20 --- /dev/null +++ b/vendor/github.com/yaegashi/msgraph.go/msauth/README.md @@ -0,0 +1,70 @@ +# msauth + +## Introduction + +Very simple package to authorize applications against [Microsoft identity platform]. + +It utilizes [v2.0 endpoint] so that it can authorize users using both personal (Microsoft) and organizational (Azure AD) account. + +## Usage + +### Device authorization grant + +- [OAuth 2.0 device authorization grant flow] + +```go +const ( + tenantID = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" + clientID = "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY" + tokenCachePath = "token_cache.json" +) + +var scopes = []string{"openid", "profile", "offline_access", "User.Read", "Files.Read"} + + ctx := context.Background() + m := msauth.NewManager() + m.LoadFile(tokenCachePath) + ts, err := m.DeviceAuthorizationGrant(ctx, tenantID, clientID, scopes, nil) + if err != nil { + log.Fatal(err) + } + m.SaveFile(tokenCachePath) + + httpClient := oauth2.NewClient(ctx, ts) + ... +``` + +### Client credentials grant + +- [OAuth 2.0 client credentials grant flow] + +```go +const ( + tenantID = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" + clientID = "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY" + clientSecret = "ZZZZZZZZZZZZZZZZZZZZZZZZ" +) + +var scopes = []string{msauth.DefaultMSGraphScope} + + ctx := context.Background() + m := msauth.NewManager() + ts, err := m.ClientCredentialsGrant(ctx, tenantID, clientID, clientSecret, scopes) + if err != nil { + log.Fatal(err) + } + + httpClient := oauth2.NewClient(ctx, ts) + ... +``` + +### Authorization code grant + +- [OAuth 2.0 authorization code grant flow] +- Not yet implemented. + +[Microsoft identity platform]: https://docs.microsoft.com/en-us/azure/active-directory/develop/ +[v2.0 endpoint]: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-overview +[OAuth 2.0 device authorization grant flow]: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code +[OAuth 2.0 client credentials grant flow]: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow +[OAuth 2.0 authorization code grant flow]: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow \ No newline at end of file diff --git a/vendor/github.com/yaegashi/msgraph.go/msauth/client_credentials_grant.go b/vendor/github.com/yaegashi/msgraph.go/msauth/client_credentials_grant.go new file mode 100644 index 00000000..bc50883d --- /dev/null +++ b/vendor/github.com/yaegashi/msgraph.go/msauth/client_credentials_grant.go @@ -0,0 +1,27 @@ +package msauth + +import ( + "context" + + "golang.org/x/oauth2" + "golang.org/x/oauth2/clientcredentials" + "golang.org/x/oauth2/microsoft" +) + +// ClientCredentialsGrant performs OAuth 2.0 client credentials grant and returns auto-refreshing TokenSource +func (m *Manager) ClientCredentialsGrant(ctx context.Context, tenantID, clientID, clientSecret string, scopes []string) (oauth2.TokenSource, error) { + config := &clientcredentials.Config{ + ClientID: clientID, + ClientSecret: clientSecret, + TokenURL: microsoft.AzureADEndpoint(tenantID).TokenURL, + Scopes: scopes, + AuthStyle: oauth2.AuthStyleInParams, + } + var err error + ts := config.TokenSource(ctx) + _, err = ts.Token() + if err != nil { + return nil, err + } + return ts, nil +} diff --git a/vendor/github.com/yaegashi/msgraph.go/msauth/device_authorization_grant.go b/vendor/github.com/yaegashi/msgraph.go/msauth/device_authorization_grant.go new file mode 100644 index 00000000..4baafd8d --- /dev/null +++ b/vendor/github.com/yaegashi/msgraph.go/msauth/device_authorization_grant.go @@ -0,0 +1,96 @@ +package msauth + +import ( + "context" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "os" + "strings" + "time" + + "golang.org/x/oauth2" + "golang.org/x/oauth2/microsoft" +) + +const ( + deviceCodeGrantType = "urn:ietf:params:oauth:grant-type:device_code" + authorizationPendingError = "authorization_pending" +) + +// DeviceCode is returned on device auth initiation +type DeviceCode struct { + DeviceCode string `json:"device_code"` + UserCode string `json:"user_code"` + VerificationURL string `json:"verification_url"` + ExpiresIn int `json:"expires_in"` + Interval int `json:"interval"` + Message string `json:"message"` +} + +// DeviceAuthorizationGrant performs OAuth 2.0 device authorization grant and returns auto-refreshing TokenSource +func (m *Manager) DeviceAuthorizationGrant(ctx context.Context, tenantID, clientID string, scopes []string, callback func(*DeviceCode) error) (oauth2.TokenSource, error) { + endpoint := microsoft.AzureADEndpoint(tenantID) + endpoint.AuthStyle = oauth2.AuthStyleInParams + config := &oauth2.Config{ + ClientID: clientID, + Endpoint: endpoint, + Scopes: scopes, + } + if t, ok := m.TokenCache[generateKey(tenantID, clientID)]; ok { + tt, err := config.TokenSource(ctx, t).Token() + if err == nil { + return config.TokenSource(ctx, tt), nil + } + if _, ok := err.(*oauth2.RetrieveError); !ok { + return nil, err + } + } + scope := strings.Join(scopes, " ") + res, err := http.PostForm(deviceCodeURL(tenantID), url.Values{"client_id": {clientID}, "scope": {scope}}) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + b, _ := ioutil.ReadAll(res.Body) + return nil, fmt.Errorf("%s: %s", res.Status, string(b)) + } + dc := &DeviceCode{} + dec := json.NewDecoder(res.Body) + err = dec.Decode(&dc) + if err != nil { + return nil, err + } + if callback != nil { + err = callback(dc) + if err != nil { + return nil, err + } + } else { + fmt.Fprintln(os.Stderr, dc.Message) + } + values := url.Values{ + "client_id": {clientID}, + "grant_type": {deviceCodeGrantType}, + "device_code": {dc.DeviceCode}, + } + interval := dc.Interval + if interval == 0 { + interval = 5 + } + for { + time.Sleep(time.Second * time.Duration(interval)) + token, err := m.requestToken(ctx, tenantID, clientID, values) + if err == nil { + m.Cache(tenantID, clientID, token) + return config.TokenSource(ctx, token), nil + } + tokenError, ok := err.(*TokenError) + if !ok || tokenError.ErrorObject != authorizationPendingError { + return nil, err + } + } +} diff --git a/vendor/github.com/yaegashi/msgraph.go/msauth/msauth.go b/vendor/github.com/yaegashi/msgraph.go/msauth/msauth.go new file mode 100644 index 00000000..c2a86985 --- /dev/null +++ b/vendor/github.com/yaegashi/msgraph.go/msauth/msauth.go @@ -0,0 +1,148 @@ +// Package msauth implements a library to authorize against Microsoft identity platform: +// https://docs.microsoft.com/en-us/azure/active-directory/develop/ +// +// It utilizes v2.0 endpoint +// so it can authorize users with both personal (Microsoft) and organizational (Azure AD) account. +package msauth + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "sync" + "time" + + "golang.org/x/oauth2" +) + +const ( + // DefaultMSGraphScope is the default scope for MS Graph API + DefaultMSGraphScope = "https://graph.microsoft.com/.default" + endpointURLFormat = "https://login.microsoftonline.com/%s/oauth2/v2.0/%s" +) + +// TokenError is returned on failed authentication +type TokenError struct { + ErrorObject string `json:"error"` + ErrorDescription string `json:"error_description"` +} + +// Error implements error interface +func (t *TokenError) Error() string { + return fmt.Sprintf("%s: %s", t.ErrorObject, t.ErrorDescription) +} + +func generateKey(tenantID, clientID string) string { + return fmt.Sprintf("%s:%s", tenantID, clientID) +} + +func deviceCodeURL(tenantID string) string { + return fmt.Sprintf(endpointURLFormat, tenantID, "devicecode") +} + +func tokenURL(tenantID string) string { + return fmt.Sprintf(endpointURLFormat, tenantID, "token") +} + +type tokenJSON struct { + AccessToken string `json:"access_token"` + TokenType string `json:"token_type"` + RefreshToken string `json:"refresh_token"` + ExpiresIn int `json:"expires_in"` +} + +func (e *tokenJSON) expiry() (t time.Time) { + if v := e.ExpiresIn; v != 0 { + return time.Now().Add(time.Duration(v) * time.Second) + } + return +} + +// Manager is oauth2 token cache manager +type Manager struct { + mu sync.Mutex + TokenCache map[string]*oauth2.Token +} + +// NewManager returns a new Manager instance +func NewManager() *Manager { + return &Manager{TokenCache: map[string]*oauth2.Token{}} +} + +// LoadBytes loads token cache from opaque bytes (it's actually JSON) +func (m *Manager) LoadBytes(b []byte) error { + m.mu.Lock() + defer m.mu.Unlock() + return json.Unmarshal(b, &m.TokenCache) +} + +// SaveBytes saves token cache to opaque bytes (it's actually JSON) +func (m *Manager) SaveBytes() ([]byte, error) { + m.mu.Lock() + defer m.mu.Unlock() + return json.Marshal(m.TokenCache) +} + +// LoadFile loads token cache from file +func (m *Manager) LoadFile(path string) error { + b, err := ioutil.ReadFile(path) + if err != nil { + return err + } + return m.LoadBytes(b) +} + +// SaveFile saves token cache to file +func (m *Manager) SaveFile(path string) error { + b, err := m.SaveBytes() + if err != nil { + return err + } + return ioutil.WriteFile(path, b, 0644) +} + +// Cache stores a token into token cache +func (m *Manager) Cache(tenantID, clientID string, token *oauth2.Token) { + m.TokenCache[generateKey(tenantID, clientID)] = token +} + +// requestToken requests a token from the token endpoint +// TODO(ctx): use http client from ctx +func (m *Manager) requestToken(ctx context.Context, tenantID, clientID string, values url.Values) (*oauth2.Token, error) { + res, err := http.PostForm(tokenURL(tenantID), values) + if err != nil { + return nil, err + } + defer res.Body.Close() + b, err := ioutil.ReadAll(res.Body) + if err != nil { + return nil, err + } + if res.StatusCode != http.StatusOK { + var terr *TokenError + err = json.Unmarshal(b, &terr) + if err != nil { + return nil, err + } + return nil, terr + } + var tj *tokenJSON + err = json.Unmarshal(b, &tj) + if err != nil { + return nil, err + } + token := &oauth2.Token{ + AccessToken: tj.AccessToken, + TokenType: tj.TokenType, + RefreshToken: tj.RefreshToken, + Expiry: tj.expiry(), + } + if token.AccessToken == "" { + return nil, errors.New("msauth: server response missing access_token") + } + return token, nil +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 75549d7a..6ca424c9 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -111,8 +111,6 @@ github.com/matterbridge/gomatrix github.com/matterbridge/gozulipbot # github.com/matterbridge/logrus-prefixed-formatter v0.0.0-20180806162718-01618749af61 github.com/matterbridge/logrus-prefixed-formatter -# github.com/matterbridge/msgraph.go v0.0.0-20200308150230-9e043fe9dbaa -github.com/matterbridge/msgraph.go/msauth # github.com/mattermost/mattermost-server v5.5.0+incompatible github.com/mattermost/mattermost-server/mlog github.com/mattermost/mattermost-server/model @@ -205,6 +203,7 @@ github.com/valyala/fasttemplate # github.com/yaegashi/msgraph.go v0.1.2 github.com/yaegashi/msgraph.go/beta github.com/yaegashi/msgraph.go/jsonx +github.com/yaegashi/msgraph.go/msauth # github.com/zfjagann/golang-ring v0.0.0-20190106091943-a88bb6aef447 github.com/zfjagann/golang-ring # go.uber.org/atomic v1.4.0 -- cgit v1.2.3