Merge pull request #90 from OpenCHAMI/final-default-secrets

Final default secrets
This commit is contained in:
David Allen 2025-04-21 15:42:06 -06:00 committed by GitHub
commit 726eed016a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 288 additions and 174 deletions

View file

@ -9,7 +9,7 @@ import (
urlx "github.com/OpenCHAMI/magellan/internal/url" urlx "github.com/OpenCHAMI/magellan/internal/url"
magellan "github.com/OpenCHAMI/magellan/pkg" magellan "github.com/OpenCHAMI/magellan/pkg"
"github.com/OpenCHAMI/magellan/pkg/auth" "github.com/OpenCHAMI/magellan/pkg/auth"
"github.com/OpenCHAMI/magellan/pkg/crawler" "github.com/OpenCHAMI/magellan/pkg/bmc"
"github.com/OpenCHAMI/magellan/pkg/secrets" "github.com/OpenCHAMI/magellan/pkg/secrets"
"github.com/cznic/mathutil" "github.com/cznic/mathutil"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
@ -61,6 +61,59 @@ var CollectCmd = &cobra.Command{
concurrency = mathutil.Clamp(len(scannedResults), 1, 10000) concurrency = mathutil.Clamp(len(scannedResults), 1, 10000)
} }
// use secret store for BMC credentials, and/or credential CLI flags
var store secrets.SecretStore
if username != "" && password != "" {
// First, try and load credentials from --username and --password if both are set.
log.Debug().Msgf("--username and --password specified, using them for BMC credentials")
store = secrets.NewStaticStore(username, password)
} else {
// Alternatively, locate specific credentials (falling back to default) and override those
// with --username or --password if either are passed.
log.Debug().Msgf("one or both of --username and --password NOT passed, attempting to obtain missing credentials from secret store at %s", secretsFile)
if store, err = secrets.OpenStore(secretsFile); err != nil {
log.Error().Err(err).Msg("failed to open local secrets store")
}
// Temporarily override username/password of each BMC if one of those
// flags is passed. The expectation is that if the flag is specified
// on the command line, it should be used.
if username != "" {
log.Info().Msg("--username passed, temporarily overriding all usernames from secret store with value")
}
if password != "" {
log.Info().Msg("--password passed, temporarily overriding all passwords from secret store with value")
}
switch s := store.(type) {
case *secrets.StaticStore:
if username != "" {
s.Username = username
}
if password != "" {
s.Password = password
}
case *secrets.LocalSecretStore:
for k, _ := range s.Secrets {
if creds, err := bmc.GetBMCCredentials(store, k); err != nil {
log.Error().Str("id", k).Err(err).Msg("failed to override BMC credentials")
} else {
if username != "" {
creds.Username = username
}
if password != "" {
creds.Password = password
}
if newCreds, err := json.Marshal(creds); err != nil {
log.Error().Str("id", k).Err(err).Msg("failed to override BMC credentials: marshal error")
} else {
s.StoreSecretByID(k, string(newCreds))
}
}
}
}
}
// set the collect parameters from CLI params // set the collect parameters from CLI params
params := &magellan.CollectParams{ params := &magellan.CollectParams{
URI: host, URI: host,
@ -71,9 +124,7 @@ var CollectCmd = &cobra.Command{
OutputPath: outputPath, OutputPath: outputPath,
ForceUpdate: forceUpdate, ForceUpdate: forceUpdate,
AccessToken: accessToken, AccessToken: accessToken,
SecretsFile: secretsFile, SecretStore: store,
Username: username,
Password: password,
} }
// show all of the 'collect' parameters being set from CLI if verbose // show all of the 'collect' parameters being set from CLI if verbose
@ -81,41 +132,7 @@ var CollectCmd = &cobra.Command{
log.Debug().Any("params", params) log.Debug().Any("params", params)
} }
// load the secrets file to get node credentials by ID (i.e. the BMC node's URI) _, err = magellan.CollectInventory(&scannedResults, params)
store, err := secrets.OpenStore(params.SecretsFile)
if err != nil {
log.Warn().Err(err).Msg("failed to open local store...falling back to default provided arguments")
// try and use the `username` and `password` arguments instead
store = secrets.NewStaticStore(username, password)
}
// found the store so try to load the creds
_, err = store.GetSecretByID(host)
if err != nil {
// if we have CLI flags set, then we want to override default stored creds
if username != "" && password != "" {
// finally, use the CLI arguments passed instead
log.Info().Msg("...using provided arguments for credentials")
store = secrets.NewStaticStore(username, password)
} else {
// try and get a default *stored* username/password
secret, err := store.GetSecretByID(secrets.DEFAULT_KEY)
if err != nil {
// no default found, so use CLI arguments
log.Warn().Err(err).Msg("failed to get default credentials...")
} else {
// found default values in local store so use them
log.Info().Msg("...using default store for credentials")
var creds crawler.BMCUsernamePassword
err = json.Unmarshal([]byte(secret), &creds)
if err != nil {
log.Warn().Err(err).Msg("failed to unmarshal default store credentials")
}
}
}
}
_, err = magellan.CollectInventory(&scannedResults, params, store)
if err != nil { if err != nil {
log.Error().Err(err).Msg("failed to collect data") log.Error().Err(err).Msg("failed to collect data")
} }
@ -124,18 +141,15 @@ var CollectCmd = &cobra.Command{
func init() { func init() {
currentUser, _ = user.Current() currentUser, _ = user.Current()
CollectCmd.PersistentFlags().StringVar(&host, "host", "", "Set the URI to the SMD root endpoint") CollectCmd.Flags().StringVar(&host, "host", "", "Set the URI to the SMD root endpoint")
CollectCmd.PersistentFlags().StringVarP(&username, "username", "u", "", "Set the master BMC username") CollectCmd.Flags().StringVarP(&username, "username", "u", "", "Set the master BMC username")
CollectCmd.PersistentFlags().StringVarP(&password, "password", "p", "", "Set the master BMC password") CollectCmd.Flags().StringVarP(&password, "password", "p", "", "Set the master BMC password")
CollectCmd.PersistentFlags().StringVar(&secretsFile, "secrets-file", "", "Set path to the node secrets file") CollectCmd.Flags().StringVar(&secretsFile, "secrets-file", "", "Set path to the node secrets file")
CollectCmd.PersistentFlags().StringVar(&scheme, "scheme", "https", "Set the default scheme used to query when not included in URI") CollectCmd.Flags().StringVar(&scheme, "scheme", "https", "Set the default scheme used to query when not included in URI")
CollectCmd.PersistentFlags().StringVar(&protocol, "protocol", "tcp", "Set the protocol used to query") CollectCmd.Flags().StringVar(&protocol, "protocol", "tcp", "Set the protocol used to query")
CollectCmd.PersistentFlags().StringVarP(&outputPath, "output", "o", fmt.Sprintf("/tmp/%smagellan/inventory/", currentUser.Username+"/"), "Set the path to store collection data") CollectCmd.Flags().StringVarP(&outputPath, "output", "o", fmt.Sprintf("/tmp/%smagellan/inventory/", currentUser.Username+"/"), "Set the path to store collection data")
CollectCmd.PersistentFlags().BoolVar(&forceUpdate, "force-update", false, "Set flag to force update data sent to SMD") CollectCmd.Flags().BoolVar(&forceUpdate, "force-update", false, "Set flag to force update data sent to SMD")
CollectCmd.PersistentFlags().StringVar(&cacertPath, "cacert", "", "Set the path to CA cert file. (defaults to system CAs when blank)") CollectCmd.Flags().StringVar(&cacertPath, "cacert", "", "Set the path to CA cert file. (defaults to system CAs when blank)")
// set flags to only be used together
CollectCmd.MarkFlagsRequiredTogether("username", "password")
// bind flags to config properties // bind flags to config properties
checkBindFlagError(viper.BindPFlag("collect.host", CollectCmd.Flags().Lookup("host"))) checkBindFlagError(viper.BindPFlag("collect.host", CollectCmd.Flags().Lookup("host")))

View file

@ -7,6 +7,7 @@ import (
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
urlx "github.com/OpenCHAMI/magellan/internal/url" urlx "github.com/OpenCHAMI/magellan/internal/url"
"github.com/OpenCHAMI/magellan/pkg/bmc"
"github.com/OpenCHAMI/magellan/pkg/crawler" "github.com/OpenCHAMI/magellan/pkg/crawler"
"github.com/OpenCHAMI/magellan/pkg/secrets" "github.com/OpenCHAMI/magellan/pkg/secrets"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -43,60 +44,32 @@ var CrawlCmd = &cobra.Command{
if username != "" && password != "" { if username != "" && password != "" {
// First, try and load credentials from --username and --password if both are set. // First, try and load credentials from --username and --password if both are set.
log.Debug().Str("uri", uri).Msgf("--username and --password specified, using them for BMC credentials") log.Debug().Str("id", uri).Msgf("--username and --password specified, using them for BMC credentials")
store = secrets.NewStaticStore(username, password) store = secrets.NewStaticStore(username, password)
} else { } else {
// Alternatively, locate specific credentials (falling back to default) and override those // Alternatively, locate specific credentials (falling back to default) and override those
// with --username or --password if either are passed. // with --username or --password if either are passed.
log.Debug().Str("uri", uri).Msgf("one or both of --username and --password NOT passed, attempting to obtain missing credentials from secret store at %s", secretsFile) log.Debug().Str("id", uri).Msgf("one or both of --username and --password NOT passed, attempting to obtain missing credentials from secret store at %s", secretsFile)
if store, err = secrets.OpenStore(secretsFile); err != nil { if store, err = secrets.OpenStore(secretsFile); err != nil {
log.Error().Str("uri", uri).Err(err).Msg("failed to open local secrets store") log.Error().Str("id", uri).Err(err).Msg("failed to open local secrets store")
} }
// Either none of the flags were passed or only one of them were; get // Either none of the flags were passed or only one of them were; get
// credentials from secrets store to fill in the gaps. // credentials from secrets store to fill in the gaps.
// bmcCreds, _ := bmc.GetBMCCredentials(store, uri)
// Attempt to get URI-specific credentials. nodeCreds := secrets.StaticStore{
var nodeCreds secrets.StaticStore Username: bmcCreds.Username,
if uriCreds, err := store.GetSecretByID(uri); err != nil { Password: bmcCreds.Password,
// Specific credentials for URI not found, fetch default.
log.Warn().Str("uri", uri).Msg("specific credentials not found, falling back to default")
defaultSecret, err := store.GetSecretByID(secrets.DEFAULT_KEY)
if err != nil {
// We've exhausted all options, the credentials will be blank unless
// overridden by a CLI flag.
log.Warn().Str("uri", uri).Err(err).Msg("no default credentials were set, they will be blank unless overridden by CLI flags")
} else {
// Default credentials found, use them.
var creds crawler.BMCUsernamePassword
if err = json.Unmarshal([]byte(defaultSecret), &creds); err != nil {
log.Warn().Str("uri", uri).Err(err).Msg("failed to unmarshal default secrets store credentials")
} else {
log.Info().Str("uri", uri).Msg("default credentials found, using")
nodeCreds.Username = creds.Username
nodeCreds.Password = creds.Password
}
}
} else {
// Specific URI credentials found, use them.
var creds crawler.BMCUsernamePassword
if err = json.Unmarshal([]byte(uriCreds), &creds); err != nil {
log.Warn().Str("uri", uri).Err(err).Msg("failed to unmarshal uri credentials")
} else {
nodeCreds.Username = creds.Username
nodeCreds.Password = creds.Password
log.Info().Str("uri", uri).Msg("specific credentials found, using")
}
} }
// If either of the flags were passed, override the fetched // If either of the flags were passed, override the fetched
// credentials with them. // credentials with them.
if username != "" { if username != "" {
log.Info().Str("uri", uri).Msg("--username was set, overriding username for this BMC") log.Info().Str("id", uri).Msg("--username was set, overriding username for this BMC")
nodeCreds.Username = username nodeCreds.Username = username
} }
if password != "" { if password != "" {
log.Info().Str("uri", uri).Msg("--password was set, overriding password for this BMC") log.Info().Str("id", uri).Msg("--password was set, overriding password for this BMC")
nodeCreds.Password = password nodeCreds.Password = password
} }

View file

@ -5,6 +5,8 @@ import (
"strings" "strings"
magellan "github.com/OpenCHAMI/magellan/pkg" magellan "github.com/OpenCHAMI/magellan/pkg"
"github.com/OpenCHAMI/magellan/pkg/bmc"
"github.com/OpenCHAMI/magellan/pkg/secrets"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
@ -41,6 +43,46 @@ var updateCmd = &cobra.Command{
os.Exit(1) os.Exit(1)
} }
// use secret store for BMC credentials, and/or credential CLI flags
var (
store secrets.SecretStore
uri = args[0]
err error
)
if username != "" && password != "" {
// First, try and load credentials from --username and --password if both are set.
log.Debug().Str("id", uri).Msgf("--username and --password specified, using them for BMC credentials")
store = secrets.NewStaticStore(username, password)
} else {
// Alternatively, locate specific credentials (falling back to default) and override those
// with --username or --password if either are passed.
log.Debug().Str("id", uri).Msgf("one or both of --username and --password NOT passed, attempting to obtain missing credentials from secret store at %s", secretsFile)
if store, err = secrets.OpenStore(secretsFile); err != nil {
log.Error().Str("id", uri).Err(err).Msg("failed to open local secrets store")
}
// Either none of the flags were passed or only one of them were; get
// credentials from secrets store to fill in the gaps.
bmcCreds, _ := bmc.GetBMCCredentials(store, uri)
nodeCreds := secrets.StaticStore{
Username: bmcCreds.Username,
Password: bmcCreds.Password,
}
// If either of the flags were passed, override the fetched
// credentials with them.
if username != "" {
log.Info().Str("id", uri).Msg("--username was set, overriding username for this BMC")
nodeCreds.Username = username
}
if password != "" {
log.Info().Str("id", uri).Msg("--password was set, overriding password for this BMC")
nodeCreds.Password = password
}
store = &nodeCreds
}
// get status if flag is set and exit // get status if flag is set and exit
for _, arg := range args { for _, arg := range args {
if showStatus { if showStatus {
@ -49,10 +91,9 @@ var updateCmd = &cobra.Command{
TransferProtocol: transferProtocol, TransferProtocol: transferProtocol,
Insecure: Insecure, Insecure: Insecure,
CollectParams: magellan.CollectParams{ CollectParams: magellan.CollectParams{
URI: arg, URI: arg,
Username: username, SecretStore: store,
Password: password, Timeout: timeout,
Timeout: timeout,
}, },
}) })
if err != nil { if err != nil {
@ -67,10 +108,9 @@ var updateCmd = &cobra.Command{
TransferProtocol: strings.ToUpper(transferProtocol), TransferProtocol: strings.ToUpper(transferProtocol),
Insecure: Insecure, Insecure: Insecure,
CollectParams: magellan.CollectParams{ CollectParams: magellan.CollectParams{
URI: arg, URI: arg,
Username: username, SecretStore: store,
Password: password, Timeout: timeout,
Timeout: timeout,
}, },
}) })
if err != nil { if err != nil {

47
internal/util/bmc.go Normal file
View file

@ -0,0 +1,47 @@
package util
import (
"github.com/OpenCHAMI/magellan/pkg/bmc"
"github.com/OpenCHAMI/magellan/pkg/secrets"
"github.com/rs/zerolog/log"
)
func GetBMCCredentials(store secrets.SecretStore, id string) bmc.BMCCredentials {
var (
creds bmc.BMCCredentials
err error
)
if id == "" {
log.Error().Msg("failed to get BMC credentials: id was empty")
return creds
}
if id == secrets.DEFAULT_KEY {
log.Info().Msg("fetching default credentials")
if creds, err = bmc.GetBMCCredentialsDefault(store); err != nil {
log.Warn().Err(err).Msg("failed to get default credentials")
} else {
log.Info().Msg("default credentials found, using")
}
return creds
}
if creds, err = bmc.GetBMCCredentials(store, id); err != nil {
// Specific credentials for URI not found, fetch default.
log.Warn().Str("id", id).Msg("specific credentials not found, falling back to default")
if defaultSecret, err := bmc.GetBMCCredentialsDefault(store); err != nil {
// We've exhausted all options, the credentials will be blank unless
// overridden by a CLI flag.
log.Warn().Str("id", id).Err(err).Msg("no default credentials were set, they will be blank unless overridden by CLI flags")
} else {
// Default credentials found, use them.
log.Info().Str("id", id).Msg("default credentials found, using")
creds = defaultSecret
}
} else {
log.Info().Str("id", id).Msg("specific credentials found, using")
}
return creds
}

65
pkg/bmc/bmc.go Normal file
View file

@ -0,0 +1,65 @@
package bmc
import (
"encoding/json"
"fmt"
"github.com/OpenCHAMI/magellan/pkg/secrets"
)
type BMCCredentials struct {
Username string `json:"username"`
Password string `json:"password"`
}
func GetBMCCredentialsDefault(store secrets.SecretStore) (BMCCredentials, error) {
var creds BMCCredentials
if strCreds, err := store.GetSecretByID(secrets.DEFAULT_KEY); err != nil {
return creds, fmt.Errorf("get default BMC credentials from secret store: %w", err)
} else {
// Default URI credentials found, use them.
if err = json.Unmarshal([]byte(strCreds), &creds); err != nil {
return creds, fmt.Errorf("get default BMC credentials from secret store: failed to unmarshal: %w", err)
}
return creds, nil
}
}
func GetBMCCredentials(store secrets.SecretStore, id string) (BMCCredentials, error) {
var creds BMCCredentials
if strCreds, err := store.GetSecretByID(id); err != nil {
return creds, fmt.Errorf("get BMC credentials from secret store: %w", err)
} else {
// Specific URI credentials found, use them.
if err = json.Unmarshal([]byte(strCreds), &creds); err != nil {
return creds, fmt.Errorf("get BMC credentials from secret store: failed to unmarshal: %w", err)
}
}
return creds, nil
}
func GetBMCCredentialsOrDefault(store secrets.SecretStore, id string) BMCCredentials {
var (
creds BMCCredentials
err error
)
if id == "" {
return creds
}
if id == secrets.DEFAULT_KEY {
creds, _ = GetBMCCredentialsDefault(store)
return creds
}
if creds, err = GetBMCCredentials(store, id); err != nil {
if defaultSecret, err := GetBMCCredentialsDefault(store); err == nil {
// Default credentials found, use them.
creds = defaultSecret
}
}
return creds
}

View file

@ -15,6 +15,7 @@ import (
"sync" "sync"
"time" "time"
"github.com/OpenCHAMI/magellan/pkg/bmc"
"github.com/OpenCHAMI/magellan/pkg/client" "github.com/OpenCHAMI/magellan/pkg/client"
"github.com/OpenCHAMI/magellan/pkg/crawler" "github.com/OpenCHAMI/magellan/pkg/crawler"
"github.com/OpenCHAMI/magellan/pkg/secrets" "github.com/OpenCHAMI/magellan/pkg/secrets"
@ -31,17 +32,15 @@ import (
// CollectParams is a collection of common parameters passed to the CLI // CollectParams is a collection of common parameters passed to the CLI
// for the 'collect' subcommand. // for the 'collect' subcommand.
type CollectParams struct { type CollectParams struct {
URI string // set by the 'host' flag URI string // set by the 'host' flag
Username string // set the BMC username with the 'username' flag Concurrency int // set the of concurrent jobs with the 'concurrency' flag
Password string // set the BMC password with the 'password' flag Timeout int // set the timeout with the 'timeout' flag
Concurrency int // set the of concurrent jobs with the 'concurrency' flag CaCertPath string // set the cert path with the 'cacert' flag
Timeout int // set the timeout with the 'timeout' flag Verbose bool // set whether to include verbose output with 'verbose' flag
CaCertPath string // set the cert path with the 'cacert' flag OutputPath string // set the path to save output with 'output' flag
Verbose bool // set whether to include verbose output with 'verbose' flag ForceUpdate bool // set whether to force updating SMD with 'force-update' flag
OutputPath string // set the path to save output with 'output' flag AccessToken string // set the access token to include in request with 'access-token' flag
ForceUpdate bool // set whether to force updating SMD with 'force-update' flag SecretStore secrets.SecretStore // set BMC credentials
AccessToken string // set the access token to include in request with 'access-token' flag
SecretsFile string // set the path to secrets file
} }
// This is the main function used to collect information from the BMC nodes via Redfish. // This is the main function used to collect information from the BMC nodes via Redfish.
@ -50,7 +49,7 @@ type CollectParams struct {
// //
// Requests can be made to several of the nodes using a goroutine by setting the q.Concurrency // Requests can be made to several of the nodes using a goroutine by setting the q.Concurrency
// property value between 1 and 10000. // property value between 1 and 10000.
func CollectInventory(assets *[]RemoteAsset, params *CollectParams, localStore secrets.SecretStore) ([]map[string]any, error) { func CollectInventory(assets *[]RemoteAsset, params *CollectParams) ([]map[string]any, error) {
// check for available remote assets found from scan // check for available remote assets found from scan
if assets == nil { if assets == nil {
return nil, fmt.Errorf("no assets found") return nil, fmt.Errorf("no assets found")
@ -120,46 +119,36 @@ func CollectInventory(assets *[]RemoteAsset, params *CollectParams, localStore s
// crawl BMC node to fetch inventory data via Redfish // crawl BMC node to fetch inventory data via Redfish
var ( var (
fallbackStore = secrets.NewStaticStore(params.Username, params.Password) systems []crawler.InventoryDetail
systems []crawler.InventoryDetail managers []crawler.Manager
managers []crawler.Manager config = crawler.CrawlerConfig{
config = crawler.CrawlerConfig{
URI: uri, URI: uri,
CredentialStore: localStore, CredentialStore: params.SecretStore,
Insecure: true, Insecure: true,
UseDefault: true, UseDefault: true,
} }
err error err error
) )
// determine if local store exists and has credentials for
// the provided secretID...
// if it does not, use the fallback static store instead with
// the username and password provided as arguments
if localStore != nil {
_, err := localStore.GetSecretByID(uri)
if err != nil {
log.Warn().Err(err).Msgf("could not retrieve secrets for '%s'...falling back to credentials provided with flags -u/-p for user '%s'", uri, params.Username)
if params.Username != "" && params.Password != "" {
config.CredentialStore = fallbackStore
} else if !config.UseDefault {
log.Warn().Msgf("no fallback credentials provided for '%s'", params.Username)
continue
}
}
} else {
log.Warn().Msgf("invalid store for %s...falling back to default provided credentials for user '%s'", uri, params.Username)
config.CredentialStore = fallbackStore
}
// crawl for node and BMC information // crawl for node and BMC information
systems, err = crawler.CrawlBMCForSystems(config) systems, err = crawler.CrawlBMCForSystems(config)
if err != nil { if err != nil {
log.Error().Err(err).Msg("failed to crawl BMC for systems") log.Error().Err(err).Str("uri", uri).Msg("failed to crawl BMC for systems")
} }
managers, err = crawler.CrawlBMCForManagers(config) managers, err = crawler.CrawlBMCForManagers(config)
if err != nil { if err != nil {
log.Error().Err(err).Msg("failed to crawl BMC for managers") log.Error().Err(err).Str("uri", uri).Msg("failed to crawl BMC for managers")
}
// we didn't find anything so do not proceed
if len(systems) == 0 && len(managers) == 0 {
continue
}
// get BMC username to send
bmcCreds := bmc.GetBMCCredentialsOrDefault(params.SecretStore, config.URI)
if bmcCreds == (bmc.BMCCredentials{}) {
log.Warn().Str("id", config.URI).Msg("username will be blank")
} }
// data to be sent to smd // data to be sent to smd
@ -168,7 +157,7 @@ func CollectInventory(assets *[]RemoteAsset, params *CollectParams, localStore s
"Type": "", "Type": "",
"Name": "", "Name": "",
"FQDN": sr.Host, "FQDN": sr.Host,
"User": params.Username, "User": bmcCreds.Username,
"MACRequired": true, "MACRequired": true,
"RediscoverOnUpdate": false, "RediscoverOnUpdate": false,
"Systems": systems, "Systems": systems,

View file

@ -1,10 +1,11 @@
package crawler package crawler
import ( import (
"encoding/json"
"fmt" "fmt"
"strings" "strings"
"github.com/OpenCHAMI/magellan/internal/util"
"github.com/OpenCHAMI/magellan/pkg/bmc"
"github.com/OpenCHAMI/magellan/pkg/secrets" "github.com/OpenCHAMI/magellan/pkg/secrets"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"github.com/stmcginnis/gofish" "github.com/stmcginnis/gofish"
@ -18,15 +19,10 @@ type CrawlerConfig struct {
UseDefault bool UseDefault bool
} }
func (cc *CrawlerConfig) GetUserPass() (BMCUsernamePassword, error) { func (cc *CrawlerConfig) GetUserPass() (bmc.BMCCredentials, error) {
return loadBMCCreds(*cc) return loadBMCCreds(*cc)
} }
type BMCUsernamePassword struct {
Username string `json:"username"`
Password string `json:"password"`
}
type EthernetInterface struct { type EthernetInterface struct {
URI string `json:"uri,omitempty"` // URI of the interface URI string `json:"uri,omitempty"` // URI of the interface
MAC string `json:"mac,omitempty"` // MAC address of the interface MAC string `json:"mac,omitempty"` // MAC address of the interface
@ -373,37 +369,14 @@ func walkManagers(rf_managers []*redfish.Manager, baseURI string) ([]Manager, er
return managers, nil return managers, nil
} }
func loadBMCCreds(config CrawlerConfig) (BMCUsernamePassword, error) { func loadBMCCreds(config CrawlerConfig) (bmc.BMCCredentials, error) {
// NOTE: it is possible for the SecretStore to be nil, so we need a check // NOTE: it is possible for the SecretStore to be nil, so we need a check
if config.CredentialStore == nil { if config.CredentialStore == nil {
return BMCUsernamePassword{}, fmt.Errorf("credential store is invalid") return bmc.BMCCredentials{}, fmt.Errorf("credential store is invalid")
} }
creds, err := config.CredentialStore.GetSecretByID(config.URI) if creds := util.GetBMCCredentials(config.CredentialStore, config.URI); creds == (bmc.BMCCredentials{}) {
if err != nil { return creds, fmt.Errorf("%s: credentials blank for BNC", config.URI)
event := log.Error() } else {
event.Err(err) return creds, nil
event.Msg("failed to get credentials from secret store")
// try to get default if parameter is set
if config.UseDefault {
creds, err = config.CredentialStore.GetSecretByID(secrets.DEFAULT_KEY)
// no default credentials
if err != nil {
event := log.Error()
event.Err(err)
event.Msg("failed to get default credentials from secret store")
return BMCUsernamePassword{}, err
}
} else {
return BMCUsernamePassword{}, err
}
} }
var bmc_creds BMCUsernamePassword
err = json.Unmarshal([]byte(creds), &bmc_creds)
if err != nil {
event := log.Error()
event.Err(err)
event.Msg("failed to unmarshal credentials")
return BMCUsernamePassword{}, err
}
return bmc_creds, nil
} }

View file

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"net/url" "net/url"
"github.com/OpenCHAMI/magellan/pkg/bmc"
"github.com/stmcginnis/gofish" "github.com/stmcginnis/gofish"
"github.com/stmcginnis/gofish/redfish" "github.com/stmcginnis/gofish/redfish"
) )
@ -34,8 +35,14 @@ func UpdateFirmwareRemote(q *UpdateParams) error {
return fmt.Errorf("failed to parse URI: %w", err) return fmt.Errorf("failed to parse URI: %w", err)
} }
// Get BMC credentials from secret store in update parameters
bmcCreds, err := bmc.GetBMCCredentials(q.SecretStore, q.URI)
if err != nil {
return fmt.Errorf("failed to get BMC credentials: %w", err)
}
// Connect to the Redfish service using gofish // Connect to the Redfish service using gofish
client, err := gofish.Connect(gofish.ClientConfig{Endpoint: uri.String(), Username: q.Username, Password: q.Password, Insecure: q.Insecure}) client, err := gofish.Connect(gofish.ClientConfig{Endpoint: uri.String(), Username: bmcCreds.Username, Password: bmcCreds.Password, Insecure: q.Insecure})
if err != nil { if err != nil {
return fmt.Errorf("failed to connect to Redfish service: %w", err) return fmt.Errorf("failed to connect to Redfish service: %w", err)
} }
@ -70,8 +77,14 @@ func GetUpdateStatus(q *UpdateParams) error {
return fmt.Errorf("failed to parse URI: %w", err) return fmt.Errorf("failed to parse URI: %w", err)
} }
// Get BMC credentials from secret store in update parameters
bmcCreds, err := bmc.GetBMCCredentials(q.SecretStore, q.URI)
if err != nil {
return fmt.Errorf("failed to get BMC credentials: %w", err)
}
// Connect to the Redfish service using gofish // Connect to the Redfish service using gofish
client, err := gofish.Connect(gofish.ClientConfig{Endpoint: uri.String(), Username: q.Username, Password: q.Password, Insecure: q.Insecure}) client, err := gofish.Connect(gofish.ClientConfig{Endpoint: uri.String(), Username: bmcCreds.Username, Password: bmcCreds.Password, Insecure: q.Insecure})
if err != nil { if err != nil {
return fmt.Errorf("failed to connect to Redfish service: %w", err) return fmt.Errorf("failed to connect to Redfish service: %w", err)
} }