func addKey()

in internal/beatcmd/keystore_nofips.go [148:216]


func addKey(store keystore.Keystore, keys []string, force, stdin bool) error {
	if len(keys) == 0 {
		return errors.New("failed to create the secret: no key provided")
	}

	if len(keys) > 1 {
		return fmt.Errorf("could not create secret for: %s, you can only provide one key per invocation", keys)
	}

	writableKeystore, err := keystore.AsWritableKeystore(store)
	if err != nil {
		return fmt.Errorf("error creating the keystore: %w", err)
	}

	if !store.IsPersisted() {
		if !force {
			create := terminal.PromptYesNo("The keystore does not exist. Do you want to create it?", false)
			if !create {
				return errors.New("exiting without creating keystore")
			}
		}
		err := writableKeystore.Create(true)
		if err != nil {
			return fmt.Errorf("could not create keystore, error: %w", err)
		}
		fmt.Println("Created keystore")
	}

	key := strings.TrimSpace(keys[0])
	if _, err := store.Retrieve(key); err == nil {
		if !force {
			if stdin {
				return fmt.Errorf("the settings %s already exist in the keystore use `--force` to replace it", key)
			}
			overwrite := terminal.PromptYesNo(fmt.Sprintf("Setting %s already exists, Overwrite?", key), false)
			if !overwrite {
				fmt.Println("Exiting without modifying keystore.")
				return nil
			}
		}
	} else if !errors.Is(err, keystore.ErrKeyDoesntExists) {
		return err
	}

	var keyValue []byte
	if stdin {
		reader := bufio.NewReader(os.Stdin)
		keyValue, err = io.ReadAll(reader)
		if err != nil {
			return fmt.Errorf("could not read input from stdin")
		}
	} else {
		fmt.Printf("Enter value for %s: ", key)
		keyValue, err = term.ReadPassword(int(syscall.Stdin))
		fmt.Println()
		if err != nil {
			return fmt.Errorf("could not read value from the input, error: %w", err)
		}
	}
	if err = writableKeystore.Store(key, keyValue); err != nil {
		return fmt.Errorf("could not add the key in the keystore, error: %w", err)
	}
	if err = writableKeystore.Save(); err != nil {
		return fmt.Errorf("fail to save the keystore: %w", err)
	} else {
		fmt.Println("Successfully updated the keystore")
	}
	return nil
}