rebase: bump the github-dependencies group with 5 updates

Bumps the github-dependencies group with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [github.com/aws/aws-sdk-go](https://github.com/aws/aws-sdk-go) | `1.49.21` | `1.50.6` |
| [github.com/google/uuid](https://github.com/google/uuid) | `1.5.0` | `1.6.0` |
| [github.com/hashicorp/vault/api](https://github.com/hashicorp/vault) | `1.10.0` | `1.11.0` |
| [github.com/onsi/ginkgo/v2](https://github.com/onsi/ginkgo) | `2.14.0` | `2.15.0` |
| [github.com/onsi/gomega](https://github.com/onsi/gomega) | `1.30.0` | `1.31.1` |


Updates `github.com/aws/aws-sdk-go` from 1.49.21 to 1.50.6
- [Release notes](https://github.com/aws/aws-sdk-go/releases)
- [Commits](https://github.com/aws/aws-sdk-go/compare/v1.49.21...v1.50.6)

Updates `github.com/google/uuid` from 1.5.0 to 1.6.0
- [Release notes](https://github.com/google/uuid/releases)
- [Changelog](https://github.com/google/uuid/blob/master/CHANGELOG.md)
- [Commits](https://github.com/google/uuid/compare/v1.5.0...v1.6.0)

Updates `github.com/hashicorp/vault/api` from 1.10.0 to 1.11.0
- [Release notes](https://github.com/hashicorp/vault/releases)
- [Changelog](https://github.com/hashicorp/vault/blob/main/CHANGELOG.md)
- [Commits](https://github.com/hashicorp/vault/compare/v1.10.0...v1.11.0)

Updates `github.com/onsi/ginkgo/v2` from 2.14.0 to 2.15.0
- [Release notes](https://github.com/onsi/ginkgo/releases)
- [Changelog](https://github.com/onsi/ginkgo/blob/master/CHANGELOG.md)
- [Commits](https://github.com/onsi/ginkgo/compare/v2.14.0...v2.15.0)

Updates `github.com/onsi/gomega` from 1.30.0 to 1.31.1
- [Release notes](https://github.com/onsi/gomega/releases)
- [Changelog](https://github.com/onsi/gomega/blob/master/CHANGELOG.md)
- [Commits](https://github.com/onsi/gomega/compare/v1.30.0...v1.31.1)

---
updated-dependencies:
- dependency-name: github.com/aws/aws-sdk-go
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-dependencies
- dependency-name: github.com/google/uuid
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-dependencies
- dependency-name: github.com/hashicorp/vault/api
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-dependencies
- dependency-name: github.com/onsi/ginkgo/v2
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-dependencies
- dependency-name: github.com/onsi/gomega
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
This commit is contained in:
dependabot[bot]
2024-01-29 20:22:47 +00:00
committed by mergify[bot]
parent 926ae07170
commit f578798f01
38 changed files with 733 additions and 74 deletions

8
vendor/github.com/hashicorp/vault/api/.copywrite.hcl generated vendored Normal file
View File

@ -0,0 +1,8 @@
schema_version = 1
project {
license = "MPL-2.0"
copyright_year = 2024
header_ignore = []
}

View File

@ -82,6 +82,8 @@ const (
const (
EnvVaultAgentAddress = "VAULT_AGENT_ADDR"
EnvVaultInsecure = "VAULT_SKIP_VERIFY"
DefaultAddress = "https://127.0.0.1:8200"
)
// WrappingLookupFunc is a function that, given an HTTP verb and a path,
@ -248,7 +250,7 @@ type TLSConfig struct {
// If an error is encountered, the Error field on the returned *Config will be populated with the specific error.
func DefaultConfig() *Config {
config := &Config{
Address: "https://127.0.0.1:8200",
Address: DefaultAddress,
HttpClient: cleanhttp.DefaultPooledClient(),
Timeout: time.Second * 60,
MinRetryWait: time.Millisecond * 1000,
@ -528,6 +530,7 @@ func (c *Config) ParseAddress(address string) (*url.URL, error) {
return nil, err
}
previousAddress := c.Address
c.Address = address
if strings.HasPrefix(address, "unix://") {
@ -550,7 +553,7 @@ func (c *Config) ParseAddress(address string) (*url.URL, error) {
} else {
return nil, fmt.Errorf("attempting to specify unix:// address with non-transport transport")
}
} else if strings.HasPrefix(c.Address, "unix://") {
} else if strings.HasPrefix(previousAddress, "unix://") {
// When the address being set does not begin with unix:// but the previous
// address in the Config did, change the transport's DialContext back to
// use the default configuration that cleanhttp uses.
@ -589,6 +592,7 @@ type Client struct {
requestCallbacks []RequestCallback
responseCallbacks []ResponseCallback
replicationStateStore *replicationStateStore
hcpCookie *http.Cookie
}
// NewClient returns a new client for the given configuration.
@ -1025,6 +1029,33 @@ func (c *Client) SetToken(v string) {
c.token = v
}
// HCPCookie returns the HCP cookie being used by this client. It will
// return an empty cookie when no cookie is set.
func (c *Client) HCPCookie() string {
c.modifyLock.RLock()
defer c.modifyLock.RUnlock()
if c.hcpCookie == nil {
return ""
}
return c.hcpCookie.String()
}
// SetHCPCookie sets the hcp cookie directly. This won't perform any auth
// verification, it simply sets the token properly for future requests.
func (c *Client) SetHCPCookie(v *http.Cookie) error {
c.modifyLock.Lock()
defer c.modifyLock.Unlock()
if err := v.Valid(); err != nil {
return err
}
c.hcpCookie = v
return nil
}
// ClearToken deletes the token if it is set or does nothing otherwise.
func (c *Client) ClearToken() {
c.modifyLock.Lock()
@ -1299,6 +1330,8 @@ func (c *Client) NewRequest(method, requestPath string) *Request {
Params: make(map[string][]string),
}
req.HCPCookie = c.hcpCookie
var lookupPath string
switch {
case strings.HasPrefix(requestPath, "/v1/"):

View File

@ -212,6 +212,17 @@ func (c *Logical) WriteWithContext(ctx context.Context, path string, data map[st
return c.write(ctx, path, r)
}
func (c *Logical) WriteRaw(path string, data []byte) (*Response, error) {
return c.WriteRawWithContext(context.Background(), path, data)
}
func (c *Logical) WriteRawWithContext(ctx context.Context, path string, data []byte) (*Response, error) {
r := c.c.NewRequest(http.MethodPut, "/v1/"+path)
r.BodyBytes = data
return c.writeRaw(ctx, r)
}
func (c *Logical) JSONMergePatch(ctx context.Context, path string, data map[string]interface{}) (*Secret, error) {
r := c.c.NewRequest(http.MethodPatch, "/v1/"+path)
r.Headers.Set("Content-Type", "application/merge-patch+json")
@ -261,6 +272,14 @@ func (c *Logical) write(ctx context.Context, path string, request *Request) (*Se
return ParseSecret(resp.Body)
}
func (c *Logical) writeRaw(ctx context.Context, request *Request) (*Response, error) {
ctx, cancelFunc := c.c.withConfiguredTimeout(ctx)
defer cancelFunc()
resp, err := c.c.rawRequestWithContext(ctx, request)
return resp, err
}
func (c *Logical) Delete(path string) (*Secret, error) {
return c.DeleteWithContext(context.Background(), path)
}

View File

@ -51,6 +51,7 @@ type PluginAPIClientMeta struct {
flagCAPath string
flagClientCert string
flagClientKey string
flagServerName string
flagInsecure bool
}
@ -62,6 +63,7 @@ func (f *PluginAPIClientMeta) FlagSet() *flag.FlagSet {
fs.StringVar(&f.flagCAPath, "ca-path", "", "")
fs.StringVar(&f.flagClientCert, "client-cert", "", "")
fs.StringVar(&f.flagClientKey, "client-key", "", "")
fs.StringVar(&f.flagServerName, "tls-server-name", "", "")
fs.BoolVar(&f.flagInsecure, "tls-skip-verify", false, "")
return fs
@ -70,13 +72,13 @@ func (f *PluginAPIClientMeta) FlagSet() *flag.FlagSet {
// GetTLSConfig will return a TLSConfig based off the values from the flags
func (f *PluginAPIClientMeta) GetTLSConfig() *TLSConfig {
// If we need custom TLS configuration, then set it
if f.flagCACert != "" || f.flagCAPath != "" || f.flagClientCert != "" || f.flagClientKey != "" || f.flagInsecure {
if f.flagCACert != "" || f.flagCAPath != "" || f.flagClientCert != "" || f.flagClientKey != "" || f.flagInsecure || f.flagServerName != "" {
t := &TLSConfig{
CACert: f.flagCACert,
CAPath: f.flagCAPath,
ClientCert: f.flagClientCert,
ClientKey: f.flagClientKey,
TLSServerName: "",
TLSServerName: f.flagServerName,
Insecure: f.flagInsecure,
}

View File

@ -7,7 +7,10 @@ package api
// https://github.com/hashicorp/vault/blob/main/sdk/helper/consts/plugin_types.go
// Any changes made should be made to both files at the same time.
import "fmt"
import (
"encoding/json"
"fmt"
)
var PluginTypes = []PluginType{
PluginTypeUnknown,
@ -64,3 +67,34 @@ func ParsePluginType(pluginType string) (PluginType, error) {
return PluginTypeUnknown, fmt.Errorf("%q is not a supported plugin type", pluginType)
}
}
// UnmarshalJSON implements json.Unmarshaler. It supports unmarshaling either a
// string or a uint32. All new serialization will be as a string, but we
// previously serialized as a uint32 so we need to support that for backwards
// compatibility.
func (p *PluginType) UnmarshalJSON(data []byte) error {
var asString string
err := json.Unmarshal(data, &asString)
if err == nil {
*p, err = ParsePluginType(asString)
return err
}
var asUint32 uint32
err = json.Unmarshal(data, &asUint32)
if err != nil {
return err
}
*p = PluginType(asUint32)
switch *p {
case PluginTypeUnknown, PluginTypeCredential, PluginTypeDatabase, PluginTypeSecrets:
return nil
default:
return fmt.Errorf("%d is not a supported plugin type", asUint32)
}
}
// MarshalJSON implements json.Marshaler.
func (p PluginType) MarshalJSON() ([]byte, error) {
return json.Marshal(p.String())
}

View File

@ -19,11 +19,13 @@ const (
)
type ClusterInfo struct {
APIAddr string `json:"api_address,omitempty" mapstructure:"api_address"`
ClusterAddress string `json:"cluster_address,omitempty" mapstructure:"cluster_address"`
ConnectionStatus string `json:"connection_status,omitempty" mapstructure:"connection_status"`
LastHeartBeat string `json:"last_heartbeat,omitempty" mapstructure:"last_heartbeat"`
NodeID string `json:"node_id,omitempty" mapstructure:"node_id"`
APIAddr string `json:"api_address,omitempty" mapstructure:"api_address"`
ClusterAddress string `json:"cluster_address,omitempty" mapstructure:"cluster_address"`
ConnectionStatus string `json:"connection_status,omitempty" mapstructure:"connection_status"`
LastHeartBeat string `json:"last_heartbeat,omitempty" mapstructure:"last_heartbeat"`
LastHeartBeatDurationMillis string `json:"last_heartbeat_duration_ms,omitempty" mapstructure:"last_heartbeat_duration_ms"`
ClockSkewMillis string `json:"clock_skew_ms,omitempty" mapstructure:"clock_skew_ms"`
NodeID string `json:"node_id,omitempty" mapstructure:"node_id"`
}
type ReplicationStatusGenericResponse struct {

View File

@ -39,6 +39,9 @@ type Request struct {
// EGPs). If set, the override flag will take effect for all policies
// evaluated during the request.
PolicyOverride bool
// HCPCookie is used to set a http cookie when client is connected to HCP
HCPCookie *http.Cookie
}
// SetJSONBody is used to set a request body that is a JSON-encoded value.
@ -145,5 +148,9 @@ func (r *Request) toRetryableHTTP() (*retryablehttp.Request, error) {
req.Header.Set("X-Vault-Policy-Override", "true")
}
if r.HCPCookie != nil {
req.AddCookie(r.HCPCookie)
}
return req, nil
}

View File

@ -42,6 +42,10 @@ type Secret struct {
// cubbyhole of the given token (which has a TTL of the given number of
// seconds)
WrapInfo *SecretWrapInfo `json:"wrap_info,omitempty"`
// MountType, if non-empty, provides some information about what kind
// of mount this secret came from.
MountType string `json:"mount_type,omitempty"`
}
// TokenID returns the standardized token ID (token) for the given secret.

View File

@ -78,3 +78,56 @@ func (c *Sys) CapabilitiesWithContext(ctx context.Context, token, path string) (
return res, nil
}
func (c *Sys) CapabilitiesAccessor(accessor, path string) ([]string, error) {
return c.CapabilitiesAccessorWithContext(context.Background(), accessor, path)
}
func (c *Sys) CapabilitiesAccessorWithContext(ctx context.Context, accessor, path string) ([]string, error) {
ctx, cancelFunc := c.c.withConfiguredTimeout(ctx)
defer cancelFunc()
body := map[string]string{
"accessor": accessor,
"path": path,
}
reqPath := "/v1/sys/capabilities-accessor"
r := c.c.NewRequest(http.MethodPost, reqPath)
if err := r.SetJSONBody(body); err != nil {
return nil, err
}
resp, err := c.c.rawRequestWithContext(ctx, r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
secret, err := ParseSecret(resp.Body)
if err != nil {
return nil, err
}
if secret == nil || secret.Data == nil {
return nil, errors.New("data from server response is empty")
}
var res []string
err = mapstructure.Decode(secret.Data[path], &res)
if err != nil {
return nil, err
}
if len(res) == 0 {
_, ok := secret.Data["capabilities"]
if ok {
err = mapstructure.Decode(secret.Data["capabilities"], &res)
if err != nil {
return nil, err
}
}
}
return res, nil
}

View File

@ -35,12 +35,14 @@ type HAStatusResponse struct {
}
type HANode struct {
Hostname string `json:"hostname"`
APIAddress string `json:"api_address"`
ClusterAddress string `json:"cluster_address"`
ActiveNode bool `json:"active_node"`
LastEcho *time.Time `json:"last_echo"`
Version string `json:"version"`
UpgradeVersion string `json:"upgrade_version,omitempty"`
RedundancyZone string `json:"redundancy_zone,omitempty"`
Hostname string `json:"hostname"`
APIAddress string `json:"api_address"`
ClusterAddress string `json:"cluster_address"`
ActiveNode bool `json:"active_node"`
LastEcho *time.Time `json:"last_echo"`
EchoDurationMillis int64 `json:"echo_duration_ms"`
ClockSkewMillis int64 `json:"clock_skew_ms"`
Version string `json:"version"`
UpgradeVersion string `json:"upgrade_version,omitempty"`
RedundancyZone string `json:"redundancy_zone,omitempty"`
}

View File

@ -49,4 +49,7 @@ type HealthResponse struct {
ClusterName string `json:"cluster_name,omitempty"`
ClusterID string `json:"cluster_id,omitempty"`
LastWAL uint64 `json:"last_wal,omitempty"`
Enterprise bool `json:"enterprise"`
EchoDurationMillis int64 `json:"echo_duration_ms"`
ClockSkewMillis int64 `json:"clock_skew_ms"`
}

View File

@ -271,6 +271,9 @@ type MountConfigInput struct {
AllowedManagedKeys []string `json:"allowed_managed_keys,omitempty" mapstructure:"allowed_managed_keys"`
PluginVersion string `json:"plugin_version,omitempty"`
UserLockoutConfig *UserLockoutConfigInput `json:"user_lockout_config,omitempty"`
DelegatedAuthAccessors []string `json:"delegated_auth_accessors,omitempty" mapstructure:"delegated_auth_accessors"`
IdentityTokenKey string `json:"identity_token_key,omitempty" mapstructure:"identity_token_key"`
// Deprecated: This field will always be blank for newer server responses.
PluginName string `json:"plugin_name,omitempty" mapstructure:"plugin_name"`
}
@ -303,6 +306,9 @@ type MountConfigOutput struct {
TokenType string `json:"token_type,omitempty" mapstructure:"token_type"`
AllowedManagedKeys []string `json:"allowed_managed_keys,omitempty" mapstructure:"allowed_managed_keys"`
UserLockoutConfig *UserLockoutConfigOutput `json:"user_lockout_config,omitempty"`
DelegatedAuthAccessors []string `json:"delegated_auth_accessors,omitempty" mapstructure:"delegated_auth_accessors"`
IdentityTokenKey string `json:"identity_token_key,omitempty" mapstructure:"identity_token_key"`
// Deprecated: This field will always be blank for newer server responses.
PluginName string `json:"plugin_name,omitempty" mapstructure:"plugin_name"`
}

View File

@ -36,6 +36,8 @@ type ListPluginsResponse struct {
type PluginDetails struct {
Type string `json:"type"`
Name string `json:"name"`
OCIImage string `json:"oci_image,omitempty" mapstructure:"oci_image"`
Runtime string `json:"runtime,omitempty"`
Version string `json:"version,omitempty"`
Builtin bool `json:"builtin"`
DeprecationStatus string `json:"deprecation_status,omitempty" mapstructure:"deprecation_status"`
@ -144,9 +146,10 @@ type GetPluginResponse struct {
Args []string `json:"args"`
Builtin bool `json:"builtin"`
Command string `json:"command"`
OCIImage string `json:"oci_image"`
Name string `json:"name"`
SHA256 string `json:"sha256"`
OCIImage string `json:"oci_image,omitempty"`
Runtime string `json:"runtime,omitempty"`
DeprecationStatus string `json:"deprecation_status,omitempty"`
Version string `json:"version,omitempty"`
}
@ -206,6 +209,9 @@ type RegisterPluginInput struct {
// OCIImage specifies the container image to run as a plugin.
OCIImage string `json:"oci_image,omitempty"`
// Runtime is the Vault plugin runtime to use when running the plugin.
Runtime string `json:"runtime,omitempty"`
// Env specifies a list of key=value pairs to add to the plugin's environment
// variables.
Env []string `json:"env,omitempty"`
@ -268,6 +274,22 @@ func (c *Sys) DeregisterPluginWithContext(ctx context.Context, i *DeregisterPlug
return err
}
// RootReloadPluginInput is used as input to the RootReloadPlugin function.
type RootReloadPluginInput struct {
Plugin string `json:"-"` // Plugin name, as registered in the plugin catalog.
Type PluginType `json:"-"` // Plugin type: auth, secret, or database.
Scope string `json:"scope,omitempty"` // Empty to reload on current node, "global" for all nodes.
}
// RootReloadPlugin reloads plugins, possibly returning reloadID for a global
// scoped reload. This is only available in the root namespace, and reloads
// plugins across all namespaces, whereas ReloadPlugin is available in all
// namespaces but only reloads plugins in use in the request's namespace.
func (c *Sys) RootReloadPlugin(ctx context.Context, i *RootReloadPluginInput) (string, error) {
path := fmt.Sprintf("/v1/sys/plugins/reload/%s/%s", i.Type.String(), i.Plugin)
return c.reloadPluginInternal(ctx, path, i, i.Scope == "global")
}
// ReloadPluginInput is used as input to the ReloadPlugin function.
type ReloadPluginInput struct {
// Plugin is the name of the plugin to reload, as registered in the plugin catalog
@ -286,15 +308,20 @@ func (c *Sys) ReloadPlugin(i *ReloadPluginInput) (string, error) {
}
// ReloadPluginWithContext reloads mounted plugin backends, possibly returning
// reloadId for a cluster scoped reload
// reloadID for a cluster scoped reload. It is limited to reloading plugins that
// are in use in the request's namespace. See RootReloadPlugin for an API that
// can reload plugins across all namespaces.
func (c *Sys) ReloadPluginWithContext(ctx context.Context, i *ReloadPluginInput) (string, error) {
return c.reloadPluginInternal(ctx, "/v1/sys/plugins/reload/backend", i, i.Scope == "global")
}
func (c *Sys) reloadPluginInternal(ctx context.Context, path string, body any, global bool) (string, error) {
ctx, cancelFunc := c.c.withConfiguredTimeout(ctx)
defer cancelFunc()
path := "/v1/sys/plugins/reload/backend"
req := c.c.NewRequest(http.MethodPut, path)
if err := req.SetJSONBody(i); err != nil {
if err := req.SetJSONBody(body); err != nil {
return "", err
}
@ -304,7 +331,7 @@ func (c *Sys) ReloadPluginWithContext(ctx context.Context, i *ReloadPluginInput)
}
defer resp.Body.Close()
if i.Scope == "global" {
if global {
// Get the reload id
secret, parseErr := ParseSecret(resp.Body)
if parseErr != nil {

View File

@ -64,8 +64,9 @@ type RegisterPluginRuntimeInput struct {
OCIRuntime string `json:"oci_runtime,omitempty"`
CgroupParent string `json:"cgroup_parent,omitempty"`
CPU int64 `json:"cpu,omitempty"`
Memory int64 `json:"memory,omitempty"`
CPU int64 `json:"cpu_nanos,omitempty"`
Memory int64 `json:"memory_bytes,omitempty"`
Rootless bool `json:"rootless,omitempty"`
}
// RegisterPluginRuntime registers the plugin with the given information.

View File

@ -109,6 +109,7 @@ type SealStatusResponse struct {
ClusterName string `json:"cluster_name,omitempty"`
ClusterID string `json:"cluster_id,omitempty"`
RecoverySeal bool `json:"recovery_seal"`
RecoverySealType string `json:"recovery_seal_type,omitempty"`
StorageType string `json:"storage_type,omitempty"`
HCPLinkStatus string `json:"hcp_link_status,omitempty"`
HCPLinkResourceID string `json:"hcp_link_resource_ID,omitempty"`

View File

@ -0,0 +1,281 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
)
const (
// baseEndpoint is the common base URL path for all endpoints used in this
// module.
baseEndpoint string = "/v1/sys/config/ui/custom-messages"
)
// ListUICustomMessages calls ListUICustomMessagesWithContext using a background
// Context.
func (c *Sys) ListUICustomMessages(req UICustomMessageListRequest) (*Secret, error) {
return c.ListUICustomMessagesWithContext(context.Background(), req)
}
// ListUICustomMessagesWithContext sends a request to the List custom messages
// endpoint using the provided Context and UICustomMessageListRequest value as
// the inputs. It returns a pointer to a Secret if a response was obtained from
// the server, including error responses; or an error if a response could not be
// obtained due to an error.
func (c *Sys) ListUICustomMessagesWithContext(ctx context.Context, req UICustomMessageListRequest) (*Secret, error) {
ctx, cancelFunc := c.c.withConfiguredTimeout(ctx)
defer cancelFunc()
r := c.c.NewRequest("LIST", fmt.Sprintf("%s/", baseEndpoint))
if req.Active != nil {
r.Params.Add("active", strconv.FormatBool(*req.Active))
}
if req.Authenticated != nil {
r.Params.Add("authenticated", strconv.FormatBool(*req.Authenticated))
}
if req.Type != nil {
r.Params.Add("type", *req.Type)
}
resp, err := c.c.rawRequestWithContext(ctx, r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
secret, err := ParseSecret(resp.Body)
if err != nil {
return nil, err
}
if secret == nil || secret.Data == nil {
return nil, errors.New("data from server response is empty")
}
return secret, nil
}
// CreateUICustomMessage calls CreateUICustomMessageWithContext using a
// background Context.
func (c *Sys) CreateUICustomMessage(req UICustomMessageRequest) (*Secret, error) {
return c.CreateUICustomMessageWithContext(context.Background(), req)
}
// CreateUICustomMessageWithContext sends a request to the Create custom
// messages endpoint using the provided Context and UICustomMessageRequest
// values as the inputs. It returns a pointer to a Secret if a response was
// obtained from the server, including error responses; or an error if a
// response could not be obtained due to an error.
func (c *Sys) CreateUICustomMessageWithContext(ctx context.Context, req UICustomMessageRequest) (*Secret, error) {
ctx, cancelFunc := c.c.withConfiguredTimeout(ctx)
defer cancelFunc()
r := c.c.NewRequest(http.MethodPost, baseEndpoint)
if err := r.SetJSONBody(&req); err != nil {
return nil, fmt.Errorf("error encoding request body to json: %w", err)
}
resp, err := c.c.rawRequestWithContext(ctx, r)
if err != nil {
return nil, fmt.Errorf("error sending request to server: %w", err)
}
defer resp.Body.Close()
secret, err := ParseSecret(resp.Body)
if err != nil {
return nil, fmt.Errorf("could not parse secret from server response: %w", err)
}
if secret == nil || secret.Data == nil {
return nil, errors.New("data from server response is empty")
}
return secret, nil
}
// ReadUICustomMessage calls ReadUICustomMessageWithContext using a background
// Context.
func (c *Sys) ReadUICustomMessage(id string) (*Secret, error) {
return c.ReadUICustomMessageWithContext(context.Background(), id)
}
// ReadUICustomMessageWithContext sends a request to the Read custom message
// endpoint using the provided Context and id values. It returns a pointer to a
// Secret if a response was obtained from the server, including error responses;
// or an error if a response could not be obtained due to an error.
func (c *Sys) ReadUICustomMessageWithContext(ctx context.Context, id string) (*Secret, error) {
ctx, cancelFunc := c.c.withConfiguredTimeout(ctx)
defer cancelFunc()
r := c.c.NewRequest(http.MethodGet, fmt.Sprintf("%s/%s", baseEndpoint, id))
resp, err := c.c.rawRequestWithContext(ctx, r)
if err != nil {
return nil, fmt.Errorf("error sending request to server: %w", err)
}
defer resp.Body.Close()
secret, err := ParseSecret(resp.Body)
if err != nil {
return nil, fmt.Errorf("could not parse secret from server response: %w", err)
}
if secret == nil || secret.Data == nil {
return nil, errors.New("data from server response is empty")
}
return secret, nil
}
// UpdateUICustomMessage calls UpdateUICustomMessageWithContext using a
// background Context.
func (c *Sys) UpdateUICustomMessage(id string, req UICustomMessageRequest) error {
return c.UpdateUICustomMessageWithContext(context.Background(), id, req)
}
// UpdateUICustomMessageWithContext sends a request to the Update custom message
// endpoint using the provided Context, id, and UICustomMessageRequest values.
// It returns a pointer to a Secret if a response was obtained from the server,
// including error responses; or an error if a response could not be obtained
// due to an error.
func (c *Sys) UpdateUICustomMessageWithContext(ctx context.Context, id string, req UICustomMessageRequest) error {
ctx, cancelFunc := c.c.withConfiguredTimeout(ctx)
defer cancelFunc()
r := c.c.NewRequest(http.MethodPost, fmt.Sprintf("%s/%s", baseEndpoint, id))
if err := r.SetJSONBody(&req); err != nil {
return fmt.Errorf("error encoding request body to json: %w", err)
}
resp, err := c.c.rawRequestWithContext(ctx, r)
if err != nil {
return fmt.Errorf("error sending request to server: %w", err)
}
defer resp.Body.Close()
return nil
}
// DeleteUICustomMessage calls DeleteUICustomMessageWithContext using a
// background Context.
func (c *Sys) DeleteUICustomMessage(id string) error {
return c.DeletePolicyWithContext(context.Background(), id)
}
// DeleteUICustomMessageWithContext sends a request to the Delete custom message
// endpoint using the provided Context and id values. It returns a pointer to a
// Secret if a response was obtained from the server, including error responses;
// or an error if a response could not be obtained due to an error.
func (c *Sys) DeleteUICustomMessageWithContext(ctx context.Context, id string) error {
ctx, cancelFunc := c.c.withConfiguredTimeout(ctx)
defer cancelFunc()
r := c.c.NewRequest(http.MethodDelete, fmt.Sprintf("%s/%s", baseEndpoint, id))
resp, err := c.c.rawRequestWithContext(ctx, r)
if err != nil {
return fmt.Errorf("error sending request to server: %w", err)
}
defer resp.Body.Close()
return nil
}
// UICustomMessageListRequest is a struct used to contain inputs for the List
// custom messages request. Each field is optional, so their types are pointers.
// The With... methods can be used to easily set the fields with pointers to
// values.
type UICustomMessageListRequest struct {
Authenticated *bool
Type *string
Active *bool
}
// WithAuthenticated sets the Authenticated field to a pointer referencing the
// provided bool value.
func (r *UICustomMessageListRequest) WithAuthenticated(value bool) *UICustomMessageListRequest {
r.Authenticated = &value
return r
}
// WithType sets the Type field to a pointer referencing the provided string
// value.
func (r *UICustomMessageListRequest) WithType(value string) *UICustomMessageListRequest {
r.Type = &value
return r
}
// WithActive sets the Active field to a pointer referencing the provided bool
// value.
func (r *UICustomMessageListRequest) WithActive(value bool) *UICustomMessageListRequest {
r.Active = &value
return r
}
// UICustomMessageRequest is a struct containing the properties of a custom
// message. The Link field can be set using the WithLink method.
type UICustomMessageRequest struct {
Title string `json:"title"`
Message string `json:"message"`
Authenticated bool `json:"authenticated"`
Type string `json:"type"`
StartTime string `json:"start_time"`
EndTime string `json:"end_time,omitempty"`
Link *uiCustomMessageLink `json:"link,omitempty"`
Options map[string]any `json:"options,omitempty"`
}
// WithLink sets the Link field to the address of a new uiCustomMessageLink
// struct constructed from the provided title and href values.
func (r *UICustomMessageRequest) WithLink(title, href string) *UICustomMessageRequest {
r.Link = &uiCustomMessageLink{
Title: title,
Href: href,
}
return r
}
// uiCustomMessageLink is a utility struct used to represent a link associated
// with a custom message.
type uiCustomMessageLink struct {
Title string
Href string
}
// MarshalJSON encodes the state of the receiver uiCustomMessageLink as JSON and
// returns those encoded bytes or an error.
func (l uiCustomMessageLink) MarshalJSON() ([]byte, error) {
m := make(map[string]string)
m[l.Title] = l.Href
return json.Marshal(m)
}
// UnmarshalJSON updates the state of the receiver uiCustomMessageLink from the
// provided JSON encoded bytes. It returns an error if there was a failure.
func (l *uiCustomMessageLink) UnmarshalJSON(b []byte) error {
m := make(map[string]string)
if err := json.Unmarshal(b, &m); err != nil {
return err
}
for k, v := range m {
l.Title = k
l.Href = v
break
}
return nil
}