snapshot of https://github.com/cortezaproject/corteza.git (2024.9.x, 2026-09-18; blobs > 131072B omitted)
Some checks failed
SonarQube / SonarQube (push) Failing after 5m28s
E2e test on main branch push / server and client test (map[name:admin port:8080]) (push) Failing after 3m33s
Server and lib tests / Library test (js) (push) Failing after 1m36s
Server and lib tests / Library test (vue) (push) Successful in 2m24s
Server and lib tests / Web client test (admin) (push) Successful in 2m52s
Server and lib tests / Web client test (compose) (push) Successful in 3m23s
Server and lib tests / Web client test (discovery) (push) Successful in 2m49s
Server and lib tests / Web client test (one) (push) Successful in 2m52s
Server and lib tests / Web client test (privacy) (push) Successful in 2m44s
Server and lib tests / Web client test (reporter) (push) Successful in 2m56s
Server and lib tests / Web client test (workflow) (push) Successful in 3m0s
Server and lib tests / Server tests (push) Failing after 4m55s
E2e test on main branch push / notify-failure (push) Failing after 9s
Server and lib tests / Send matrix testing notification (push) Successful in 2s
Mark stale issues and pull requests / stale (push) Successful in 40s

This commit is contained in:
upstream-mirror
2026-09-18 01:22:23 +05:00
commit 7e385fc126
8391 changed files with 1766236 additions and 0 deletions

View File

@@ -0,0 +1,66 @@
package oauth2
import (
"context"
"fmt"
"strconv"
"github.com/cortezaproject/corteza/server/pkg/handle"
"github.com/cortezaproject/corteza/server/store"
systemService "github.com/cortezaproject/corteza/server/system/service"
"github.com/cortezaproject/corteza/server/system/types"
"github.com/go-oauth2/oauth2/v4"
"github.com/go-oauth2/oauth2/v4/models"
"github.com/spf13/cast"
)
type (
// Wrapper for store to satisfy oauth2.clientStore interface
clientStore struct {
store store.AuthClients
def *types.AuthClient
}
)
var (
_ oauth2.ClientStore = &clientStore{}
)
func NewClientStore(s store.AuthClients, def *types.AuthClient) *clientStore {
return &clientStore{s, def}
}
// GetByID pulls client directly from context
//
// This requires that client is put in context before oauth2 procedures are executed!
func (cs clientStore) GetByID(ctx context.Context, id string) (_ oauth2.ClientInfo, err error) {
var c *types.AuthClient
if id == "0" || cs.def != nil && cast.ToUint64(id) == cs.def.ID {
if cs.def == nil {
return nil, fmt.Errorf("could not provide default auth client")
}
c = cs.def
} else if c, err = clientLookup(ctx, cs.store, id); err != nil {
return nil, fmt.Errorf("failed to do auth client lookup (%q): %w", id, err)
}
m := &models.Client{
ID: strconv.FormatUint(c.ID, 10),
Secret: c.Secret,
Domain: c.RedirectURI,
}
return m, nil
}
func clientLookup(ctx context.Context, s store.AuthClients, identifier interface{}) (*types.AuthClient, error) {
if id := cast.ToUint64(identifier); id > 0 {
return store.LookupAuthClientByID(ctx, s, id)
} else if h := cast.ToString(identifier); handle.IsValid(h) {
return store.LookupAuthClientByHandle(ctx, s, h)
} else {
return nil, systemService.AuthClientErrInvalidID()
}
}

View File

@@ -0,0 +1,184 @@
package oauth2
import (
"context"
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/cortezaproject/corteza/server/pkg/auth"
"github.com/cortezaproject/corteza/server/pkg/errors"
"github.com/cortezaproject/corteza/server/pkg/id"
"github.com/cortezaproject/corteza/server/store"
"github.com/cortezaproject/corteza/server/system/types"
"github.com/go-oauth2/oauth2/v4"
oauth2errors "github.com/go-oauth2/oauth2/v4/errors"
oauth2models "github.com/go-oauth2/oauth2/v4/models"
)
type (
tokenStorer interface {
store.AuthOa2tokens
store.AuthConfirmedClients
}
tokenStore struct {
Store tokenStorer
}
)
var (
// wrapper around time.Now() that will aid service testing
now = func() *time.Time {
c := time.Now().Round(time.Second)
return &c
}
// wrapper around id.Next() that will aid service testing
nextID = func() uint64 {
return id.Next()
}
_ oauth2.TokenStore = &tokenStore{}
)
func NewTokenStore(s tokenStorer) *tokenStore {
return &tokenStore{Store: s}
}
func (c tokenStore) Create(ctx context.Context, info oauth2.TokenInfo) (err error) {
var (
oa2t *types.AuthOa2token
acc *types.AuthConfirmedClient
userID uint64
clientID uint64
)
if clientID, err = strconv.ParseUint(info.GetClientID(), 10, 64); err != nil {
return fmt.Errorf("could not parse client ID from token info: %w", err)
}
if userID, _ = auth.ExtractFromSubClaim(info.GetUserID()); userID == 0 {
return fmt.Errorf("could not parse user ID from token info")
}
// Make oauth2 token and auth confirmation structs from user and client IDs
if oa2t, acc, err = makeAuthStructs(ctx, userID, clientID, info, info.GetCodeExpiresIn()); err != nil {
return
}
if err = store.UpsertAuthConfirmedClient(ctx, c.Store, acc); err != nil {
return
}
if err = store.CreateAuthOa2token(ctx, c.Store, oa2t); err != nil {
return
}
return nil
}
func (c tokenStore) RemoveByCode(ctx context.Context, code string) error {
return store.DeleteAuthOA2TokenByCode(ctx, c.Store, code)
}
func (c tokenStore) RemoveByAccess(ctx context.Context, access string) error {
return store.DeleteAuthOA2TokenByAccess(ctx, c.Store, access)
}
func (c tokenStore) RemoveByRefresh(ctx context.Context, refresh string) error {
return store.DeleteAuthOA2TokenByRefresh(ctx, c.Store, refresh)
}
func (c tokenStore) GetByCode(ctx context.Context, code string) (oauth2.TokenInfo, error) {
var (
internal = &oauth2models.Token{}
t, err = store.LookupAuthOa2tokenByCode(ctx, c.Store, code)
)
if err != nil {
if errors.IsNotFound(err) {
return nil, oauth2errors.ErrInvalidAuthorizeCode
}
return nil, fmt.Errorf("failed to get code: %w", err)
}
return internal, t.Data.Unmarshal(internal)
}
func (c tokenStore) GetByAccess(ctx context.Context, access string) (oauth2.TokenInfo, error) {
var (
internal = &oauth2models.Token{}
t, err = store.LookupAuthOa2tokenByAccess(ctx, c.Store, access)
)
if err != nil {
return nil, fmt.Errorf("failed to get access token: %w", err)
}
return internal, t.Data.Unmarshal(internal)
}
func (c tokenStore) GetByRefresh(ctx context.Context, refresh string) (oauth2.TokenInfo, error) {
var (
internal = &oauth2models.Token{}
t, err = store.LookupAuthOa2tokenByRefresh(ctx, c.Store, refresh)
)
if err != nil {
if errors.IsNotFound(err) {
return nil, oauth2errors.ErrInvalidRefreshToken
}
return nil, fmt.Errorf("failed to get refresh token: %w", err)
}
return internal, t.Data.Unmarshal(internal)
}
func makeAuthStructs(ctx context.Context, userID, clientID uint64, info oauth2.TokenInfo, expiresAt time.Duration) (oa2t *types.AuthOa2token, acc *types.AuthConfirmedClient, err error) {
var (
eti = auth.GetExtraReqInfoFromContext(ctx)
createdAt = time.Now().Round(time.Second)
)
oa2t = &types.AuthOa2token{
ID: id.Next(),
CreatedAt: createdAt,
RemoteAddr: eti.RemoteAddr,
UserAgent: eti.UserAgent,
ClientID: clientID,
UserID: userID,
ExpiresAt: createdAt.Add(expiresAt),
}
acc = &types.AuthConfirmedClient{
ClientID: clientID,
UserID: userID,
ConfirmedAt: createdAt,
}
if oa2t.Data, err = json.Marshal(info); err != nil {
return nil, nil, err
}
if code := info.GetCode(); code != "" {
oa2t.Code = code
} else {
// When creating non-access-code tokens,
// we need to overwrite expiration time
// with custom values for access or refresh token
oa2t.Access = info.GetAccess()
oa2t.ExpiresAt = info.GetAccessCreateAt().Add(info.GetAccessExpiresIn())
if refresh := info.GetRefresh(); refresh != "" {
oa2t.Refresh = info.GetRefresh()
oa2t.ExpiresAt = info.GetRefreshCreateAt().Add(info.GetRefreshExpiresIn())
}
}
return
}

View File

@@ -0,0 +1,135 @@
package oauth2
import (
"fmt"
"net/http"
"strings"
"github.com/cortezaproject/corteza/server/pkg/handle"
"github.com/cortezaproject/corteza/server/pkg/logger"
"github.com/cortezaproject/corteza/server/pkg/options"
"github.com/cortezaproject/corteza/server/pkg/payload"
"github.com/go-oauth2/oauth2/v4"
"github.com/go-oauth2/oauth2/v4/errors"
"github.com/go-oauth2/oauth2/v4/manage"
"github.com/go-oauth2/oauth2/v4/server"
"go.uber.org/zap"
)
const (
RedirectUriSeparator = " "
)
func NewManager(opt options.AuthOpt, log *zap.Logger, cs oauth2.ClientStore, ts oauth2.TokenStore) *manage.Manager {
manager := manage.NewDefaultManager()
// Here we are cloning the internal package variable as I do not think
// it is sane to overwrite it directly.
cfg := *manage.DefaultAuthorizeCodeTokenCfg
cfg.AccessTokenExp = opt.AccessTokenLifetime
cfg.RefreshTokenExp = opt.RefreshTokenLifetime
manager.SetAuthorizeCodeTokenCfg(&cfg)
// token store
manager.MapTokenStorage(ts)
manager.MapClientStorage(cs)
// Change the default config for it to update refresh token timestamps
// else the refresh token timestamp remains the same
//
// @note do this so we don't change the default `manage` package var
rcfg := *manage.DefaultRefreshTokenCfg
rcfg.IsResetRefreshTime = true
manager.SetRefreshTokenCfg(&rcfg)
manager.SetValidateURIHandler(func(baseURI, redirectURI string) (err error) {
if baseURI == "" {
log.Debug(
"redirect URI check for client is disabled (empty validation list)",
zap.String("sent", redirectURI),
)
return nil
}
var (
valid = strings.Split(baseURI, RedirectUriSeparator)
)
log.Debug(
"matching redirectURI",
zap.String("sent", redirectURI),
zap.Strings("valid", valid),
)
for _, baseURI = range valid {
if strings.HasPrefix(redirectURI, baseURI) {
return nil
}
}
return errors.ErrInvalidRedirectURI
})
return manager
}
func NewServer(manager oauth2.Manager) *server.Server {
srv := server.NewServer(&server.Config{
TokenType: "Bearer",
AllowGetAccessRequest: false,
AllowedResponseTypes: []oauth2.ResponseType{
oauth2.Code,
},
AllowedGrantTypes: []oauth2.GrantType{
oauth2.AuthorizationCode,
oauth2.Refreshing,
oauth2.ClientCredentials,
},
AllowedCodeChallengeMethods: []oauth2.CodeChallengeMethod{
oauth2.CodeChallengePlain,
oauth2.CodeChallengeS256,
},
}, manager)
srv.ClientInfoHandler = func(r *http.Request) (clientID, clientSecret string, err error) {
// check in basic handler first
clientID, clientSecret, err = server.ClientBasicHandler(r)
if clientID == "" && clientSecret == "" {
//error or no error, if ID & secret are empty,
// check the form handler
clientID, clientSecret, err = server.ClientFormHandler(r)
}
// just in case, when client's handle is used instead of the ID
// preload it here
if id := payload.ParseUint64(clientID); id == 0 && handle.IsValid(clientID) {
var client oauth2.ClientInfo
client, err = manager.GetClient(r.Context(), clientID)
if err != nil {
err = fmt.Errorf("could not resolve client info: %v", err)
return
}
clientID = client.GetID()
}
return
}
srv.SetInternalErrorHandler(func(err error) (re *errors.Response) {
return errors.NewResponse(err, 500)
})
srv.SetResponseErrorHandler(func(re *errors.Response) {
msg := re.Description
if msg == "" {
msg = re.Error.Error()
}
logger.Default().Warn(msg)
})
return srv
}

View File

@@ -0,0 +1,78 @@
package oauth2
import (
"fmt"
"net/http"
"github.com/cortezaproject/corteza/server/auth/request"
internalAuth "github.com/cortezaproject/corteza/server/pkg/auth"
"github.com/cortezaproject/corteza/server/pkg/payload"
"github.com/go-oauth2/oauth2/v4/server"
)
func NewUserAuthorizer(sm *request.SessionManager, loginURL, clientAuthURL string) server.UserAuthorizationHandler {
return func(w http.ResponseWriter, r *http.Request) (identity string, err error) {
var (
ses = sm.Get(r)
au = request.GetAuthUser(ses)
client = request.GetOauth2Client(ses)
)
// temporary break oauth2 flow by redirecting to
// login form and ask user to authenticate
request.SetOauth2AuthParams(ses, r.Form)
// make sure session is saved!
sm.Save(w, r)
// @todo harden security by enforcing login
// for each new authorization flow
if au == nil {
// user is currently not logged-in;
http.Redirect(w, r, loginURL, http.StatusSeeOther)
return
} else {
if !request.IsOauth2ClientAuthorized(ses) || client == nil {
// user logged in but we need to re-authenticate the client
http.Redirect(w, r, clientAuthURL, http.StatusSeeOther)
return
}
}
roles := au.User.Roles()
if client.Security != nil {
// filter user's roles with client security settings
roles = internalAuth.ApplyRoleSecurity(
payload.ParseUint64s(client.Security.PermittedRoles),
payload.ParseUint64s(client.Security.ProhibitedRoles),
payload.ParseUint64s(client.Security.ForcedRoles),
roles...,
)
}
// User authenticated, client authorized!
// remove authorization values from session
request.SetOauth2AuthParams(ses, nil)
request.SetOauth2Client(ses, nil)
request.SetOauth2ClientAuthorized(ses, false)
// make sure session is saved!
sm.Save(w, r)
return UserIDSerializer(au.User.ID, roles...), nil
}
}
// UserIDSerializer packs user ID and IDs of all roles
// into space delimited string
//
// Main reason to do this is to simplify JWT claims encoding;
// we do not have access to user's membership info from there)
func UserIDSerializer(userID uint64, rr ...uint64) string {
identity := fmt.Sprintf("%d", userID)
for _, r := range rr {
identity += fmt.Sprintf(" %d", r)
}
return identity
}