Skip to content
Snippets Groups Projects
client.go 2.16 KiB
Newer Older
  • Learn to ignore specific revisions
  • package client
    
    
    import (
    	"bytes"
    	"encoding/json"
    
    	"net/http"
    
    	"code.fbi.h-da.de/danet/quant/goKMS/config"
    
    	"code.fbi.h-da.de/danet/quant/goKMS/kms/crypto"
    
    	kmstls "code.fbi.h-da.de/danet/quant/goKMS/kms/tls"
    
    	"github.com/sirupsen/logrus"
    
    )
    
    type CkmsAkmsClient struct {
    
    	url        string
    	httpClient *http.Client
    
    func NewCkmsAkmsClient(url string, tlsConfig config.TLSConfig) (*CkmsAkmsClient, error) {
    	client := &http.Client{}
    
    	if tlsConfig.Active {
    		tlsConf, err := kmstls.GenerateTLSLibraryConfig(tlsConfig)
    		if err != nil {
    			return nil, fmt.Errorf("unable to generate TLS config: %w", err)
    		}
    
    		client.Transport = &http.Transport{
    			TLSClientConfig: tlsConf,
    		}
    
    
    	return &CkmsAkmsClient{
    		url:        url,
    		httpClient: client,
    	}, nil
    
    }
    
    type PushKSAKeyRequest struct {
    
    	RequestID string          `json:"request_ID"`
    	ProcessID string          `json:"process_ID"`
    	KSAKeys   []crypto.KSAKey `json:"ksa_keys"`
    
    func (c *CkmsAkmsClient) SendKSAKeysToRequestingInstances(requestID string, processID string, ksaKeys []crypto.KSAKey) error {
    
    	pushRequest := PushKSAKeyRequest{
    		RequestID: requestID,
    		ProcessID: processID,
    		KSAKeys:   ksaKeys,
    	}
    
    	jsonData, err := json.Marshal(pushRequest)
    	if err != nil {
    
    		logrus.Errorf("Error marshaling JSON: %s", err)
    
    		return err
    	}
    
    
    	logrus.Infof("Attempting to send KSA post request to AKMS with URL: %s", c.url)
    
    	resp, err := c.httpClient.Post(c.url, "application/json", bytes.NewBuffer(jsonData))
    
    	if err != nil {
    
    		body, err2 := io.ReadAll(resp.Body)
    		if err2 != nil {
    			logrus.Errorf("Error reading POST response body: %s", err2)
    		}
    		logrus.Errorf("Error sending POST request: %s, received response body: %s", err, string(body))
    
    		logrus.Errorf("Tried to send request: %s to url: %s", jsonData, c.url)
    
    		return err
    	}
    	err = resp.Body.Close()
    	if err != nil {
    
    		logrus.Errorf("Error closing response body: %s", err)
    
    	}
    
    	if resp.StatusCode != http.StatusNoContent {
    
    		logrus.Errorf("Unexpected response status code: %d", resp.StatusCode)
    		logrus.Errorf("Tried to send request: %s to url: %s", jsonData, c.url)
    
    		return err
    	}
    
    
    	logrus.Infof("Successfully sent request: %s to url: %s", jsonData, c.url)
    
    	return nil
    }