-
Notifications
You must be signed in to change notification settings - Fork 350
Expand file tree
/
Copy pathauth.go
More file actions
587 lines (535 loc) · 19.7 KB
/
Copy pathauth.go
File metadata and controls
587 lines (535 loc) · 19.7 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
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
package bedrock
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/openai/openai-go/v3/internal/requestconfig"
"github.com/openai/openai-go/v3/option"
)
const (
bedrockService = "bedrock-mantle"
bedrockRuntimeService = "bedrock"
missingRegionMessage = "bedrock: an AWS region is required; pass `AWSRegion` in `bedrock.Config`, or set `AWS_REGION` or `AWS_DEFAULT_REGION`"
missingCredentialsMessage = "bedrock: credentials not found; pass a bearer credential or AWS credentials in `bedrock.Config`, set `AWS_BEARER_TOKEN_BEDROCK`, or configure the default AWS credential chain"
credentialResolutionMessage = "bedrock: failed to resolve AWS credentials; verify your AWS profile, environment variables, or runtime identity configuration and try again"
nonReplayableBodyMessage = "bedrock: SigV4 authentication requires a replayable request body; buffer the body before sending or use bearer authentication"
)
var awsRegionPattern = regexp.MustCompile(`^[a-z]{2,8}(?:-[a-z0-9]+)+-[0-9]+$`)
type authMode int
const (
authModeUnset authMode = iota
authModeSkip
authModeBearer
authModeSigV4
)
type resolvedConfig struct {
mode authMode
endpoint Endpoint
region string
baseURL *url.URL
middleware option.Middleware
}
type safeError struct {
message string
cause error
}
func (e *safeError) Error() string { return e.message }
func (e *safeError) Unwrap() error { return e.cause }
func newClientOptions(
ctx context.Context,
cfg Config,
now func() time.Time,
userOpts ...option.RequestOption,
) ([]option.RequestOption, error) {
if ctx == nil {
return nil, errors.New("bedrock: nil context")
}
if err := requestconfig.ValidateEndpointOptions("Bedrock", userOpts...); err != nil {
return nil, err
}
resolved, err := resolveConfig(ctx, cfg, now)
if err != nil {
return nil, err
}
opts := []option.RequestOption{
requestconfig.WithEnvironmentDefaultsDisabled(),
requestconfig.WithEndpointProvider("Bedrock"),
option.WithBaseURL(resolved.baseURL.String()),
}
opts = append(opts, userOpts...)
opts = append(opts, requestconfig.WithRequestFinalizer(func(rc *requestconfig.RequestConfig) error {
if resolved.mode != authModeSkip && (rc.APIKey != "" || rc.AdminAPIKey != "") {
return errors.New("bedrock: provider authentication cannot be combined with an OpenAI API key; configure authentication in `bedrock.Config`")
}
if !sameBaseURL(rc.BaseURL, resolved.baseURL) {
return errors.New("bedrock: provider routing cannot be overridden with `option.WithBaseURL`; configure `BaseURL` in `bedrock.Config`")
}
if resolved.mode == authModeBearer || resolved.mode == authModeSigV4 {
if rc.CustomHTTPDoer != nil {
return errors.New("bedrock: authenticated requests require an *http.Client; custom HTTP doers cannot guarantee redirect safety")
}
if rc.HTTPClient == nil {
return errors.New("bedrock: authenticated requests require a non-nil *http.Client")
}
client := *rc.HTTPClient
client.CheckRedirect = func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
}
rc.HTTPClient = &client
}
if resolved.middleware != nil {
return option.WithMiddleware(resolved.middleware).Apply(rc)
}
return nil
}))
return opts, nil
}
func resolveConfig(ctx context.Context, cfg Config, now func() time.Time) (resolvedConfig, error) {
mode, tokenProvider, explicitAWS, err := resolveAuthMode(cfg)
if err != nil {
return resolvedConfig{}, err
}
region, err := resolveOptionalConfigValue("AWSRegion", cfg.AWSRegion, "AWS_REGION", "AWS_DEFAULT_REGION")
if err != nil {
return resolvedConfig{}, err
}
if regionErr := validateAWSRegion(region); regionErr != nil {
return resolvedConfig{}, regionErr
}
baseURLValue, err := resolveOptionalConfigValue("BaseURL", cfg.BaseURL, "AWS_BEDROCK_BASE_URL")
if err != nil {
return resolvedConfig{}, err
}
baseURL, err := parseBaseURL(baseURLValue)
if err != nil {
return resolvedConfig{}, err
}
endpoint, err := resolveEndpoint(cfg.Endpoint, baseURL)
if err != nil {
return resolvedConfig{}, err
}
if baseURL != nil {
region, err = reconcileEndpointRegion(baseURL, region)
if err != nil {
return resolvedConfig{}, err
}
if regionErr := validateAWSRegion(region); regionErr != nil {
return resolvedConfig{}, regionErr
}
}
resolved := resolvedConfig{mode: mode, endpoint: endpoint, region: region, baseURL: baseURL}
var awsCfg aws.Config
switch mode {
case authModeSkip:
case authModeBearer:
case authModeSigV4:
awsCfg, err = loadAWSConfig(ctx, cfg, region)
if err != nil {
return resolvedConfig{}, err
}
if region == "" {
region = strings.TrimSpace(awsCfg.Region)
}
if region == "" {
return resolvedConfig{}, errors.New(missingRegionMessage)
}
if regionErr := validateAWSRegion(region); regionErr != nil {
return resolvedConfig{}, regionErr
}
if baseURL != nil {
if _, endpointErr := reconcileEndpointRegion(baseURL, region); endpointErr != nil {
return resolvedConfig{}, endpointErr
}
}
awsCfg.Region = region
if credentialErr := verifyAWSCredentials(ctx, awsCfg, explicitAWS); credentialErr != nil {
return resolvedConfig{}, credentialErr
}
resolved.region = region
default:
return resolvedConfig{}, errors.New("bedrock: invalid authentication mode")
}
if resolved.baseURL == nil {
if region == "" {
return resolvedConfig{}, errors.New(missingRegionMessage)
}
resolved.baseURL, err = parseBaseURL(defaultEndpointURL(endpoint, region))
if err != nil {
return resolvedConfig{}, err
}
}
resolved.baseURL = normalizeBaseURL(resolved.baseURL)
if mode == authModeBearer {
resolved.middleware = bearerMiddleware(resolved.baseURL, tokenProvider)
}
if mode == authModeSigV4 {
resolved.middleware = endpointSigV4Middleware(resolved.baseURL, awsCfg, v4.NewSigner(), now, endpoint)
}
return resolved, nil
}
func resolveAuthMode(cfg Config) (authMode, TokenProvider, bool, error) {
if cfg.APIKey != "" && strings.TrimSpace(cfg.APIKey) == "" {
return authModeUnset, nil, false, errors.New("bedrock: bearer credential must not be empty")
}
if cfg.APIKey != "" && cfg.BedrockTokenProvider != nil {
return authModeUnset, nil, false, errors.New("bedrock: `APIKey` and `BedrockTokenProvider` are mutually exclusive; configure only one")
}
hasAccessKey := cfg.AWSAccessKeyID != ""
hasSecretKey := cfg.AWSSecretAccessKey != ""
hasSessionToken := cfg.AWSSessionToken != ""
if hasAccessKey != hasSecretKey || (hasSessionToken && !hasAccessKey) {
return authModeUnset, nil, false, errors.New("bedrock: static AWS credentials require both `AWSAccessKeyID` and `AWSSecretAccessKey`; `AWSSessionToken` may only be used with both")
}
if hasAccessKey && (strings.TrimSpace(cfg.AWSAccessKeyID) == "" || strings.TrimSpace(cfg.AWSSecretAccessKey) == "") {
return authModeUnset, nil, false, errors.New("bedrock: static AWS credentials require non-empty `AWSAccessKeyID` and `AWSSecretAccessKey` values")
}
if hasSessionToken && strings.TrimSpace(cfg.AWSSessionToken) == "" {
return authModeUnset, nil, false, errors.New("bedrock: static AWS `AWSSessionToken` must not be empty when provided")
}
profile := strings.TrimSpace(cfg.AWSProfile)
if cfg.AWSProfile != "" && profile == "" {
return authModeUnset, nil, false, errors.New("bedrock: AWS `AWSProfile` must not be empty")
}
awsModes := 0
if hasAccessKey {
awsModes++
}
if profile != "" {
awsModes++
}
if cfg.AWSCredentialsProvider != nil {
awsModes++
}
if awsModes > 1 {
return authModeUnset, nil, false, errors.New("bedrock: authentication is ambiguous; configure exactly one explicit AWS mode: static credentials, profile, or credentials provider")
}
hasBearer := cfg.APIKey != "" || cfg.BedrockTokenProvider != nil
if hasBearer && awsModes != 0 {
return authModeUnset, nil, false, errors.New("bedrock: bearer and AWS credential authentication are mutually exclusive; configure exactly one explicit mode: bearer credential, static AWS credentials, profile, or credentials provider")
}
if cfg.SkipAuth && (hasBearer || awsModes != 0) {
return authModeUnset, nil, false, errors.New("bedrock: `SkipAuth` cannot be combined with explicit authentication options")
}
if cfg.SkipAuth {
return authModeSkip, nil, false, nil
}
if cfg.BedrockTokenProvider != nil {
return authModeBearer, cfg.BedrockTokenProvider, false, nil
}
if cfg.APIKey != "" {
token := strings.TrimSpace(cfg.APIKey)
return authModeBearer, func(context.Context) (string, error) { return token, nil }, false, nil
}
if awsModes != 0 {
return authModeSigV4, nil, true, nil
}
if strings.TrimSpace(os.Getenv("AWS_BEARER_TOKEN_BEDROCK")) != "" {
return authModeBearer, func(context.Context) (string, error) {
token := strings.TrimSpace(os.Getenv("AWS_BEARER_TOKEN_BEDROCK"))
if token == "" {
return "", errors.New(missingCredentialsMessage)
}
return token, nil
}, false, nil
}
return authModeSigV4, nil, false, nil
}
func resolveOptionalConfigValue(name string, explicit string, environment ...string) (string, error) {
if explicit != "" {
value := strings.TrimSpace(explicit)
if value == "" {
return "", fmt.Errorf("bedrock: `%s` must not be empty", name)
}
return value, nil
}
for _, envName := range environment {
if value := strings.TrimSpace(os.Getenv(envName)); value != "" {
return value, nil
}
}
return "", nil
}
func validateAWSRegion(region string) error {
if region != "" && !awsRegionPattern.MatchString(region) {
return fmt.Errorf("bedrock: invalid AWS region %q", region)
}
return nil
}
func parseBaseURL(value string) (*url.URL, error) {
if value == "" {
return nil, nil
}
parsed, err := url.Parse(value)
if err != nil || parsed.Scheme == "" || parsed.Host == "" || parsed.User != nil {
return nil, errors.New("bedrock: `BaseURL` must be an absolute HTTP or HTTPS URL without user information")
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return nil, errors.New("bedrock: `BaseURL` must use HTTP or HTTPS")
}
return normalizeBaseURL(parsed), nil
}
func normalizeBaseURL(value *url.URL) *url.URL {
if value == nil {
return nil
}
copy := *value
if copy.Path == "" {
copy.Path = "/"
} else if !strings.HasSuffix(copy.Path, "/") {
copy.Path += "/"
}
return ©
}
func resolveEndpoint(endpoint Endpoint, baseURL *url.URL) (Endpoint, error) {
if endpoint != "" && endpoint != EndpointMantle && endpoint != EndpointRuntime {
return "", errors.New("bedrock: `Endpoint` must be `EndpointMantle` or `EndpointRuntime`")
}
if baseURL != nil {
canonicalEndpoint, _, canonical := parseBedrockEndpointHostname(baseURL.Hostname())
if canonical {
if !strings.EqualFold(baseURL.Scheme, "https") {
return "", errors.New("bedrock: canonical AWS endpoints require HTTPS")
}
if endpoint != "" && endpoint != canonicalEndpoint {
return "", fmt.Errorf("bedrock: %s hostname does not match the selected %s endpoint", canonicalEndpoint, endpoint)
}
if endpoint == "" {
endpoint = canonicalEndpoint
}
}
}
if endpoint == "" {
return EndpointMantle, nil
}
return endpoint, nil
}
func defaultEndpointURL(endpoint Endpoint, region string) string {
if endpoint == EndpointRuntime {
standardSuffix, _ := runtimeDNSSuffixes(region)
return fmt.Sprintf("https://bedrock-runtime.%s.%s/openai/v1/", region, standardSuffix)
}
return fmt.Sprintf("https://bedrock-mantle.%s.api.aws/v1/", region)
}
func runtimeDNSSuffixes(region string) (standard string, dualStack string) {
switch {
case strings.HasPrefix(region, "cn-"):
return "amazonaws.com.cn", "api.amazonwebservices.com.cn"
case strings.HasPrefix(region, "eusc-"):
return "amazonaws.eu", "api.amazonwebservices.eu"
case strings.HasPrefix(region, "us-iso-"):
return "c2s.ic.gov", "api.aws.ic.gov"
case strings.HasPrefix(region, "us-isob-"):
return "sc2s.sgov.gov", "api.aws.scloud"
case strings.HasPrefix(region, "eu-isoe-"):
return "cloud.adc-e.uk", "api.cloud-aws.adc-e.uk"
case strings.HasPrefix(region, "us-isof-"):
return "csp.hci.ic.gov", "api.aws.hci.ic.gov"
default:
return "amazonaws.com", "api.aws"
}
}
func parseBedrockEndpointHostname(hostname string) (Endpoint, string, bool) {
parts := strings.Split(strings.ToLower(strings.TrimSuffix(hostname, ".")), ".")
if len(parts) < 3 {
return "", "", false
}
service, region, suffix := parts[0], parts[1], strings.Join(parts[2:], ".")
if service == "bedrock-mantle" && region != "" && suffix == "api.aws" {
return EndpointMantle, region, true
}
if (service == "bedrock-runtime" || service == "bedrock-runtime-fips") && region != "" {
standard, dualStack := runtimeDNSSuffixes(region)
if suffix == standard || suffix == dualStack {
return EndpointRuntime, region, true
}
}
return "", "", false
}
func reconcileEndpointRegion(baseURL *url.URL, region string) (string, error) {
_, endpointRegion, canonical := parseBedrockEndpointHostname(baseURL.Hostname())
if !canonical {
return region, nil
}
if region != "" && !strings.EqualFold(endpointRegion, region) {
return "", fmt.Errorf("bedrock: endpoint region %q does not match SigV4 region %q", endpointRegion, region)
}
if region == "" {
return endpointRegion, nil
}
return region, nil
}
func loadAWSConfig(ctx context.Context, cfg Config, region string) (aws.Config, error) {
explicitProvider := explicitAWSCredentialsProvider(cfg)
if explicitProvider != nil && region != "" {
return aws.Config{
Region: region,
Credentials: aws.NewCredentialsCache(explicitProvider),
}, nil
}
loadOptions := make([]func(*awsconfig.LoadOptions) error, 0, 3)
if region != "" {
loadOptions = append(loadOptions, awsconfig.WithRegion(region))
}
if profile := strings.TrimSpace(cfg.AWSProfile); profile != "" {
loadOptions = append(loadOptions, awsconfig.WithSharedConfigProfile(profile))
}
if explicitProvider != nil {
loadOptions = append(loadOptions, awsconfig.WithCredentialsProvider(explicitProvider))
}
awsCfg, err := awsconfig.LoadDefaultConfig(ctx, loadOptions...)
if err != nil {
return aws.Config{}, &safeError{message: credentialResolutionMessage, cause: err}
}
if awsCfg.Credentials == nil {
return aws.Config{}, errors.New(missingCredentialsMessage)
}
if _, ok := awsCfg.Credentials.(*aws.CredentialsCache); !ok {
awsCfg.Credentials = aws.NewCredentialsCache(awsCfg.Credentials)
}
return awsCfg, nil
}
func explicitAWSCredentialsProvider(cfg Config) aws.CredentialsProvider {
if cfg.AWSAccessKeyID != "" {
credentials := aws.Credentials{
AccessKeyID: strings.TrimSpace(cfg.AWSAccessKeyID),
SecretAccessKey: strings.TrimSpace(cfg.AWSSecretAccessKey),
SessionToken: strings.TrimSpace(cfg.AWSSessionToken),
Source: "bedrock.Config",
}
return aws.CredentialsProviderFunc(func(context.Context) (aws.Credentials, error) {
return credentials, nil
})
}
return cfg.AWSCredentialsProvider
}
func verifyAWSCredentials(ctx context.Context, awsCfg aws.Config, explicitAWS bool) error {
if _, err := awsCfg.Credentials.Retrieve(ctx); err != nil {
message := credentialResolutionMessage
if !explicitAWS {
message = missingCredentialsMessage
}
return &safeError{message: message, cause: err}
}
return nil
}
func bearerMiddleware(baseURL *url.URL, provider TokenProvider) option.Middleware {
return func(req *http.Request, next option.MiddlewareNext) (*http.Response, error) {
if err := validateProviderRequest(req, baseURL); err != nil {
return nil, requestconfig.WithNoRetryError(err)
}
if req.Header.Get("Authorization") != "" {
return nil, requestconfig.WithNoRetryError(errors.New("bedrock: provider authentication cannot be combined with a custom `Authorization` header"))
}
token, err := provider(req.Context())
if err != nil {
return nil, &safeError{message: "bedrock: failed to resolve a bearer credential", cause: err}
}
token = strings.TrimSpace(token)
if token == "" {
return nil, requestconfig.WithNoRetryError(errors.New("bedrock: bearer credential provider must return a non-empty string"))
}
req.Header.Set("Authorization", "Bearer "+token)
return next(req)
}
}
type httpSigner interface {
SignHTTP(context.Context, aws.Credentials, *http.Request, string, string, string, time.Time, ...func(*v4.SignerOptions)) error
}
func sigV4Middleware(baseURL *url.URL, cfg aws.Config, signer httpSigner, now func() time.Time) option.Middleware {
return endpointSigV4Middleware(baseURL, cfg, signer, now, EndpointMantle)
}
func endpointSigV4Middleware(baseURL *url.URL, cfg aws.Config, signer httpSigner, now func() time.Time, endpoint Endpoint) option.Middleware {
service := bedrockService
if endpoint == EndpointRuntime {
service = bedrockRuntimeService
}
return func(req *http.Request, next option.MiddlewareNext) (*http.Response, error) {
if err := validateProviderRequest(req, baseURL); err != nil {
return nil, requestconfig.WithNoRetryError(err)
}
if req.Header.Get("Authorization") != "" {
return nil, requestconfig.WithNoRetryError(errors.New("bedrock: provider authentication cannot be combined with a custom `Authorization` header"))
}
if _, err := reconcileEndpointRegion(req.URL, cfg.Region); err != nil {
return nil, requestconfig.WithNoRetryError(err)
}
body, err := materializeReplayableBody(req)
if err != nil {
return nil, requestconfig.WithNoRetryError(err)
}
credentials, err := cfg.Credentials.Retrieve(req.Context())
if err != nil {
return nil, &safeError{message: credentialResolutionMessage, cause: err}
}
if strings.TrimSpace(credentials.AccessKeyID) == "" || strings.TrimSpace(credentials.SecretAccessKey) == "" {
return nil, requestconfig.WithNoRetryError(errors.New(credentialResolutionMessage))
}
req.Method = strings.ToUpper(req.Method)
req.Header.Del("X-Amz-Date")
req.Header.Del("X-Amz-Security-Token")
req.Header.Del("X-Amz-Content-Sha256")
payloadHash := sha256.Sum256(body)
encodedHash := hex.EncodeToString(payloadHash[:])
req.Header.Set("X-Amz-Content-Sha256", encodedHash)
// Content-Length is transmitted by net/http but does not need to be part of
// SigV4's signed-header set. Temporarily hide it from the AWS signer so the
// signature matches the shared cross-SDK fixture, then restore the exact
// wire length before the request is sent.
contentLength := req.ContentLength
req.ContentLength = -1
signErr := signer.SignHTTP(req.Context(), credentials, req, encodedHash, service, cfg.Region, now().UTC())
req.ContentLength = contentLength
if signErr != nil {
return nil, &safeError{message: "bedrock: failed to sign request", cause: signErr}
}
return next(req)
}
}
func materializeReplayableBody(req *http.Request) ([]byte, error) {
if req.Body == nil {
return nil, nil
}
if req.GetBody == nil {
return nil, errors.New(nonReplayableBodyMessage)
}
body, readErr := io.ReadAll(req.Body)
closeErr := req.Body.Close()
if readErr != nil {
return nil, &safeError{message: nonReplayableBodyMessage, cause: readErr}
}
if closeErr != nil {
return nil, &safeError{message: nonReplayableBodyMessage, cause: closeErr}
}
body = bytes.Clone(body)
req.Body = io.NopCloser(bytes.NewReader(body))
req.GetBody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(body)), nil
}
req.ContentLength = int64(len(body))
return body, nil
}
func validateProviderRequest(req *http.Request, baseURL *url.URL) error {
if !requestconfig.RequestHasOrigin(req, baseURL) {
return errors.New("bedrock: provider authentication cannot send credentials to an origin other than the configured provider URL")
}
return nil
}
func sameBaseURL(left, right *url.URL) bool {
if left == nil || right == nil {
return left == right
}
return normalizeBaseURL(left).String() == normalizeBaseURL(right).String()
}