Skip to content

vcsim: Add minimal json-rpc support #3765

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

Merged
merged 2 commits into from
Apr 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions govc/test/vcsim.bats
Original file line number Diff line number Diff line change
Expand Up @@ -585,3 +585,74 @@ EOF

rm "$file"
}

@test "vcsim jsonrpc" {
vcsim_start

url=$(govc env -x GOVC_URL) # w/o username:password@

run govc session.login -u "$url" -X POST /api <<EOF
{
"jsonrpc": "2.0",
"method": "invoke",
"params": {
"serviceId": "com.vmware.cis.session",
"operationId": "create",
"ctx": {
"securityCtx": {
"schemeId": "com.vmware.vapi.std.security.user_pass",
"userName": "$(govc env GOVC_USERNAME)",
"password": "$(govc env GOVC_PASSWORD)"
}
}
},
"id": "0"
}
EOF
assert_success

session=$(jq -r .result.output.SECRET <<<"$output")
[ -n "$session" ]

run govc session.login -X POST /api <<EOF
{
"jsonrpc": "2.0",
"method": "invoke",
"params": {
"serviceId": "com.vmware.cis.session",
"operationId": "delete"
},
"id": "123"
}
EOF
assert_success

id=$(jq -r .id <<<"$output")
assert_equal "$id" "123"

run govc session.login -r -X GET /rest/vcenter/certificate-authority/get-root
assert_success

run jq -r .value <<<"$output"
assert_success

run openssl x509 -text <<<"$output"
assert_success

run govc host.cert.csr -host DC0_H0
assert_success
csr="${output//$'\n'/\\n}"

run govc session.login -r -X POST /rest/vcenter/certificate-authority/sign-cert <<EOF
{ "csr": "$csr", "duration": "30"}
EOF
assert_success

run jq -r .value <<<"$output"
assert_success

cert="$output"
run openssl x509 -text <<<"$cert"
assert_success
assert_matches DNS:DC0_H0
}
5 changes: 1 addition & 4 deletions lookup/simulator/registration_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,7 @@ func registrationInfo(ctx *simulator.Context) []types.LookupServiceRegistrationI
}
}

trust := []string{""}
if sm.TLSCert != nil {
trust[0] = sm.TLSCert()
}
trust := []string{sm.TLSCert()}
sdk := opts["vcsim.server.url"] + vim25.Path
admin := opts["config.vpxd.sso.default.admin"]
owner := opts["config.vpxd.sso.solutionUser.name"]
Expand Down
11 changes: 10 additions & 1 deletion simulator/session_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ package simulator

import (
"context"
"crypto/tls"
"encoding/base64"
"fmt"
"net/http"
"net/url"
Expand All @@ -30,7 +32,7 @@ type SessionManager struct {
nopLocker

ServiceHostName string
TLSCert func() string
TLS func() *tls.Config
ValidLogin func(*types.Login) bool

sessions map[string]Session
Expand Down Expand Up @@ -122,6 +124,13 @@ func (s *SessionManager) Authenticate(u url.URL, req *types.Login) bool {
return req.UserName == u.User.Username() && req.Password == pass
}

func (s *SessionManager) TLSCert() string {
if s.TLS == nil {
return ""
}
return base64.StdEncoding.EncodeToString(s.TLS().Certificates[0].Certificate[0])
}

func (s *SessionManager) Login(ctx *Context, req *types.Login) soap.HasFault {
body := new(methods.LoginBody)

Expand Down
5 changes: 1 addition & 4 deletions simulator/simulator.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
Expand Down Expand Up @@ -777,9 +776,7 @@ func (s *Service) NewServer() *Server {
if s.TLS != nil {
ts.TLS = s.TLS
ts.TLS.ClientAuth = tls.RequestClientCert // Used by SessionManager.LoginExtensionByCertificate
ctx.Map.SessionManager().TLSCert = func() string {
return base64.StdEncoding.EncodeToString(ts.TLS.Certificates[0].Certificate[0])
}
ctx.Map.SessionManager().TLS = func() *tls.Config { return ts.TLS }
ts.StartTLS()
} else {
ts.Start()
Expand Down
2 changes: 1 addition & 1 deletion ssoadmin/simulator/simulator.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ func (*ConfigurationManagementService) GetTrustedCertificates(ctx *simulator.Con
}
res = append(res, base64.StdEncoding.EncodeToString(block.Bytes))
}
} else if m.TLSCert != nil {
} else if m.TLS != nil {
res = append(res, m.TLSCert())
}

Expand Down
118 changes: 115 additions & 3 deletions vapi/simulator/simulator.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"bytes"
"context"
"crypto/md5"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
Expand All @@ -22,6 +23,7 @@ import (
"hash"
"io"
"log"
"math/big"
"net/http"
"net/url"
"os"
Expand Down Expand Up @@ -167,8 +169,10 @@ func New(u *url.URL, r *simulator.Registry) ([]string, http.Handler) {
{internal.VCenterOVFLibraryItem + "/", s.libraryItemOVFID},
{internal.VCenterVMTXLibraryItem, s.libraryItemCreateTemplate},
{internal.VCenterVMTXLibraryItem + "/", s.libraryItemTemplateID},
{"/vcenter/certificate-authority/", s.certificateAuthority},
{internal.DebugEcho, s.debugEcho},
// /api/ patterns.
{vapi.Path, s.jsonRPC},
{internal.SecurityPoliciesPath, s.librarySecurityPolicies},
{internal.TrustedCertificatesPath, s.libraryTrustedCertificates},
{internal.TrustedCertificatesPath + "/", s.libraryTrustedCertificatesID},
Expand All @@ -179,7 +183,10 @@ func New(u *url.URL, r *simulator.Registry) ([]string, http.Handler) {
s.HandleFunc(h.p, h.m)
}

return []string{rest.Path + "/", vapi.Path + "/"}, s
return []string{
rest.Path, rest.Path + "/",
vapi.Path, vapi.Path + "/",
}, s
}

func (s *handler) withClient(f func(context.Context, *vim25.Client) error) error {
Expand Down Expand Up @@ -266,8 +273,13 @@ func (s *handler) HandleFunc(pattern string, handler func(http.ResponseWriter, *
}

func (s *handler) isAuthorized(r *http.Request) bool {
if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, internal.SessionPath) && s.action(r) == "" {
return true
if r.Method == http.MethodPost && s.action(r) == "" {
if r.URL.Path == vapi.Path {
return true
}
if strings.HasSuffix(r.URL.Path, internal.SessionPath) {
return true
}
}
id := r.Header.Get(internal.SessionCookieName)
if id == "" {
Expand Down Expand Up @@ -565,6 +577,106 @@ func (s *handler) session(w http.ResponseWriter, r *http.Request) {
}
}

// just enough json-rpc to support Supervisor upgrade testing
func (s *handler) jsonRPC(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}

var rpc, out map[string]any

if Decode(r, w, &rpc) {
params := rpc["params"].(map[string]any)

switch params["serviceId"] {
case "com.vmware.cis.session":
switch params["operationId"] {
case "create":
id := uuid.New().String()
now := time.Now()
s.Session[id] = &rest.Session{User: id, Created: now, LastAccessed: now}
out = map[string]any{"SECRET": id}
case "delete":
}
}

res := map[string]any{
"jsonrpc": rpc["jsonrpc"],
"id": rpc["id"],
"result": map[string]any{
"output": out,
},
}

StatusOK(w, res)
}
}

func (s *handler) certificateAuthority(w http.ResponseWriter, r *http.Request) {
signer := s.Map.SessionManager().TLS().Certificates[0]

switch path.Base(r.URL.Path) {
case "get-root":
var encoded bytes.Buffer
_ = pem.Encode(&encoded, &pem.Block{Type: "CERTIFICATE", Bytes: signer.Leaf.Raw})
OK(w, encoded.String())
case "sign-cert":
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}

var req struct {
Duration string `json:"duration"`
CSR string `json:"csr"`
}

if Decode(r, w, &req) {
block, _ := pem.Decode([]byte(req.CSR))
csr, err := x509.ParseCertificateRequest(block.Bytes)
if err != nil {
BadRequest(w, err.Error())
return
}
duration, err := strconv.ParseInt(req.Duration, 10, 64)
if err != nil {
BadRequest(w, err.Error())
return
}

serialNumber, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
now := time.Now()
cert := &x509.Certificate{
SerialNumber: serialNumber,
Subject: csr.Subject,
DNSNames: csr.DNSNames,
IPAddresses: csr.IPAddresses,
NotBefore: now,
NotAfter: now.Add(time.Hour * 24 * time.Duration(duration)),
AuthorityKeyId: signer.Leaf.SubjectKeyId,
}

der, err := x509.CreateCertificate(rand.Reader, cert, signer.Leaf, csr.PublicKey, signer.PrivateKey)
if err != nil {
BadRequest(w, err.Error())
return
}

var encoded bytes.Buffer
err = pem.Encode(&encoded, &pem.Block{Type: "CERTIFICATE", Bytes: der})
if err != nil {
BadRequest(w, err.Error())
return
}

OK(w, encoded.String())
}
default:
http.NotFound(w, r)
}
}

func (s *handler) action(r *http.Request) string {
return r.URL.Query().Get("~action")
}
Expand Down
Loading