2020-07-27 23:49:43 +00:00
|
|
|
/*
|
|
|
|
Copyright 2020 VMware, Inc.
|
|
|
|
SPDX-License-Identifier: Apache-2.0
|
|
|
|
*/
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2020-07-28 14:10:40 +00:00
|
|
|
"context"
|
2020-07-27 23:49:43 +00:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"os"
|
2020-07-28 14:10:40 +00:00
|
|
|
"time"
|
2020-07-27 23:49:43 +00:00
|
|
|
|
|
|
|
"k8s.io/client-go/pkg/apis/clientauthentication"
|
|
|
|
|
|
|
|
"github.com/suzerain-io/placeholder-name/internal/constable"
|
|
|
|
"github.com/suzerain-io/placeholder-name/pkg/client"
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
2020-07-28 14:10:40 +00:00
|
|
|
err := run(os.LookupEnv, client.ExchangeToken, os.Stdout, 30*time.Second)
|
2020-07-27 23:49:43 +00:00
|
|
|
if err != nil {
|
|
|
|
_, _ = fmt.Fprintf(os.Stderr, "%s", err.Error())
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type envGetter func(string) (string, bool)
|
2020-07-28 14:10:40 +00:00
|
|
|
type tokenExchanger func(ctx context.Context, token, caBundle, apiEndpoint string) (*clientauthentication.ExecCredential, error)
|
2020-07-27 23:49:43 +00:00
|
|
|
|
2020-07-28 13:37:27 +00:00
|
|
|
const ErrMissingEnvVar = constable.Error("failed to login: environment variable not set")
|
2020-07-27 23:49:43 +00:00
|
|
|
|
2020-07-28 14:10:40 +00:00
|
|
|
func run(envGetter envGetter, tokenExchanger tokenExchanger, outputWriter io.Writer, timeout time.Duration) error {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
|
|
|
defer cancel()
|
|
|
|
|
2020-07-27 23:49:43 +00:00
|
|
|
token, varExists := envGetter("PLACEHOLDER_NAME_TOKEN")
|
|
|
|
if !varExists {
|
|
|
|
return envVarNotSetError("PLACEHOLDER_NAME_TOKEN")
|
|
|
|
}
|
|
|
|
|
|
|
|
caBundle, varExists := envGetter("PLACEHOLDER_NAME_CA_BUNDLE")
|
|
|
|
if !varExists {
|
|
|
|
return envVarNotSetError("PLACEHOLDER_NAME_CA_BUNDLE")
|
|
|
|
}
|
|
|
|
|
|
|
|
apiEndpoint, varExists := envGetter("PLACEHOLDER_NAME_K8S_API_ENDPOINT")
|
|
|
|
if !varExists {
|
|
|
|
return envVarNotSetError("PLACEHOLDER_NAME_K8S_API_ENDPOINT")
|
|
|
|
}
|
|
|
|
|
2020-07-28 14:10:40 +00:00
|
|
|
execCredential, err := tokenExchanger(ctx, token, caBundle, apiEndpoint)
|
2020-07-27 23:49:43 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to login: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
err = json.NewEncoder(outputWriter).Encode(execCredential)
|
|
|
|
if err != nil {
|
2020-07-28 13:41:26 +00:00
|
|
|
return fmt.Errorf("failed to marshal response to stdout: %w", err)
|
2020-07-27 23:49:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func envVarNotSetError(varName string) error {
|
2020-07-28 13:37:27 +00:00
|
|
|
return fmt.Errorf("%w: %s", ErrMissingEnvVar, varName)
|
2020-07-27 23:49:43 +00:00
|
|
|
}
|