go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers-sdk/v1/upstream/upstream.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package upstream
     5  
     6  import (
     7  	"errors"
     8  	"net/http"
     9  
    10  	"github.com/rs/zerolog/log"
    11  	"go.mondoo.com/cnquery/utils/multierr"
    12  	"go.mondoo.com/ranger-rpc"
    13  	guard_cert_auth "go.mondoo.com/ranger-rpc/plugins/authentication/cert"
    14  	"go.mondoo.com/ranger-rpc/plugins/rangerguard/crypto"
    15  )
    16  
    17  //go:generate protoc --proto_path=../../:. --go_out=. --go_opt=paths=source_relative --rangerrpc_out=. upstream.proto
    18  
    19  const agents_issuer = "mondoo/ams"
    20  
    21  func NewServiceAccountRangerPlugin(credentials *ServiceAccountCredentials) (ranger.ClientPlugin, error) {
    22  	if credentials == nil {
    23  		return nil, errors.New("agent credentials must be set")
    24  	}
    25  
    26  	// verify that we can read the private key
    27  	privateKey, err := crypto.PrivateKeyFromBytes([]byte(credentials.PrivateKey))
    28  	if err != nil {
    29  		return nil, errors.New("cannot load retrieved key: " + err.Error())
    30  	}
    31  
    32  	log.Debug().Str("kid", credentials.Mrn).Str("issuer", agents_issuer).Msg("initialize client authentication")
    33  
    34  	// configure authentication plugin, since the server only accepts authenticated calls
    35  	return guard_cert_auth.NewRangerPlugin(guard_cert_auth.ClientConfig{
    36  		PrivateKey: privateKey,
    37  		Issuer:     agents_issuer,
    38  		Kid:        credentials.Mrn,
    39  		Subject:    credentials.Mrn,
    40  	})
    41  }
    42  
    43  // mondoo platform config so that resource scan talk upstream
    44  // TODO: this configuration struct does not belong into the MQL package
    45  // nevertheless the MQL runtime needs to have something that allows users
    46  // to store additional credentials so that resource can use those for
    47  // their resources.
    48  type UpstreamClient struct {
    49  	UpstreamConfig
    50  	Plugins    []ranger.ClientPlugin
    51  	HttpClient *http.Client
    52  }
    53  
    54  func (c *UpstreamConfig) InitClient() (*UpstreamClient, error) {
    55  	certAuth, err := NewServiceAccountRangerPlugin(c.Creds)
    56  	if err != nil {
    57  		return nil, multierr.Wrap(err, "could not initialize client authentication")
    58  	}
    59  
    60  	res := UpstreamClient{
    61  		UpstreamConfig: *c,
    62  		Plugins:        []ranger.ClientPlugin{certAuth},
    63  		HttpClient:     ranger.DefaultHttpClient(),
    64  	}
    65  
    66  	return &res, nil
    67  }