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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package openbao
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
api "github.com/openbao/openbao/api/v2"
"github.com/johnandersen777/socialweb-computer-kcp/internal/contract/vault"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/lease"
)
var (
ErrNotFound = vault.ErrNotFound
ErrUnauthorized = errors.New("openbao: the token is not accepted (HTTP 401)")
ErrForbidden = errors.New("openbao: denied by policy (HTTP 403)")
ErrTransport = errors.New("openbao: transport failure")
ErrNoCA = errors.New("openbao: the supplied CA carries no CERTIFICATE PEM block")
ErrBodyTooLarge = errors.New("openbao: the response body is too large")
)
const (
IdleConnTimeout = 90 * time.Second
maxBody = 32 << 20
)
type ResponseError struct {
Method string
Path string
Status int
Body string
}
func (e *ResponseError) Error() string {
return fmt.Sprintf("openbao: %s /v1/%s -> HTTP %d: %s", e.Method, e.Path, e.Status, e.Body)
}
func (e *ResponseError) HTTPStatus() int { return e.Status }
func (e *ResponseError) Is(target error) bool {
switch e.Status {
case http.StatusNotFound:
return target == ErrNotFound
case http.StatusUnauthorized:
return target == ErrUnauthorized
case http.StatusForbidden:
return target == ErrForbidden
default:
return false
}
}
func IsAuthError(err error) bool {
var re *ResponseError
return errors.As(err, &re) && (re.Status == http.StatusUnauthorized || re.Status == http.StatusForbidden)
}
type tokenSource interface {
Get(ctx context.Context) (string, error)
Invalidate()
}
type staticToken string
func (t staticToken) Get(context.Context) (string, error) { return string(t), nil }
func (staticToken) Invalidate() {}
type Client struct {
addr string
http *http.Client
tls *tls.Config
timeout time.Duration
api *api.Client
token tokenSource
renews bool
err error
}
type Option func(*Client)
func CertPoolFromPEM(caPEM []byte) (*x509.CertPool, error) {
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(caPEM) {
return nil, ErrNoCA
}
return pool, nil
}
// ponytail: one trust root per client, no system pool; a caller that needs the public roots too can fold them in before WithCACertPool.
func WithCACertPool(pool *x509.CertPool) Option {
return func(c *Client) {
c.tlsConfig().RootCAs = pool
}
}
func WithClientCertificate(cert tls.Certificate) Option {
return func(c *Client) {
c.tlsConfig().Certificates = []tls.Certificate{cert}
}
}
func WithHTTPClient(client *http.Client) Option {
return func(c *Client) {
if client != nil {
c.http = client
}
}
}
func WithTimeout(timeout time.Duration) Option {
return func(c *Client) {
c.timeout = timeout
}
}
func (c *Client) tlsConfig() *tls.Config {
if c.tls == nil {
c.tls = &tls.Config{MinVersion: tls.VersionTLS12}
c.http = &http.Client{Transport: &http.Transport{TLSClientConfig: c.tls, IdleConnTimeout: IdleConnTimeout}}
}
return c.tls
}
func New(addr, token string, opts ...Option) *Client {
c := &Client{addr: strings.TrimRight(strings.TrimSpace(addr), "/"), http: http.DefaultClient, token: staticToken(token)}
for _, o := range opts {
o(c)
}
c.api, c.err = newAPI(c.addr, c.http, c.timeout)
return c
}
func newAPI(addr string, hc *http.Client, timeout time.Duration) (*api.Client, error) {
own := *hc
if own.Transport == nil {
own.Transport = http.DefaultTransport
}
hc = &own
client, err := api.NewClient(&api.Config{Address: addr, HttpClient: hc, MaxRetries: 0, Timeout: timeout})
if err != nil {
return nil, fmt.Errorf("%w: the client for %s: %v", ErrTransport, addr, err)
}
client.ClearToken()
client.ClearNamespace()
return client, nil
}
func (c *Client) with(token tokenSource, renews bool) *Client {
return &Client{addr: c.addr, http: c.http, tls: c.tls, timeout: c.timeout, api: c.api, err: c.err, token: token, renews: renews}
}
func (c *Client) anonymous() *Client {
return c.with(staticToken(""), false)
}
func (c *Client) WithToken(token string) *Client {
return c.with(staticToken(token), false)
}
func (c *Client) Address() string { return c.addr }
func leaseUntil(lease time.Duration) time.Time {
if lease <= 0 {
return time.Time{}
}
return time.Now().Add(lease)
}
func (c *Client) leased(ctx context.Context, login func(context.Context) (loginAuth, error)) (*Client, error) {
src := lease.New(func(ctx context.Context) (string, time.Time, error) {
auth, err := login(ctx)
if err != nil {
return "", time.Time{}, err
}
return auth.token, leaseUntil(auth.lease), nil
})
if _, err := src.Get(ctx); err != nil {
return nil, err
}
return c.with(src, true), nil
}
func (c *Client) LoginCert(ctx context.Context, mount, role string) (*Client, error) {
path := "auth/" + strings.Trim(mount, "/") + "/login"
anonymous := c.anonymous()
return c.leased(ctx, func(ctx context.Context) (loginAuth, error) {
return anonymous.login(ctx, path, map[string]any{"name": role})
})
}
func (c *Client) LoginAppRole(ctx context.Context, mount, roleID, secretID string) (*Client, error) {
if mount = strings.Trim(mount, "/"); mount == "" {
mount = "approle"
}
path := "auth/" + mount + "/login"
anonymous := c.anonymous()
return c.leased(ctx, func(ctx context.Context) (loginAuth, error) {
return anonymous.login(ctx, path, map[string]any{"role_id": roleID, "secret_id": secretID})
})
}
func (c *Client) LoginJWT(ctx context.Context, mount, role, jwt string) (*Client, error) {
auth, err := c.anonymous().login(ctx, "auth/"+strings.Trim(mount, "/")+"/login", map[string]any{"role": role, "jwt": jwt})
if err != nil {
return nil, err
}
return c.WithToken(auth.token), nil
}
type loginAuth struct {
token string
accessor string
lease time.Duration
renewable bool
}
func (c *Client) login(ctx context.Context, path string, body map[string]any) (loginAuth, error) {
status, raw, err := c.send(ctx, http.MethodPost, path, body, "")
if err != nil {
return loginAuth{}, err
}
if status < 200 || status > 299 {
return loginAuth{}, &ResponseError{Method: http.MethodPost, Path: path, Status: status, Body: strings.TrimSpace(string(raw))}
}
return decodeAuth(path, raw, true)
}
func decodeAuth(path string, raw []byte, needToken bool) (loginAuth, error) {
var payload struct {
Auth struct {
ClientToken string `json:"client_token"`
Accessor string `json:"accessor"`
LeaseDuration int64 `json:"lease_duration"`
Renewable bool `json:"renewable"`
} `json:"auth"`
}
if err := json.Unmarshal(raw, &payload); err != nil {
return loginAuth{}, fmt.Errorf("openbao: %s returned a body that is not JSON: %v", path, err)
}
if needToken && payload.Auth.ClientToken == "" {
return loginAuth{}, fmt.Errorf("openbao: %s answered without a client token", path)
}
return loginAuth{token: payload.Auth.ClientToken, accessor: payload.Auth.Accessor,
lease: time.Duration(payload.Auth.LeaseDuration) * time.Second, renewable: payload.Auth.Renewable}, nil
}
func (c *Client) RevokeSelf(ctx context.Context) error {
_, err := c.topLevel(ctx, http.MethodPost, "auth/token/revoke-self", nil)
c.token.Invalidate()
return err
}
func (c *Client) do(ctx context.Context, method, path string, in any) (json.RawMessage, error) {
status, body, err := c.request(ctx, method, path, in)
if err != nil {
return nil, err
}
if status < 200 || status > 299 {
return nil, &ResponseError{Method: method, Path: path, Status: status, Body: strings.TrimSpace(string(body))}
}
if len(bytes.TrimSpace(body)) == 0 {
return nil, nil
}
var envelope struct {
Data json.RawMessage `json:"data"`
}
if err := json.Unmarshal(body, &envelope); err != nil {
return nil, fmt.Errorf("openbao: %s /v1/%s returned a body that is not JSON: %v (%s)", method, path, err, strings.TrimSpace(string(body)))
}
return envelope.Data, nil
}
func (c *Client) topLevel(ctx context.Context, method, path string, in any) (json.RawMessage, error) {
status, body, err := c.request(ctx, method, path, in)
if err != nil {
return nil, err
}
if status < 200 || status > 299 {
return nil, &ResponseError{Method: method, Path: path, Status: status, Body: strings.TrimSpace(string(body))}
}
return json.RawMessage(bytes.TrimSpace(body)), nil
}
func (c *Client) request(ctx context.Context, method, path string, in any) (int, []byte, error) {
token, err := c.token.Get(ctx)
if err != nil {
return 0, nil, fmt.Errorf("%w: the token for %s /v1/%s: %v", ErrTransport, method, path, err)
}
status, body, err := c.send(ctx, method, path, in, token)
if err != nil || !c.renews || (status != http.StatusUnauthorized && status != http.StatusForbidden) {
return status, body, err
}
c.token.Invalidate()
fresh, ferr := c.token.Get(ctx)
if ferr != nil || fresh == token {
return status, body, nil
}
return c.send(ctx, method, path, in, fresh)
}
func (c *Client) send(ctx context.Context, method, path string, in any, token string) (int, []byte, error) {
if c.err != nil {
return 0, nil, c.err
}
clean, query, _ := strings.Cut(strings.TrimPrefix(path, "/"), "?")
r := c.api.NewRequest(method, "/v1/"+clean)
r.ClientToken = token
r.WrapTTL = ""
if query != "" {
values, err := url.ParseQuery(query)
if err != nil {
return 0, nil, fmt.Errorf("%w: the query of %s /v1/%s: %v", ErrTransport, method, path, err)
}
r.Params = values
}
if in != nil {
if err := r.SetJSONBody(in); err != nil {
return 0, nil, fmt.Errorf("%w: encode %s /v1/%s: %v", ErrTransport, method, path, err)
}
}
resp, err := c.api.RawRequestWithContext(ctx, r)
if resp == nil || resp.Response == nil {
if err == nil {
err = errors.New("no response")
}
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return 0, nil, err
}
return 0, nil, fmt.Errorf("%w: %s /v1/%s: %v", ErrTransport, method, path, err)
}
defer resp.Body.Close()
body, rerr := io.ReadAll(io.LimitReader(resp.Body, maxBody+1))
if rerr != nil {
return 0, nil, fmt.Errorf("%w: reading %s /v1/%s: %v", ErrTransport, method, path, rerr)
}
if len(body) > maxBody {
return resp.StatusCode, nil, fmt.Errorf("%w: %s /v1/%s answered more than %d bytes", ErrBodyTooLarge, method, path, maxBody)
}
return resp.StatusCode, body, nil
}
func (c *Client) Raw(ctx context.Context, method, path string, body any) (int, []byte, error) {
return c.request(ctx, method, path, body)
}