feature: assume user login support (#23964)

Co-authored-by: Qiu Jian <qiujian@yunionyun.com>
This commit is contained in:
Jian Qiu
2025-12-23 13:54:04 +08:00
committed by GitHub
co-authored by Qiu Jian
parent 9434522102
commit bfc17bc3c7
8 changed files with 279 additions and 8 deletions
+3 -3
View File
@@ -17,7 +17,7 @@ package clientman
import (
"crypto/rand"
"crypto/rsa"
"io/ioutil"
"os"
"github.com/pkg/errors"
@@ -27,9 +27,9 @@ import (
func InitClient() error {
if options.Options.EnableSsl {
privData, err := ioutil.ReadFile(options.Options.SslKeyfile)
privData, err := os.ReadFile(options.Options.SslKeyfile)
if err != nil {
return errors.Wrapf(err, "ioutil.ReadFile %s", options.Options.SslKeyfile)
return errors.Wrapf(err, "os.ReadFile %s", options.Options.SslKeyfile)
}
privateKey, err := seclib2.DecodePrivateKey(privData)
if err != nil {
+101
View File
@@ -0,0 +1,101 @@
// Copyright 2019 Yunion
//
// 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.
package handler
import (
"context"
"net/http"
"strings"
"yunion.io/x/onecloud/pkg/apigateway/clientman"
"yunion.io/x/onecloud/pkg/appsrv"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/mcclient/auth"
"yunion.io/x/onecloud/pkg/util/netutils2"
"yunion.io/x/pkg/errors"
)
const (
ASSUME_TOKEN_HEADER = "X-Assume-Token"
)
type SAssumeToken struct {
Token string `json:"token"`
UserId string `json:"user_id"`
ProjectId string `json:"project_id"`
}
func getAssumeToken(r *http.Request) (*SAssumeToken, error) {
auth := r.Header.Get(ASSUME_TOKEN_HEADER)
if auth == "" {
return nil, errors.Wrap(httperrors.ErrInputParameter, "Assume token header is empty")
}
parts := strings.Split(strings.TrimSpace(auth), ":")
if len(parts) != 3 {
return nil, errors.Wrap(httperrors.ErrInputParameter, "Assume token header is invalid")
}
return &SAssumeToken{
Token: parts[0],
UserId: parts[1],
ProjectId: parts[2],
}, nil
}
func doAssumeLogin(assumeToken *SAssumeToken, w http.ResponseWriter, req *http.Request) (mcclient.TokenCredential, error) {
cliIp := netutils2.GetHttpRequestIp(req)
token, err := auth.Client().AuthenticateAssume(assumeToken.Token, assumeToken.UserId, assumeToken.ProjectId, cliIp)
if err != nil {
return nil, errors.Wrapf(httperrors.ErrInvalidCredential, "AuthenticateAssume fail %s", err)
}
authToken := clientman.NewAuthToken(token.GetTokenString(), false, false, false)
saveLoginCookies(w, authToken, token, nil)
return token, nil
}
func (h *AuthHandlers) handleAssumeLogin(ctx context.Context, w http.ResponseWriter, req *http.Request) {
// no auth cookie, try to get get assume user token from header
assumeToken, err := getAssumeToken(req)
if err != nil {
appsrv.Send(w, err.Error())
return
}
token, err := doAssumeLogin(assumeToken, w, req)
if err != nil {
appsrv.Send(w, err.Error())
return
}
_, query, _ := appsrv.FetchEnv(ctx, w, req)
redirect := ""
if query != nil {
queryMap, err := query.GetMap()
if err != nil {
appsrv.Send(w, err.Error())
return
}
for k, v := range queryMap {
if k == "p" {
redirect, _ = v.GetString()
} else {
value, _ := v.GetString()
saveCookie(w, k, value, "", token.GetExpires(), false)
}
}
}
if !strings.HasPrefix(redirect, "/") {
redirect = "/" + redirect
}
appsrv.SendRedirect(w, redirect)
}
+9 -5
View File
@@ -85,6 +85,7 @@ func (h *AuthHandlers) AddMethods() {
NewHP(handleOIDCJWKeys, "oidc", "keys"),
NewHP(handleOIDCUserInfo, "oidc", "user"),
NewHP(handleOIDCRPInitLogout, "oidc", "logout"),
NewHP(h.handleAssumeLogin, "assume"),
)
h.AddByMethod(POST, nil,
NewHP(h.initTotpSecrets, "initcredential"),
@@ -661,31 +662,34 @@ func (h *AuthHandlers) doLogin(ctx context.Context, w http.ResponseWriter, req *
return httperrors.NewForbiddenError("user forbidden login from web")
}
saveLoginCookies(w, authToken, token, body)
return nil
}
func saveLoginCookies(w http.ResponseWriter, authToken *clientman.SAuthToken, token mcclient.TokenCredential, body jsonutils.JSONObject) {
saveAuthCookie(w, authToken, token)
if len(token.GetProjectId()) > 0 {
if body.Contains("isadmin") {
if body != nil && body.Contains("isadmin") {
adminVal := "false"
if policy.PolicyManager.IsScopeCapable(token, rbacscope.ScopeSystem) {
adminVal, _ = body.GetString("isadmin")
}
saveCookie(w, "isadmin", adminVal, "", token.GetExpires(), false)
}
if body.Contains("scope") {
if body != nil && body.Contains("scope") {
scopeStr, _ := body.GetString("scope")
if !policy.PolicyManager.IsScopeCapable(token, rbacscope.TRbacScope(scopeStr)) {
scopeStr = string(rbacscope.ScopeProject)
}
saveCookie(w, "scope", scopeStr, "", token.GetExpires(), false)
}
if body.Contains("domain") {
if body != nil && body.Contains("domain") {
domainStr, _ := body.GetString("domain")
saveCookie(w, "domain", domainStr, "", token.GetExpires(), false)
}
saveCookie(w, "tenant", token.GetProjectId(), "", token.GetExpires(), false)
}
return nil
}
func doLogout(ctx context.Context, w http.ResponseWriter, req *http.Request) {
+1
View File
@@ -38,6 +38,7 @@ const (
AUTH_METHOD_OIDC = "oidc"
AUTH_METHOD_OAuth2 = "oauth2"
AUTH_METHOD_VERIFY = "verify"
AUTH_METHOD_ASSUME = "assume"
// AUTH_METHOD_ID_PASSWORD = 1
// AUTH_METHOD_ID_TOKEN = 2
+102
View File
@@ -0,0 +1,102 @@
// Copyright 2019 Yunion
//
// 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.
package tokens
import (
"context"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/util/rbacscope"
api "yunion.io/x/onecloud/pkg/apis/identity"
"yunion.io/x/onecloud/pkg/cloudcommon/policy"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/keystone/models"
"yunion.io/x/onecloud/pkg/mcclient"
)
// authUserByAssume allows an admin token to login as any user without password
func authUserByAssume(ctx context.Context, input mcclient.SAuthenticationInputV3) (*api.SUserExtended, error) {
// Validate admin token
if len(input.Auth.Identity.Token.Id) == 0 {
return nil, httperrors.NewInputParameterError("admin token is required for assume authentication")
}
// Decode and validate the admin token
adminToken, err := TokenStrDecode(ctx, input.Auth.Identity.Token.Id)
if err != nil {
return nil, errors.Wrap(err, "decode admin token")
}
// Check if admin token is expired
if adminToken.IsExpired() {
return nil, ErrExpiredToken
}
scopedProject, err := models.ProjectManager.FetchProject(
input.Auth.Scope.Project.Id,
input.Auth.Scope.Project.Name,
input.Auth.Scope.Project.Domain.Id,
input.Auth.Scope.Project.Domain.Name,
)
if err != nil {
return nil, errors.Wrap(err, "fetch scoped project")
}
var requireScope rbacscope.TRbacScope
if adminToken.ProjectId == scopedProject.Id {
requireScope = rbacscope.ScopeProject
} else if adminToken.DomainId == scopedProject.DomainId {
requireScope = rbacscope.ScopeDomain
} else {
requireScope = rbacscope.ScopeSystem
}
adminToken.ProjectId = scopedProject.Id
adminToken.DomainId = scopedProject.DomainId
adminTokenCred, err := adminToken.GetSimpleUserCred(input.Auth.Identity.Token.Id)
if err != nil {
return nil, errors.Wrap(err, "get admin token credential")
}
// Validate target user information
assumeUser := input.Auth.Identity.Assume.User
if len(assumeUser.Id) == 0 && len(assumeUser.Name) == 0 {
return nil, httperrors.NewInputParameterError("target user id or name is required")
}
// Fetch target user
targetUser, err := models.UserManager.FetchUserExtended(
assumeUser.Id,
assumeUser.Name,
assumeUser.Domain.Id,
assumeUser.Domain.Name,
)
if err != nil {
return nil, errors.Wrap(err, "fetch target user")
}
if adminTokenCred.GetUserId() != targetUser.Id {
if policy.PolicyManager.Allow(requireScope, adminTokenCred, api.SERVICE_TYPE, "tokens", "perform", "assume").Result.IsDeny() {
return nil, httperrors.NewForbiddenError("%s not allow to assume user in project %s", adminTokenCred.GetUserName(), scopedProject.Name)
}
}
// Set audit IDs to include both admin token and assume operation
targetUser.AuditIds = []string{adminTokenCred.GetUserId()}
return targetUser, nil
}
+5
View File
@@ -485,6 +485,11 @@ func AuthenticateV3(ctx context.Context, input mcclient.SAuthenticationInputV3)
if err != nil {
return nil, errors.Wrap(err, "authUserByVerify")
}
case api.AUTH_METHOD_ASSUME:
user, err = authUserByAssume(ctx, input)
if err != nil {
return nil, errors.Wrap(err, "authUserByAssume")
}
default:
// auth by other methods, e.g. password , etc...
user, err = authUserByIdentityV3(ctx, input)
+42
View File
@@ -0,0 +1,42 @@
// Copyright 2019 Yunion
//
// 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.
package mcclient
import (
api "yunion.io/x/onecloud/pkg/apis/identity"
"yunion.io/x/onecloud/pkg/httperrors"
)
func (client *Client) AuthenticateAssume(token string, userId, projectId string, cliIp string) (TokenCredential, error) {
aCtx := SAuthContext{
// Assume auth must comes from API
Source: AuthSourceAPI,
Ip: cliIp,
}
return client.authenticateAssumeWithContext(token, userId, projectId, aCtx)
}
func (client *Client) authenticateAssumeWithContext(token string, userId, projectId string, aCtx SAuthContext) (TokenCredential, error) {
if client.AuthVersion() != "v3" {
return nil, httperrors.ErrNotSupported
}
input := SAuthenticationInputV3{}
input.Auth.Identity.Token.Id = token
input.Auth.Identity.Methods = []string{api.AUTH_METHOD_ASSUME}
input.Auth.Identity.Assume.User.Id = userId
input.Auth.Scope.Project.Id = projectId
input.Auth.Context = aCtx
return client._authV3Input(input)
}
+16
View File
@@ -134,6 +134,22 @@ type SAuthenticationIdentity struct {
VerifyCode string `json:"verify_code,omitempty"`
ContactType string `json:"contact_type,omitempty"`
} `json:"mobile,omitempty"`
// 当认证方式为assume时,通过该字段提供目标用户信息
Assume struct {
User struct {
// 用户ID
Id string `json:"id,omitempty"`
// 用户名称
Name string `json:"name,omitempty"`
// 用户所属域的信息
Domain struct {
// 域ID
Id string `json:"id,omitempty"`
// 域名称
Name string `json:"name,omitempty"`
} `json:"domain,omitempty"`
} `json:"user,omitempty"`
} `json:"assume,omitempty"`
}
type SAuthenticationInputV3 struct {