github.com/google/fleetspeak@v0.1.15-0.20240426164851-4f31f62c1aea/fleetspeak/src/config/server/config.go (about)

     1  // Copyright 2019 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package serer
    16  package server
    17  
    18  import (
    19  	"errors"
    20  	"fmt"
    21  	"os"
    22  
    23  	"google.golang.org/protobuf/encoding/prototext"
    24  
    25  	cpb "github.com/google/fleetspeak/fleetspeak/src/config/proto/fleetspeak_config"
    26  )
    27  
    28  // WriteConfig validates and then writes a server component configuration.
    29  func WriteConfig(cfg *cpb.Config, certPEM, keyPEM []byte) error {
    30  	if cfg.ServerComponentConfigurationFile == "" {
    31  		return errors.New("server_component_configuration_file is required")
    32  	}
    33  
    34  	cc := cfg.ComponentsConfig
    35  	if cc == nil {
    36  		return errors.New("components_config is required")
    37  	}
    38  	if cc.HttpsConfig == nil {
    39  		return errors.New("components_config.https_config is required")
    40  	}
    41  	if cc.HttpsConfig.ListenAddress == "" {
    42  		return errors.New("components_config.https_config.listen_address is required")
    43  	}
    44  	cc.HttpsConfig.Certificates = string(certPEM)
    45  	cc.HttpsConfig.Key = string(keyPEM)
    46  
    47  	b, err := prototext.Marshal(cc)
    48  	if err != nil {
    49  		return fmt.Errorf("failed to marshal server component configuration: %v", err)
    50  	}
    51  	err = os.WriteFile(cfg.ServerComponentConfigurationFile, b, 0600)
    52  	if err != nil {
    53  		return fmt.Errorf("failed to write server component configuration file [%s]: %v", cfg.ServerComponentConfigurationFile, err)
    54  	}
    55  
    56  	return nil
    57  }