Skip to content

Commit 30b7da4

Browse files
wip refactor to single dev mode flag
Signed-off-by: greg pereira <[email protected]>
1 parent 49a4236 commit 30b7da4

File tree

1 file changed

+49
-102
lines changed

1 file changed

+49
-102
lines changed

ui/apiserver/apiserver.go

Lines changed: 49 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"encoding/json"
99
"fmt"
1010
"io"
11+
"log"
1112
"net/http"
1213
"os"
1314
"os/exec"
@@ -29,15 +30,11 @@ const (
2930
const (
3031
localEndpoint = "http://localhost:8000/v1"
3132
InstructLabBotUrl = "http://bot:8081"
33+
TLSCertChainPath = "/home/fedora/chain.pem"
34+
TLSClientCRTPath = "/home/fedora/client-tls-crt.pem2"
35+
TLSClientKEYPath = "/home/fedora/client-tls-key.pem2"
3236
)
3337

34-
type TLSConfig struct {
35-
TlsClientCertPath string
36-
TlsClientKeyPath string
37-
TlsServerCaCertPath string
38-
TlsInsecure bool
39-
}
40-
4138
type ApiServer struct {
4239
router *gin.Engine
4340
logger *zap.SugaredLogger
@@ -46,7 +43,7 @@ type ApiServer struct {
4643
testMode bool
4744
preCheckEndpointURL string
4845
instructLabBotUrl string
49-
tlsConfig TLSConfig
46+
devMode bool
5047
}
5148

5249
type JobData struct {
@@ -214,30 +211,23 @@ func (api *ApiServer) knowledgePRHandler(c *gin.Context) {
214211
}
215212

216213
func (api *ApiServer) buildHTTPServer() (http.Client, error) {
217-
defaultHTTPClient := http.Client{
218-
Timeout: 0 * time.Second,
219-
Transport: &http.Transport{
220-
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
221-
},
222-
}
223-
if !api.tlsConfig.TlsInsecure {
224-
certs, err := tls.LoadX509KeyPair(api.tlsConfig.TlsClientCertPath, api.tlsConfig.TlsClientKeyPath)
214+
tlsInseucre := !api.devMode
215+
if !api.devMode {
216+
certPool := x509.NewCertPool()
217+
pemData, err := os.ReadFile(TLSCertChainPath) // Replace with your certificate file path
225218
if err != nil {
226-
api.logger.Warnf("failed to load client certificate/key: %w", err)
227-
return defaultHTTPClient, fmt.Errorf("Error load client certificate/key, defaulting to TLS Insecure session (http)")
219+
err = fmt.Errorf("Failed to read cert chain file: %s", err)
220+
api.logger.Error(err)
221+
return http.Client{}, err
228222
}
229-
// // NOT SURE WE NEED SERVER CA CERT FOR THIS, PLEASE ADVISE
230-
caCert, err := os.ReadFile(api.tlsConfig.TlsServerCaCertPath)
231-
if err != nil {
232-
api.logger.Warnf("failed to read server CA certificate: %w", err)
233-
return defaultHTTPClient, fmt.Errorf("Error load server CA certificate, defaulting to TLS Insecure session (http)")
223+
if !certPool.AppendCertsFromPEM(pemData) {
224+
err = fmt.Errorf("Failed to append pemData to certPool: %s", err)
225+
api.logger.Error(err)
226+
return http.Client{}, err
234227
}
235-
caCertPool := x509.NewCertPool()
236-
caCertPool.AppendCertsFromPEM(caCert)
237228
tlsConfig := &tls.Config{
238-
Certificates: []tls.Certificate{certs},
239-
RootCAs: caCertPool,
240-
InsecureSkipVerify: true,
229+
RootCAs: certPool,
230+
InsecureSkipVerify: tlsInseucre,
241231
}
242232
httpClient := &http.Client{
243233
Transport: &http.Transport{
@@ -248,37 +238,26 @@ func (api *ApiServer) buildHTTPServer() (http.Client, error) {
248238
}
249239
return *httpClient, nil
250240
} else {
251-
return defaultHTTPClient, nil
241+
return http.Client{
242+
Transport: &http.Transport{
243+
TLSClientConfig: &tls.Config{InsecureSkipVerify: tlsInseucre},
244+
},
245+
}, nil
252246
}
253247
}
254248

255249
// Sent http post request using custom client with zero timeout
256250
func (api *ApiServer) sendPostRequest(url string, body io.Reader) (*http.Response, error) {
257251
client, err := api.buildHTTPServer()
258252
if err != nil {
259-
// Either running http with tlsInsecure = true, or https runing with tlsInsecure = false
260-
if err.Error() == "Error load client certificate/key, defaulting to TLS Insecure session (http)" ||
261-
err.Error() == "Error load server CA certificate, defaulting to TLS Insecure session (http)" {
262-
// Handle the specific error (e.g., log it)
263-
api.logger.Warn("Warning: TLS certificate/key or server CA certificate not loaded, downgraded to http client.")
264-
} else {
265-
// Handle other errors
266-
err = fmt.Errorf("Error creating http(s) server: %v", err)
267-
fmt.Print(err)
268-
return nil, err
269-
}
270-
}
271-
272-
request, err := http.NewRequest("POST", url, body)
273-
if err != nil {
274-
api.logger.Errorf("Error creating http request: %v", err)
253+
err = fmt.Errorf("Error creating http(s) server: %v", err)
254+
api.logger.Error(err)
275255
return nil, err
276256
}
277-
request.Header.Set("Content-Type", "application/json")
278-
response, err := client.Do(request)
257+
response, err := client.Post(url, "application/json", body)
279258
if err != nil {
280-
api.logger.Errorf("Error sending http request: %v", err)
281-
return nil, err
259+
api.logger.Errorf("Error creating and or sending http request: %v", err)
260+
return response, err
282261
}
283262
return response, nil
284263
}
@@ -448,26 +427,19 @@ func (api *ApiServer) fetchModelName(fullName bool) (string, error) {
448427
}
449428
endpoint += "models"
450429

451-
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
452-
http.DefaultTransport.(*http.Transport).TLSHandshakeTimeout = 10 * time.Second
453-
http.DefaultTransport.(*http.Transport).ExpectContinueTimeout = 1 * time.Second
454-
455-
req, err := http.NewRequestWithContext(api.ctx, "GET", endpoint, nil)
456-
if err != nil {
457-
return "", fmt.Errorf("failed to create request: %w", err)
458-
}
430+
client, err := api.buildHTTPServer()
459431

460-
resp, err := http.DefaultClient.Do(req)
432+
response, err := client.Get(endpoint)
461433
if err != nil {
462434
return "", fmt.Errorf("failed to fetch model details: %w", err)
463435
}
464-
defer resp.Body.Close()
436+
defer response.Body.Close()
465437

466-
if resp.StatusCode != http.StatusOK {
467-
return "", fmt.Errorf("unexpected status code: %d", resp.StatusCode)
438+
if response.StatusCode != http.StatusOK {
439+
return "", fmt.Errorf("unexpected status code: %d", response.StatusCode)
468440
}
469441

470-
body, err := io.ReadAll(resp.Body)
442+
body, err := io.ReadAll(response.Body)
471443
if err != nil {
472444
return "", fmt.Errorf("failed to read response body: %w", err)
473445
}
@@ -520,10 +492,7 @@ func main() {
520492
preCheckEndpointURL := pflag.String("precheck-endpoint", "", "Precheck endpoint URL")
521493
InstructLabBotUrl := pflag.String("bot-url", InstructLabBotUrl, "InstructLab Bot URL")
522494
// TLS variables
523-
tlsInsecure := pflag.Bool("tls-insecure", false, "Whether to skip TLS verification")
524-
tlsClientCertPath := pflag.String("tls-client-cert", "", "Path to the TLS client certificate. Evantually defaults to '$HOME/client-tls-crt.pem2'")
525-
tlsClientKeyPath := pflag.String("tls-client-key", "", "Path to the TLS client key. Evantually defaults to '$HOME/client-tls-key.pem2'")
526-
tlsServerCaCertPath := pflag.String("tls-server-ca-cert", "", "Path to the TLS server CA certificate. Evantually defaults to '$HOME/server-ca-crt.pem2'")
495+
devMode := pflag.Bool("dev-mode", false, "Whether to skip TLS verification")
527496
pflag.Parse()
528497

529498
/* ENV support, most variabls take 3 options, with the following priority:
@@ -545,34 +514,6 @@ func main() {
545514
}
546515
}
547516

548-
// TLS configurations
549-
HOME := os.Getenv("HOME")
550-
if *tlsClientCertPath == "" {
551-
tlsClientCertPathEnvValue := os.Getenv("TLS_CLIENT_CERT_PATH")
552-
if tlsClientCertPathEnvValue != "" {
553-
*tlsClientCertPath = tlsClientCertPathEnvValue
554-
} else {
555-
*tlsClientCertPath = fmt.Sprintf("%s/client-tls-crt.pem2", HOME)
556-
}
557-
}
558-
// TLS keyPath
559-
if *tlsClientKeyPath == "" {
560-
tlsClientKeyPathEnvValue := os.Getenv("TLS_CLIENT_KEY_PATH")
561-
if tlsClientKeyPathEnvValue != "" {
562-
*tlsClientKeyPath = tlsClientKeyPathEnvValue
563-
} else {
564-
*tlsClientKeyPath = fmt.Sprintf("%s/client-tls-key.pem2", HOME)
565-
}
566-
}
567-
if *tlsServerCaCertPath == "" {
568-
tlsServerCaCertPathEnvValue := os.Getenv("TLS_SERVER_CA_CERT_PATH")
569-
if tlsServerCaCertPathEnvValue != "" {
570-
*tlsServerCaCertPath = tlsServerCaCertPathEnvValue
571-
} else {
572-
*tlsServerCaCertPath = fmt.Sprintf("%s/server-ca-crt.pem2", HOME)
573-
}
574-
}
575-
576517
// NOTE: TLSInsecure not settable by env, just apiserver cli flag or defaults to false
577518

578519
/* API credentials
@@ -604,6 +545,7 @@ func main() {
604545
Addr: *redisAddress,
605546
})
606547

548+
tlsInsecure := !*devMode
607549
router := gin.Default()
608550
svr := ApiServer{
609551
router: router,
@@ -613,21 +555,26 @@ func main() {
613555
testMode: *testMode,
614556
preCheckEndpointURL: *preCheckEndpointURL,
615557
instructLabBotUrl: *InstructLabBotUrl,
616-
tlsConfig: TLSConfig{
617-
TlsInsecure: *tlsInsecure,
618-
TlsClientCertPath: *tlsClientCertPath,
619-
TlsClientKeyPath: *tlsClientKeyPath,
620-
TlsServerCaCertPath: *tlsServerCaCertPath,
621-
},
558+
devMode: *devMode,
622559
}
623560
svr.setupRoutes(*apiUser, *apiPass)
624561

625562
if *tlsInsecure == false {
626563
// Check if we is valid key pair
627-
_, err := tls.LoadX509KeyPair(*tlsClientCertPath, *tlsClientKeyPath)
564+
565+
certPool := x509.NewCertPool()
566+
pemData, err := os.ReadFile(*tlsCertChainPath) // Replace with your certificate file path
628567
if err != nil {
629-
logger.Fatal(fmt.Errorf("TLS enforced but failed to load client certificate/key: %w", err))
568+
log.Fatalf("Failed to read cert chain file: %s", err)
569+
}
570+
if !certPool.AppendCertsFromPEM(pemData) {
571+
log.Fatalf("Failed to append pemData to certPool: %s", err)
630572
}
573+
// tlsConfig := &tls.Config{
574+
// RootCAs: certPool,
575+
// InsecureSkipVerify: *tlsInsecure,
576+
// }
577+
// if err := svr.router.
631578
svr.logger.Info("ApiServer starting with TLS", zap.String("listen-address", *listenAddress))
632579
if err := svr.router.RunTLS(*listenAddress, *tlsClientCertPath, *tlsClientKeyPath); err != nil {
633580
svr.logger.Error("ApiServer failed to start", zap.Error(err))

0 commit comments

Comments
 (0)