-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathclient.go
More file actions
262 lines (234 loc) · 7.43 KB
/
client.go
File metadata and controls
262 lines (234 loc) · 7.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// Copyright 2025-2026 Docker, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package client
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"time"
"connectrpc.com/connect"
"github.com/docker/secrets-engine/x/api"
healthv1 "github.com/docker/secrets-engine/x/api/health/v1"
"github.com/docker/secrets-engine/x/api/health/v1/healthv1connect"
"github.com/docker/secrets-engine/x/api/resolver"
v1 "github.com/docker/secrets-engine/x/api/resolver/v1"
"github.com/docker/secrets-engine/x/api/resolver/v1/resolverv1connect"
"github.com/docker/secrets-engine/x/secrets"
)
type (
Envelope = secrets.Envelope
ID = secrets.ID
Pattern = secrets.Pattern
DaemonVersion = api.DaemonVersion
)
var (
ParseID = secrets.ParseID
MustParseID = secrets.MustParseID
ParsePattern = secrets.ParsePattern
MustParsePattern = secrets.MustParsePattern
ErrSecretNotFound = secrets.ErrNotFound
ErrSecretsEngineNotAvailable = errors.New("secrets engine is not available")
)
var _ secrets.Resolver = &client{}
type Option func(c *config) error
func WithSocketPath(path string) Option {
return func(s *config) error {
if path == "" {
return errors.New("no path provided")
}
if s.dialContext != nil {
return errors.New("cannot set socket path and dial")
}
s.dialContext = dialFromPath(path)
return nil
}
}
func WithDialContext(dialContext func(ctx context.Context, network, addr string) (net.Conn, error)) Option {
return func(s *config) error {
if s.dialContext != nil {
return errors.New("cannot set socket path and dial")
}
s.dialContext = dialContext
return nil
}
}
// WithTimeout overrides the request timeout of the client.
//
// It is useful to set if there are hard-limits to when the client must wait
// for the server to accept the request.
//
// A timout of 0 means no request timeout will be applied.
// Negative durations are not allowed and will result in an error.
func WithTimeout(timeout time.Duration) Option {
return func(s *config) error {
if timeout < 0 {
return errors.New("request timeout duration cannot be negative")
}
s.requestTimeout = timeout
return nil
}
}
// WithResponseTimeout overrides the response header timeout of the client.
//
// It is useful to set if there are long-lived user interactions required
// when the Secrets Engine requests secrets from a plugin.
//
// A responseTimeout of 0 means no response header timeout will be applied.
// Negative durations are not allowed and will result in an error.
func WithResponseTimeout(responseTimeout time.Duration) Option {
return func(s *config) error {
if responseTimeout < 0 {
return errors.New("response timeout duration cannot be negative")
}
s.responseTimeout = responseTimeout
return nil
}
}
type dial func(ctx context.Context, network, addr string) (net.Conn, error)
type config struct {
dialContext dial
requestTimeout time.Duration
responseTimeout time.Duration
}
type client struct {
resolverClient secrets.Resolver
listClient resolverv1connect.ListServiceClient
versionClient healthv1connect.VersionServiceClient
}
func (c client) GetSecrets(ctx context.Context, pattern secrets.Pattern) ([]secrets.Envelope, error) {
envelopes, err := c.resolverClient.GetSecrets(ctx, pattern)
if isDialError(err) {
return nil, fmt.Errorf("%w: %w", ErrSecretsEngineNotAvailable, err)
}
if err != nil {
return nil, err
}
return envelopes, nil
}
func (c client) Version(ctx context.Context) (DaemonVersion, error) {
resp, err := c.versionClient.GetVersion(ctx, connect.NewRequest(healthv1.GetVersionRequest_builder{}.Build()))
if isDialError(err) {
return DaemonVersion{}, fmt.Errorf("%w: %w", ErrSecretsEngineNotAvailable, err)
}
if err != nil {
return DaemonVersion{}, err
}
ver, err := api.NewVersion(resp.Msg.GetVersion())
if err != nil {
return DaemonVersion{}, fmt.Errorf("parsing daemon version %q: %w", resp.Msg.GetVersion(), err)
}
return DaemonVersion{Version: ver, Date: resp.Msg.GetDate(), CommitHash: resp.Msg.GetCommitHash()}, nil
}
// Client is the interface for interacting with the secrets engine daemon.
type Client interface {
secrets.Resolver
// Version returns the name and version reported by the daemon.
Version(ctx context.Context) (DaemonVersion, error)
ListPlugins(ctx context.Context) ([]PluginInfo, error)
}
func isDialError(err error) bool {
if err == nil {
return false
}
var oe *net.OpError
if errors.As(err, &oe) && (oe.Op == "dial" || oe.Op == "connect") {
return true
}
return false
}
func New(options ...Option) (Client, error) {
cfg := &config{
requestTimeout: api.DefaultClientRequestTimeout,
responseTimeout: api.DefaultClientResponseHeaderTimeout,
}
for _, opt := range options {
if err := opt(cfg); err != nil {
return nil, err
}
}
if cfg.dialContext == nil {
cfg.dialContext = dialFromPath(api.DaemonSocketPath())
}
c := &http.Client{
Transport: &http.Transport{
// re-use the same connection to the runtime, this speeds up subsequent
// calls.
MaxConnsPerHost: api.DefaultClientMaxConnsPerHost,
MaxIdleConnsPerHost: api.DefaultClientMaxIdleConnsPerHost,
// keep the connection alive (good for long-lived clients)
IdleConnTimeout: api.DefaultClientIdleConnTimeout,
// By default it is 1 second, but can be overridden with [WithResponseTimeout]
ResponseHeaderTimeout: cfg.responseTimeout,
TLSHandshakeTimeout: api.DefaultClientTLSHandshakeTimeout,
DialContext: cfg.dialContext,
DisableKeepAlives: false,
DisableCompression: false,
ForceAttemptHTTP2: true,
},
// by default Timeout will be 0 (meaning no timeout)
// it can be overwritten with [WithTimeout]
Timeout: cfg.requestTimeout,
}
return &client{
resolverClient: resolver.NewResolverClient(c),
listClient: resolverv1connect.NewListServiceClient(c, "http://unix"),
versionClient: healthv1connect.NewVersionServiceClient(c, "http://unix"),
}, nil
}
func (c client) ListPlugins(ctx context.Context) ([]PluginInfo, error) {
req := connect.NewRequest(v1.ListPluginsRequest_builder{}.Build())
resp, err := c.listClient.ListPlugins(ctx, req)
if isDialError(err) {
return nil, fmt.Errorf("%w: %w", ErrSecretsEngineNotAvailable, err)
}
if err != nil {
return nil, err
}
var result []PluginInfo
for _, item := range resp.Msg.GetPlugins() {
name, err := api.NewName(item.GetName())
if err != nil {
continue
}
version, err := api.NewVersion(item.GetVersion())
if err != nil {
continue
}
pattern, err := secrets.ParsePattern(item.GetPattern())
if err != nil {
continue
}
result = append(result, PluginInfo{
Name: name,
Version: version,
Pattern: pattern,
External: item.GetExternal(),
})
}
return result, nil
}
type PluginInfo struct {
Name api.Name
Version api.Version
Pattern secrets.Pattern
External bool
}
func dialFromPath(path string) dial {
return func(ctx context.Context, _, _ string) (net.Conn, error) {
d := &net.Dialer{}
return d.DialContext(ctx, "unix", path)
}
}