[MM-53968] Includes mattermost-plugin-api into the mono repo (#24235)

Include https://github.com/mattermost/mattermost-plugin-api into the mono repo

Co-authored-by: Jesse Hallam <jesse.hallam@gmail.com>
Co-authored-by: Michael Kochell <mjkochell@gmail.com>
Co-authored-by: Alejandro García Montoro <alejandro.garciamontoro@gmail.com>
Co-authored-by: Ben Schumacher <ben.schumacher@mattermost.com>
Co-authored-by: Alex Dovenmuehle <alex.dovenmuehle@mattermost.com>
Co-authored-by: Michael Kochell <6913320+mickmister@users.noreply.github.com>
Co-authored-by: Christopher Poile <cpoile@gmail.com>
Co-authored-by: İlker Göktuğ Öztürk <ilkergoktugozturk@gmail.com>
Co-authored-by: Shota Gvinepadze <wineson@gmail.com>
Co-authored-by: Ali Farooq <ali.farooq0@pm.me>
Co-authored-by: Maria A Nunez <maria.nunez@mattermost.com>
Co-authored-by: Daniel Espino García <larkox@gmail.com>
Co-authored-by: Christopher Speller <crspeller@gmail.com>
Co-authored-by: Alex Dovenmuehle <adovenmuehle@gmail.com>
Co-authored-by: Szymon Gibała <szymongib@gmail.com>
Co-authored-by: Lev <1187448+levb@users.noreply.github.com>
Co-authored-by: Jason Frerich <jason.frerich@mattermost.com>
Co-authored-by: Agniva De Sarker <agnivade@yahoo.co.in>
Co-authored-by: Artur M. Wolff <artur.m.wolff@gmail.com>
Co-authored-by: Madhav Hugar <16546715+madhavhugar@users.noreply.github.com>
Co-authored-by: Joe <security.joe@pm.me>
Co-authored-by: Ibrahim Serdar Acikgoz <serdaracikgoz86@gmail.com>
Co-authored-by: José Peso <trilopin@users.noreply.github.com>
Этот коммит содержится в:
Ben Schumacher
2023-08-21 09:50:30 +02:00
коммит произвёл GitHub
родитель bc11b29807
Коммит 3ee5432664
117 изменённых файлов: 14912 добавлений и 5 удалений

Просмотреть файл

@@ -0,0 +1,77 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/mattermost/mattermost-plugin-mscalendar/server/utils/oauther (interfaces: OAuther)
// Package mock_oauther is a generated GoMock package.
package mock_oauther
import (
gomock "github.com/golang/mock/gomock"
oauth2 "golang.org/x/oauth2"
reflect "reflect"
)
// MockOAuther is a mock of OAuther interface
type MockOAuther struct {
ctrl *gomock.Controller
recorder *MockOAutherMockRecorder
}
// MockOAutherMockRecorder is the mock recorder for MockOAuther
type MockOAutherMockRecorder struct {
mock *MockOAuther
}
// NewMockOAuther creates a new mock instance
func NewMockOAuther(ctrl *gomock.Controller) *MockOAuther {
mock := &MockOAuther{ctrl: ctrl}
mock.recorder = &MockOAutherMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockOAuther) EXPECT() *MockOAutherMockRecorder {
return m.recorder
}
// Deauth mocks base method
func (m *MockOAuther) Deauth(arg0 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Deauth", arg0)
ret0, _ := ret[0].(error)
return ret0
}
// Deauth indicates an expected call of Deauth
func (mr *MockOAutherMockRecorder) Deauth(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Deauth", reflect.TypeOf((*MockOAuther)(nil).Deauth), arg0)
}
// GetToken mocks base method
func (m *MockOAuther) GetToken(arg0 string) (*oauth2.Token, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetToken", arg0)
ret0, _ := ret[0].(*oauth2.Token)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetToken indicates an expected call of GetToken
func (mr *MockOAutherMockRecorder) GetToken(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetToken", reflect.TypeOf((*MockOAuther)(nil).GetToken), arg0)
}
// GetURL mocks base method
func (m *MockOAuther) GetURL() string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetURL")
ret0, _ := ret[0].(string)
return ret0
}
// GetURL indicates an expected call of GetURL
func (mr *MockOAutherMockRecorder) GetURL() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetURL", reflect.TypeOf((*MockOAuther)(nil).GetURL))
}

Просмотреть файл

@@ -0,0 +1,105 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/mattermost/mattermost/server/public/pluginapi/experimental/oauther (interfaces: OAuther)
// Package mock_oauther is a generated GoMock package.
package mock_oauther
import (
http "net/http"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
oauth2 "golang.org/x/oauth2"
)
// MockOAuther is a mock of OAuther interface.
type MockOAuther struct {
ctrl *gomock.Controller
recorder *MockOAutherMockRecorder
}
// MockOAutherMockRecorder is the mock recorder for MockOAuther.
type MockOAutherMockRecorder struct {
mock *MockOAuther
}
// NewMockOAuther creates a new mock instance.
func NewMockOAuther(ctrl *gomock.Controller) *MockOAuther {
mock := &MockOAuther{ctrl: ctrl}
mock.recorder = &MockOAutherMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockOAuther) EXPECT() *MockOAutherMockRecorder {
return m.recorder
}
// AddPayload mocks base method.
func (m *MockOAuther) AddPayload(arg0 string, arg1 []byte) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "AddPayload", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
// AddPayload indicates an expected call of AddPayload.
func (mr *MockOAutherMockRecorder) AddPayload(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddPayload", reflect.TypeOf((*MockOAuther)(nil).AddPayload), arg0, arg1)
}
// Deauthorize mocks base method.
func (m *MockOAuther) Deauthorize(arg0 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Deauthorize", arg0)
ret0, _ := ret[0].(error)
return ret0
}
// Deauthorize indicates an expected call of Deauthorize.
func (mr *MockOAutherMockRecorder) Deauthorize(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Deauthorize", reflect.TypeOf((*MockOAuther)(nil).Deauthorize), arg0)
}
// GetConnectURL mocks base method.
func (m *MockOAuther) GetConnectURL() string {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetConnectURL")
ret0, _ := ret[0].(string)
return ret0
}
// GetConnectURL indicates an expected call of GetConnectURL.
func (mr *MockOAutherMockRecorder) GetConnectURL() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConnectURL", reflect.TypeOf((*MockOAuther)(nil).GetConnectURL))
}
// GetToken mocks base method.
func (m *MockOAuther) GetToken(arg0 string) (*oauth2.Token, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetToken", arg0)
ret0, _ := ret[0].(*oauth2.Token)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetToken indicates an expected call of GetToken.
func (mr *MockOAutherMockRecorder) GetToken(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetToken", reflect.TypeOf((*MockOAuther)(nil).GetToken), arg0)
}
// ServeHTTP mocks base method.
func (m *MockOAuther) ServeHTTP(arg0 http.ResponseWriter, arg1 *http.Request) {
m.ctrl.T.Helper()
m.ctrl.Call(m, "ServeHTTP", arg0, arg1)
}
// ServeHTTP indicates an expected call of ServeHTTP.
func (mr *MockOAutherMockRecorder) ServeHTTP(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ServeHTTP", reflect.TypeOf((*MockOAuther)(nil).ServeHTTP), arg0, arg1)
}

Просмотреть файл

@@ -0,0 +1,191 @@
// Copyright (c) 2019-present Mattermost, Inc. All Rights Reserved.
// See License for license information.
package oauther
import (
"net/http"
"time"
"golang.org/x/oauth2"
"github.com/mattermost/mattermost/server/public/pluginapi"
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/bot/logger"
"github.com/mattermost/mattermost/server/public/pluginapi/experimental/common"
)
const (
// DefaultStorePrefix is the prefix used when storing information in the KVStore by default.
DefaultStorePrefix = "oauth_"
// DefaultOAuthURL is the URL the OAuther will use to register its endpoints by default.
DefaultOAuthURL = "/oauth2"
// DefaultConnectedString is the string shown to the user when the oauth flow is completed by default.
DefaultConnectedString = "Successfully connected. Please close this window."
// DefaultOAuth2StateTimeToLive is the duration the states from the OAuth flow will live in the KVStore by default.
DefaultOAuth2StateTimeToLive = 5 * time.Minute
// DefaultPayloadTimeToLive is the duration the user payload will live in the KVStore by default.
DefaultPayloadTimeToLive = 10 * time.Minute
)
const (
connectURL = "/connect"
completeURL = "/complete"
)
// OAuther defines an object able to perform the OAuth flow.
type OAuther interface {
// GetToken returns the oauth token for userID, or error if it does not exist or there is any store error.
GetToken(userID string) (*oauth2.Token, error)
// GetConnectURL returns the URL to reach in order to start the OAuth flow.
GetConnectURL() string
// Deauthorize removes the token for userID. Return error if there is any store error.
Deauthorize(userID string) error
// ServeHTTP implements http.Handler
ServeHTTP(w http.ResponseWriter, r *http.Request)
// AddPayload stores some information to be returned after the flow is over
AddPayload(userID string, payload []byte) error
}
type oAuther struct {
pluginURL string
config oauth2.Config
onConnect func(userID string, token oauth2.Token, payload []byte)
store common.KVStore
logger logger.Logger
storePrefix string
oAuthURL string
connectedString string
oAuth2StateTimeToLive time.Duration
payloadTimeToLive time.Duration
}
/*
New creates a new OAuther.
- pluginURL: The base URL for the plugin (e.g. https://www.instance.com/plugins/pluginid).
- oAuthConfig: The configuration of the Authorization flow to perform.
- onConnect: What to do when the Authorization process is complete.
- store: A KVStore to store the data of the OAuther.
- l Logger: A logger to log errors during authorization.
- options: Optional options for the OAuther. Available options are StorePrefix, OAuthURL, ConnectedString and OAuth2StateTimeToLive.
*/
func New(
pluginURL string,
oAuthConfig oauth2.Config,
onConnect func(userID string, token oauth2.Token, payload []byte),
store common.KVStore,
l logger.Logger,
options ...Option,
) OAuther {
o := &oAuther{
pluginURL: pluginURL,
config: oAuthConfig,
onConnect: onConnect,
store: store,
logger: l,
storePrefix: DefaultStorePrefix,
oAuthURL: DefaultOAuthURL,
connectedString: DefaultConnectedString,
oAuth2StateTimeToLive: DefaultOAuth2StateTimeToLive,
payloadTimeToLive: DefaultPayloadTimeToLive,
}
for _, option := range options {
option(o)
}
o.config.RedirectURL = o.pluginURL + o.oAuthURL + "/complete"
return o
}
/*
NewFromClient creates a new OAuther from the plugin api client.
- pluginapi: A plugin api client.
- pluginID: The plugin ID.
- oAuthConfig: The configuration of the Authorization flow to perform.
- onConnect: What to do when the Authorization process is complete.
- l Logger: A logger to log errors during authorization.
- options: Optional options for the OAuther. Available options are StorePrefix, OAuthURL, ConnectedString and OAuth2StateTimeToLive.
*/
func NewFromClient(
client *pluginapi.Client,
oAuthConfig oauth2.Config,
onConnect func(userID string, token oauth2.Token, payload []byte),
l logger.Logger,
options ...Option,
) OAuther {
return New(
common.GetPluginURL(client),
oAuthConfig,
onConnect,
&client.KV,
l,
options...,
)
}
func (o *oAuther) GetConnectURL() string {
return o.pluginURL + o.oAuthURL + "/connect"
}
func (o *oAuther) GetToken(userID string) (*oauth2.Token, error) {
var token *oauth2.Token
err := o.store.Get(o.getTokenKey(userID), &token)
if err != nil {
return nil, err
}
return token, nil
}
func (o *oAuther) getTokenKey(userID string) string {
return o.storePrefix + "token_" + userID
}
func (o *oAuther) getStateKey(userID string) string {
return o.storePrefix + "state_" + userID
}
func (o *oAuther) getPayloadKey(userID string) string {
return o.storePrefix + "payload_" + userID
}
func (o *oAuther) Deauthorize(userID string) error {
err := o.store.Delete(o.getTokenKey(userID))
if err != nil {
return err
}
return nil
}
func (o *oAuther) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case o.oAuthURL + connectURL:
o.oauth2Connect(w, r)
case o.oAuthURL + completeURL:
o.oauth2Complete(w, r)
default:
http.NotFound(w, r)
}
}
func (o *oAuther) AddPayload(userID string, payload []byte) error {
_, err := o.store.Set(o.getPayloadKey(userID), payload, pluginapi.SetExpiry(o.payloadTimeToLive))
if err != nil {
return err
}
return nil
}

Просмотреть файл

@@ -0,0 +1,105 @@
// Copyright (c) 2019-present Mattermost, Inc. All Rights Reserved.
// See License for license information.
package oauther
import (
"context"
"fmt"
"net/http"
"strings"
)
func (o *oAuther) oauth2Complete(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
authedUserID := r.Header.Get("Mattermost-User-ID")
if authedUserID == "" {
o.logger.Debugf("oauth2Complete: reached by non authed user")
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
code := r.URL.Query().Get("code")
if code == "" {
o.logger.Debugf("oauth2Complete: reached with no code")
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
state := r.URL.Query().Get("state")
var storedState string
err := o.store.Get(o.getStateKey(authedUserID), &storedState)
if err != nil {
o.logger.Warnf("oauth2Complete: cannot get state, err=%s", err.Error())
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if storedState != state {
o.logger.Debugf("oauth2Complete: state mismatch")
o.logger.Debugf("received state '%s'; expected state '%s%", state, storedState)
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
userID := strings.Split(state, "_")[1]
if userID != authedUserID {
o.logger.Debugf("oauth2Complete: authed user mismatch")
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
ctx := context.Background()
token, err := o.config.Exchange(ctx, code)
if err != nil {
o.logger.Warnf("oauth2Complete: could not generate token, err=%s", err.Error())
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
var payload []byte
err = o.store.Get(o.getPayloadKey(userID), &payload)
if err != nil {
o.logger.Errorf("oauth2Complete: could not fetch payload, err=&s", err.Error())
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
ok, err := o.store.Set(o.getTokenKey(userID), token)
if err != nil {
o.logger.Errorf("oauth2Complete: cannot store the token, err=%s", err.Error())
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if !ok {
o.logger.Errorf("oauth2Complete: cannot store token without error")
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
html := fmt.Sprintf(`
<!DOCTYPE html>
<html>
<head>
<script>
window.close();
</script>
</head>
<body>
<p>%s</p>
</body>
</html>
`, o.connectedString)
w.Header().Set("Content-Type", "text/html")
_, err = w.Write([]byte(html))
if err != nil {
o.logger.Errorf("oauth2Complete: error writing response, err=%s", err.Error())
}
if o.onConnect != nil {
o.onConnect(userID, *token, payload)
}
}

Просмотреть файл

@@ -0,0 +1,38 @@
// Copyright (c) 2019-present Mattermost, Inc. All Rights Reserved.
// See License for license information.
package oauther
import (
"fmt"
"net/http"
"golang.org/x/oauth2"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/pluginapi"
)
func (o *oAuther) oauth2Connect(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
userID := r.Header.Get("Mattermost-User-ID")
if userID == "" {
o.logger.Debugf("oauth2Connect: reached by non authed user")
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
state := fmt.Sprintf("%v_%v", model.NewId()[0:15], userID)
_, err := o.store.Set(o.getStateKey(userID), state, pluginapi.SetExpiry(o.oAuth2StateTimeToLive))
if err != nil {
o.logger.Errorf("oauth2Connect: failed to store state, err=%s", err.Error())
http.Error(w, "failed to store token state", http.StatusInternalServerError)
return
}
redirectURL := o.config.AuthCodeURL(state, oauth2.AccessTypeOffline)
http.Redirect(w, r, redirectURL, http.StatusFound)
}

Просмотреть файл

@@ -0,0 +1,47 @@
package oauther
import "time"
// Option defines each option that can be passed in the creation of the OAuther.
// Options functions available are OAuthURL, StorePrefix, ConnectedString and OAuth2StateTimeToLive and PayloadTimeToLive.
type Option func(*oAuther)
// OAuthURL defines the URL the OAuther will use to register its endpoints.
// Defaults to "/oauth2".
func OAuthURL(url string) Option {
return func(o *oAuther) {
o.oAuthURL = url
}
}
// StorePrefix defines the prefix the OAuther will use to store information in the KVStore.
// Defaults to "oauth_".
func StorePrefix(prefix string) Option {
return func(o *oAuther) {
o.storePrefix = prefix
}
}
// ConnectedString defines the string shown to the user when the oauth flow is completed.
// Defaults to "Successfully connected. Please close this window.".
func ConnectedString(text string) Option {
return func(o *oAuther) {
o.connectedString = text
}
}
// OAuth2StateTimeToLive is the duration the states from the OAuth flow will live in the KVStore.
// Defaults to 5 minutes.
func OAuth2StateTimeToLive(ttl time.Duration) Option {
return func(o *oAuther) {
o.oAuth2StateTimeToLive = ttl
}
}
// PayloadTimeToLive is the duration the payload from the OAuth flow will live in the KVStore.
// Defaults to 10 minutes.
func PayloadTimeToLive(ttl time.Duration) Option {
return func(o *oAuther) {
o.payloadTimeToLive = ttl
}
}