carlos / platform Public

domains: the zone host uses its own AWS credentials, never the box role

Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 210826f9d47eb09e0831eabd3e3c8f2e89ecf4e0 parent 5394c7f
7 files changed, +314 −25
  • cmd/console/domains.go +6 −2
  • cmd/console/domains_test.go +17 −10
  • docs/site/domains-buying.md +53 −12
  • internal/rootaws/config.go +23 −0
  • internal/rootaws/config_test.go +123 −0
  • internal/zonehost/route53zones/route53.go +12 −1
  • internal/zonehost/route53zones/route53_test.go +80 −0
diff --git a/cmd/console/domains.go b/cmd/console/domains.go
index 38cd34294..60983ea73 100644
--- a/cmd/console/domains.go
+++ b/cmd/console/domains.go
@@ -30,6 +30,8 @@ func domainBackends(
"CARLOS_OPENPROVIDER_USERNAME",
"CARLOS_OPENPROVIDER_PASSWORD",
"CARLOS_DOMAIN_DELEGATION_SET_ID",
+ "CARLOS_DOMAIN_AWS_ACCESS_KEY_ID",
+ "CARLOS_DOMAIN_AWS_SECRET_ACCESS_KEY",
"CARLOS_DOMAIN_NAMESERVERS",
"CARLOS_DOMAIN_CATALOG",
} {
@@ -37,7 +39,7 @@ func domainBackends(
if strings.TrimSpace(value) == "" {
missing = append(missing, name)
}
- if name != "CARLOS_OPENPROVIDER_PASSWORD" {
+ if name != "CARLOS_OPENPROVIDER_PASSWORD" && name != "CARLOS_DOMAIN_AWS_SECRET_ACCESS_KEY" {
value = strings.TrimSpace(value)
}
values[name] = value
@@ -64,6 +66,8 @@ func domainBackends(
nameservers[i] = strings.TrimSpace(nameservers[i])
}
cfg := route53zones.Config{
+ AccessKeyID: values["CARLOS_DOMAIN_AWS_ACCESS_KEY_ID"],
+ SecretAccessKey: values["CARLOS_DOMAIN_AWS_SECRET_ACCESS_KEY"],
DelegationSetID: values["CARLOS_DOMAIN_DELEGATION_SET_ID"],
Nameservers: nameservers,
SteeringHost: steeringHost(),
@@ -73,7 +77,7 @@ func domainBackends(
}
z, err := newZones(context.Background(), cfg)
if err != nil || z == nil {
- log.Print("console: cannot construct domain zone host; check CARLOS_DOMAIN_DELEGATION_SET_ID, CARLOS_DOMAIN_NAMESERVERS and AWS configuration")
+ log.Print("console: cannot construct domain zone host; check CARLOS_DOMAIN_DELEGATION_SET_ID, CARLOS_DOMAIN_NAMESERVERS, CARLOS_DOMAIN_AWS_ACCESS_KEY_ID, CARLOS_DOMAIN_AWS_SECRET_ACCESS_KEY and AWS configuration")
return nil, nil, nil, nil, nil
}
var apex zonehost.ApexSource
diff --git a/cmd/console/domains_test.go b/cmd/console/domains_test.go
index 70e09e37e..251b6859c 100644
--- a/cmd/console/domains_test.go
+++ b/cmd/console/domains_test.go
@@ -19,12 +19,14 @@ import (
func domainTestEnv() map[string]string {
return map[string]string{
- "CARLOS_OPENPROVIDER_URL": "https://registrar.example/v1",
- "CARLOS_OPENPROVIDER_USERNAME": "operator-test-user",
- "CARLOS_OPENPROVIDER_PASSWORD": " secret-test-password ",
- "CARLOS_DOMAIN_DELEGATION_SET_ID": "NTEST123",
- "CARLOS_DOMAIN_NAMESERVERS": "ns1.dns.example, ns2.dns.example,ns3.dns.example,ns4.dns.example",
- "CARLOS_DOMAIN_CATALOG": "../../internal/domainreg/testdata/catalog.json",
+ "CARLOS_OPENPROVIDER_URL": "https://registrar.example/v1",
+ "CARLOS_OPENPROVIDER_USERNAME": "operator-test-user",
+ "CARLOS_OPENPROVIDER_PASSWORD": " secret-test-password ",
+ "CARLOS_DOMAIN_DELEGATION_SET_ID": "NTEST123",
+ "CARLOS_DOMAIN_AWS_ACCESS_KEY_ID": "ZONE_TEST_ACCESS",
+ "CARLOS_DOMAIN_AWS_SECRET_ACCESS_KEY": " zone-test-secret/+== ",
+ "CARLOS_DOMAIN_NAMESERVERS": "ns1.dns.example, ns2.dns.example,ns3.dns.example,ns4.dns.example",
+ "CARLOS_DOMAIN_CATALOG": "../../internal/domainreg/testdata/catalog.json",
}
}
@@ -114,6 +116,9 @@ func TestDomainBackendsSteeredWhenSteeringOn(t *testing.T) {
return wantR, nil
}, func(ctx context.Context, cfg route53zones.Config) (*route53zones.Host, error) {
zoneCalls++
+ if cfg.AccessKeyID != env["CARLOS_DOMAIN_AWS_ACCESS_KEY_ID"] || cfg.SecretAccessKey != env["CARLOS_DOMAIN_AWS_SECRET_ACCESS_KEY"] {
+ t.Fatal("zone credentials changed, including secret whitespace")
+ }
if ctx == nil || ctx.Err() != nil {
t.Fatal("zone constructor requires a live context")
}
@@ -144,7 +149,7 @@ func TestDomainBackendsErrorNeverLeaksPassword(t *testing.T) {
t.Run(stage, func(t *testing.T) {
t.Setenv("CARLOS_STEERING_ZONE_ID", "")
env := domainTestEnv()
- secret := env["CARLOS_OPENPROVIDER_PASSWORD"]
+ secret := env["CARLOS_OPENPROVIDER_PASSWORD"] + env["CARLOS_DOMAIN_AWS_ACCESS_KEY_ID"] + env["CARLOS_DOMAIN_AWS_SECRET_ACCESS_KEY"]
logs := domainTestLog(t)
if stage == "catalog" {
env["CARLOS_DOMAIN_CATALOG"] = filepath.Join(t.TempDir(), secret)
@@ -152,7 +157,7 @@ func TestDomainBackendsErrorNeverLeaksPassword(t *testing.T) {
r, z, a, c, err := domainBackends(func(k string) string { return env[k] },
func(cfg openprovider.Config) (registrar.Registrar, error) {
if stage == "registrar" {
- return nil, fmt.Errorf("constructor failed: %+v", cfg)
+ return nil, fmt.Errorf("constructor failed: %+v %s", cfg, secret)
}
return registrartest.New(), nil
}, func(context.Context, route53zones.Config) (*route53zones.Host, error) {
@@ -167,8 +172,10 @@ func TestDomainBackendsErrorNeverLeaksPassword(t *testing.T) {
if stage != "catalog" && strings.Count(logs.String(), "\n") != 1 {
t.Fatal("adapter failure must log one line")
}
- if strings.Contains(fmt.Sprintf("%+v", err)+logs.String(), strings.TrimSpace(secret)) {
- t.Fatal("startup error leaked the password")
+ for _, name := range []string{"CARLOS_OPENPROVIDER_PASSWORD", "CARLOS_DOMAIN_AWS_ACCESS_KEY_ID", "CARLOS_DOMAIN_AWS_SECRET_ACCESS_KEY"} {
+ if strings.Contains(fmt.Sprintf("%+v", err)+logs.String(), strings.TrimSpace(env[name])) {
+ t.Fatal("startup error leaked credentials")
+ }
}
})
}
diff --git a/docs/site/domains-buying.md b/docs/site/domains-buying.md
index d8cbbff9c..70da47027 100644
--- a/docs/site/domains-buying.md
+++ b/docs/site/domains-buying.md
@@ -46,7 +46,7 @@ AWS includes this operator step in the procedure above.
## Configure the console
-Set all six variables together. If any is empty or whitespace-only, domain
+Set all eight variables together. If any is empty or whitespace-only, domain
buying stays off and one startup log line lists the missing variable names.
A malformed `CARLOS_DOMAIN_CATALOG` stays fatal (operator config error, same as
`CARLOS_PLAN_CATALOG`); a registrar or zone-host constructor failure logs one line
@@ -59,33 +59,74 @@ underlying provider errors.
| `CARLOS_OPENPROVIDER_USERNAME` | Username for that Openprovider account. |
| `CARLOS_OPENPROVIDER_PASSWORD` | Its password, supplied only through the console service's protected `EnvironmentFile`. |
| `CARLOS_DOMAIN_DELEGATION_SET_ID` | ID of the reusable delegation set. |
+| `CARLOS_DOMAIN_AWS_ACCESS_KEY_ID` | Access key ID for the deployment's dedicated zone-host IAM user. |
+| `CARLOS_DOMAIN_AWS_SECRET_ACCESS_KEY` | Its secret access key, supplied only through the console service's protected `EnvironmentFile`. |
| `CARLOS_DOMAIN_NAMESERVERS` | Four distinct comma-separated names, for example `ns1.dns.example,ns2.dns.example,ns3.dns.example,ns4.dns.example`. Spaces around entries are accepted. |
| `CARLOS_DOMAIN_CATALOG` | Absolute path to the catalog JSON file below, readable by the console. |
-Keep the password out of command arguments, shell history, unit-file
-`Environment=` entries and source control. Store it in the service's existing
-secret environment file, with restricted ownership and mode `0600`. Restart the
+Keep the registrar password and AWS keys out of command arguments, shell history,
+unit-file `Environment=` entries and source control. Store them only in the
+console service's `EnvironmentFile`, owned by root with mode `0600`. Restart the
console after changing its environment or catalog.
The console also needs its existing billing provider and plan configuration;
backend settings alone do not enable purchases. See [Plans](/docs/plans).
-Give the console's AWS role the Route 53 permissions its zone host uses:
-`CreateHostedZone`, `ListHostedZones`, `ListResourceRecordSets`,
-`ChangeResourceRecordSets` and `DeleteHostedZone`. Keep access scoped to the
-deployment wherever the action supports it. The adapter uses the existing AWS
-credential chain; `AWS_REGION` or `AWS_DEFAULT_REGION` selects the signing region,
-defaulting to `us-east-1` when neither is set.
+Create a dedicated IAM user per deployment for the zone host. Give it only this
+policy, replacing `<the deployment's set id>` with your reusable delegation set ID:
+
+```json
+{
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Action": [
+ "route53:CreateHostedZone",
+ "route53:ListHostedZones",
+ "route53:ListHostedZonesByName",
+ "route53:GetChange"
+ ],
+ "Resource": "*"
+ },
+ {
+ "Effect": "Allow",
+ "Action": "route53:GetReusableDelegationSet",
+ "Resource": "arn:aws:route53:::delegationset/<the deployment's set id>"
+ },
+ {
+ "Effect": "Allow",
+ "Action": [
+ "route53:GetHostedZone",
+ "route53:DeleteHostedZone",
+ "route53:ChangeResourceRecordSets",
+ "route53:ListResourceRecordSets"
+ ],
+ "Resource": "arn:aws:route53:::hostedzone/*"
+ }
+ ]
+}
+```
+
+Create its access key outside tofu with `aws iam create-access-key`, so the secret
+never enters tofu state. Put the returned key ID and secret in
+`CARLOS_DOMAIN_AWS_ACCESS_KEY_ID` and `CARLOS_DOMAIN_AWS_SECRET_ACCESS_KEY` in the
+console's protected environment file. The zone host uses only these credentials
+and never falls back to the box role. Leave `AWS_PROFILE` and `AWS_DEFAULT_PROFILE`
+unset for the console; the static loader refuses shared profiles. `AWS_REGION` or
+`AWS_DEFAULT_REGION` selects the signing region, defaulting to `us-east-1` when
+neither is set.
With a valid `CARLOS_STEERING_ZONE_ID` and `PLATFORM_APPS_DOMAIN`, the console
copies the latency A records and health-check IDs from
-`edge.<PLATFORM_APPS_DOMAIN>` in that zone. It needs read access to that zone too.
+`edge.<PLATFORM_APPS_DOMAIN>` in that zone, using the same dedicated credentials.
+The policy above includes read access to that zone.
Without a steering hostname, bought zones use the IPv4 addresses in the existing
comma-separated `PLATFORM_EDGE_IPS` setting. Configure working edge addresses
before buying on a deployment without steering.
## Set prices and verify
-The catalog may list only TLDs that allow WHOIS privacy — if wrong, a TLD is
+The catalog may list only TLDs that allow WHOIS privacy. A TLD without it is
unbuyable until removed from the catalog.
Save a catalog such as this at the path in `CARLOS_DOMAIN_CATALOG`. These are
diff --git a/internal/rootaws/config.go b/internal/rootaws/config.go
index c8229d77e..f24e49766 100644
--- a/internal/rootaws/config.go
+++ b/internal/rootaws/config.go
@@ -11,6 +11,7 @@ import (
"github.com/aws/aws-sdk-go-v2/aws"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
)
const credentialsPath = "/etc/carlos/credentials"
@@ -41,6 +42,28 @@ func LoadDefaultConfig(ctx context.Context, opts ...func(*awsconfig.LoadOptions)
return loadRootConfig(ctx, credentialsPath, opts...)
}
+func LoadStaticConfig(ctx context.Context, accessKeyID, secretAccessKey string, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) {
+ if accessKeyID == "" {
+ return aws.Config{}, errors.New("rootaws: accessKeyID is empty")
+ }
+ if secretAccessKey == "" {
+ return aws.Config{}, errors.New("rootaws: secretAccessKey is empty")
+ }
+ if os.Getenv("AWS_PROFILE") != "" || os.Getenv("AWS_DEFAULT_PROFILE") != "" {
+ return aws.Config{}, errors.New("static AWS clients do not support AWS_PROFILE or AWS_DEFAULT_PROFILE")
+ }
+ opts = append(opts, awsconfig.WithSharedConfigFiles([]string{}),
+ awsconfig.WithSharedCredentialsFiles([]string{}), awsconfig.WithSharedConfigProfile(""),
+ awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKeyID, secretAccessKey, "")),
+ func(o *awsconfig.LoadOptions) error {
+ o.UseEC2IMDSRegion = nil
+ o.EC2IMDSClientEnableState = imds.ClientDisabled
+ o.DefaultsModeOptions.IMDSClient = imds.New(imds.Options{ClientEnableState: imds.ClientDisabled})
+ return nil
+ })
+ return awsconfig.LoadDefaultConfig(ctx, opts...)
+}
+
func loadRootConfig(ctx context.Context, path string, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) {
// The SDK cannot ignore an environment profile per call. Refuse it rather
// than mutate process-wide environment while other goroutines may read it.
diff --git a/internal/rootaws/config_test.go b/internal/rootaws/config_test.go
index f54defb37..d2f6f2819 100644
--- a/internal/rootaws/config_test.go
+++ b/internal/rootaws/config_test.go
@@ -3,14 +3,20 @@ package rootaws
import (
"bytes"
"context"
+ "fmt"
"log"
+ "net/http"
+ "net/http/httptest"
"os"
"path/filepath"
"strings"
+ "sync/atomic"
"testing"
+ "github.com/aws/aws-sdk-go-v2/aws"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
)
func TestParseStaticCredentials(t *testing.T) {
@@ -295,3 +301,120 @@ func TestRootCredentialsOffcloudSelection(t *testing.T) {
})
}
}
+
+func TestLoadStaticConfigCredentials(t *testing.T) {
+ for _, ambient := range []bool{false, true} {
+ t.Run(fmt.Sprint(ambient), func(t *testing.T) {
+ isolatedAWSEnv(t)
+ var requests atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests.Add(1)
+ http.Error(w, "unexpected credential lookup", http.StatusForbidden)
+ }))
+ defer server.Close()
+ t.Setenv("AWS_EC2_METADATA_DISABLED", "false")
+ t.Setenv("AWS_EC2_METADATA_SERVICE_ENDPOINT", server.URL)
+ t.Setenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", server.URL)
+ if ambient {
+ t.Setenv("AWS_ACCESS_KEY_ID", "ENV_ACCESS")
+ t.Setenv("AWS_SECRET_ACCESS_KEY", "ENV_SECRET")
+ }
+ t.Setenv("AWS_SESSION_TOKEN", "ENV_TOKEN")
+ dir := t.TempDir()
+ t.Setenv("HOME", dir)
+ if err := os.Mkdir(filepath.Join(dir, ".aws"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(dir, ".aws", "credentials")
+ body := []byte("[default\naws_access_key_id=FILE_ACCESS\naws_secret_access_key=FILE_SECRET\n")
+ if err := os.WriteFile(path, body, 0600); err != nil {
+ t.Fatal(err)
+ }
+ config := filepath.Join(dir, ".aws", "config")
+ if err := os.WriteFile(config, []byte("[invalid section\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("AWS_SHARED_CREDENTIALS_FILE", path)
+ t.Setenv("AWS_CONFIG_FILE", config)
+ cfg, err := LoadStaticConfig(context.Background(), "GIVEN_ACCESS", " GIVEN_SECRET/+== ",
+ awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("OPTION_ACCESS", "OPTION_SECRET", "OPTION_TOKEN")),
+ awsconfig.WithSharedConfigFiles([]string{config}),
+ awsconfig.WithSharedCredentialsFiles([]string{path}),
+ awsconfig.WithSharedConfigProfile("untrusted"),
+ awsconfig.WithRegion("us-east-1"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := cfg.Credentials.Retrieve(context.Background())
+ if err != nil || got.AccessKeyID != "GIVEN_ACCESS" || got.SecretAccessKey != " GIVEN_SECRET/+== " || got.SessionToken != "" {
+ t.Fatalf("explicit static credentials were not preserved: %v", err)
+ }
+ if cfg.Region != "us-east-1" || requests.Load() != 0 {
+ t.Fatal("static loading consulted another configuration source")
+ }
+ })
+ }
+}
+
+func TestLoadStaticConfigEmptyCredentials(t *testing.T) {
+ for _, tc := range []struct{ access, secret, field string }{
+ {"", "SECRET_SENTINEL", "accessKeyID"},
+ {"ACCESS_SENTINEL", "", "secretAccessKey"},
+ } {
+ t.Run(tc.field, func(t *testing.T) {
+ _, err := LoadStaticConfig(context.Background(), tc.access, tc.secret)
+ if err == nil || !strings.Contains(err.Error(), tc.field) {
+ t.Fatalf("missing credential field not named: %v", err)
+ }
+ if strings.Contains(err.Error(), "SENTINEL") {
+ t.Fatal("error leaked credentials")
+ }
+ })
+ }
+}
+
+func TestLoadStaticConfigRefusesEnvironmentProfiles(t *testing.T) {
+ for _, name := range []string{"AWS_PROFILE", "AWS_DEFAULT_PROFILE"} {
+ t.Run(name, func(t *testing.T) {
+ isolatedAWSEnv(t)
+ t.Setenv(name, "PROFILE_SENTINEL")
+ _, err := LoadStaticConfig(context.Background(), "ACCESS_SENTINEL", "SECRET_SENTINEL")
+ if err == nil || !strings.Contains(err.Error(), name) || strings.Contains(err.Error(), "SENTINEL") {
+ t.Fatalf("profile not safely refused: %v", err)
+ }
+ })
+ }
+}
+
+func TestLoadStaticConfigNeverConsultsIMDS(t *testing.T) {
+ for _, mode := range []string{"environment defaults", "caller defaults", "caller region"} {
+ t.Run(mode, func(t *testing.T) {
+ isolatedAWSEnv(t)
+ t.Setenv("AWS_REGION", "")
+ t.Setenv("AWS_DEFAULT_REGION", "")
+ t.Setenv("AWS_EXECUTION_ENV", "")
+ t.Setenv("AWS_EC2_METADATA_DISABLED", "false")
+ var requests atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests.Add(1)
+ http.Error(w, "unexpected metadata request", http.StatusForbidden)
+ }))
+ defer server.Close()
+ t.Setenv("AWS_EC2_METADATA_SERVICE_ENDPOINT", server.URL)
+ client := imds.New(imds.Options{Endpoint: server.URL, HTTPClient: server.Client(), ClientEnableState: imds.ClientEnabled})
+ var opts []func(*awsconfig.LoadOptions) error
+ switch mode {
+ case "environment defaults":
+ t.Setenv("AWS_DEFAULTS_MODE", "auto")
+ case "caller defaults":
+ opts = append(opts, awsconfig.WithDefaultsMode(aws.DefaultsModeAuto, func(o *awsconfig.DefaultsModeOptions) { o.IMDSClient = client }))
+ case "caller region":
+ opts = append(opts, awsconfig.WithEC2IMDSRegion(func(o *awsconfig.UseEC2IMDSRegion) { o.Client = client }))
+ }
+ _, err := LoadStaticConfig(context.Background(), "GIVEN_ACCESS", "GIVEN_SECRET", opts...)
+ if err != nil || requests.Load() != 0 {
+ t.Fatalf("static loading contacted IMDS: requests=%d, err=%v", requests.Load(), err)
+ }
+ })
+ }
+}
diff --git a/internal/zonehost/route53zones/route53.go b/internal/zonehost/route53zones/route53.go
index 34e761374..a7e672da6 100644
--- a/internal/zonehost/route53zones/route53.go
+++ b/internal/zonehost/route53zones/route53.go
@@ -19,10 +19,15 @@ import (
)
type Config struct {
+ AccessKeyID, SecretAccessKey string
DelegationSetID string
Nameservers []string
SteeringZoneID, SteeringHost string
}
+
+func (c Config) String() string { return "route53zones.Config" }
+func (c Config) GoString() string { return c.String() }
+
type Host struct {
client route53API
config Config
@@ -65,6 +70,12 @@ func (m route53Methods) ChangeResourceRecordSets(ctx context.Context, in *route5
}
func New(ctx context.Context, c Config) (*Host, error) {
+ if c.AccessKeyID == "" {
+ return nil, errors.New("route53zones: AccessKeyID is empty")
+ }
+ if c.SecretAccessKey == "" {
+ return nil, errors.New("route53zones: SecretAccessKey is empty")
+ }
if c.DelegationSetID == "" || len(c.Nameservers) != 4 {
return nil, fmt.Errorf("route53zones: delegation set and four nameservers are required")
}
@@ -82,7 +93,7 @@ func New(ctx context.Context, c Config) (*Host, error) {
if strings.TrimSpace(os.Getenv("AWS_REGION")) == "" && strings.TrimSpace(os.Getenv("AWS_DEFAULT_REGION")) == "" {
opts = append(opts, awsconfig.WithRegion("us-east-1"))
}
- cfg, err := rootaws.LoadDefaultConfig(ctx, opts...)
+ cfg, err := rootaws.LoadStaticConfig(ctx, c.AccessKeyID, c.SecretAccessKey, opts...)
if err != nil {
return nil, fmt.Errorf("route53zones: load AWS config: %w", err)
}
diff --git a/internal/zonehost/route53zones/route53_test.go b/internal/zonehost/route53zones/route53_test.go
index 085f9242e..9f17b6f73 100644
--- a/internal/zonehost/route53zones/route53_test.go
+++ b/internal/zonehost/route53zones/route53_test.go
@@ -4,9 +4,13 @@ import (
"context"
"errors"
"fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
"reflect"
"strings"
"testing"
+ "time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/route53"
@@ -490,3 +494,79 @@ func TestSteeredRefusesEmptyOrMalformedTargets(t *testing.T) {
}
}
}
+
+func TestNewRequiresStaticCredentials(t *testing.T) {
+ for _, field := range []string{"AccessKeyID", "SecretAccessKey"} {
+ t.Run(field, func(t *testing.T) {
+ c := Config{AccessKeyID: "ACCESS_SENTINEL", SecretAccessKey: "SECRET_SENTINEL", DelegationSetID: "NTEST", Nameservers: []string{"ns1.dns.example", "ns2.dns.example", "ns3.dns.example", "ns4.dns.example"}}
+ if field == "AccessKeyID" {
+ c.AccessKeyID = ""
+ } else {
+ c.SecretAccessKey = ""
+ }
+ h, err := New(context.Background(), c)
+ if h != nil || err == nil || !strings.Contains(err.Error(), field) || strings.Contains(err.Error(), "SENTINEL") {
+ t.Fatalf("missing credential field not safely refused: %v", err)
+ }
+ })
+ }
+}
+
+func TestConfigRedactsCredentials(t *testing.T) {
+ c := Config{AccessKeyID: "ACCESS_SENTINEL", SecretAccessKey: "SECRET_SENTINEL"}
+ for _, format := range []string{"%v", "%+v", "%#v"} {
+ for _, value := range []any{c, &c} {
+ if strings.Contains(fmt.Sprintf(format, value), "SENTINEL") {
+ t.Fatal("config formatting leaked credentials")
+ }
+ }
+ }
+}
+
+func TestNewUsesStaticCredentialsForZonesAndSteering(t *testing.T) {
+ for _, key := range []string{"AWS_PROFILE", "AWS_DEFAULT_PROFILE", "AWS_CONFIG_FILE", "AWS_SHARED_CREDENTIALS_FILE", "AWS_REGION", "AWS_DEFAULT_REGION"} {
+ t.Setenv(key, "")
+ }
+ t.Setenv("AWS_ACCESS_KEY_ID", "BOX_ACCESS")
+ t.Setenv("AWS_SECRET_ACCESS_KEY", "BOX_SECRET")
+ t.Setenv("AWS_SESSION_TOKEN", "BOX_TOKEN")
+ t.Setenv("AWS_EC2_METADATA_DISABLED", "true")
+ paths := make(chan string, 2)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.Contains(r.Header.Get("Authorization"), "Credential=ZONE_ACCESS/") || r.Header.Get("X-Amz-Security-Token") != "" {
+ t.Error("Route 53 request did not use the dedicated static credentials")
+ }
+ paths <- r.URL.Path
+ w.Header().Set("Content-Type", "text/xml")
+ if strings.HasSuffix(r.URL.Path, "/rrset") {
+ io.WriteString(w, `<ListResourceRecordSetsResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/"><ResourceRecordSets><ResourceRecordSet><Name>edge.apps.example.</Name><Type>A</Type><TTL>60</TTL><ResourceRecords><ResourceRecord><Value>192.0.2.1</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></ResourceRecordSets><IsTruncated>false</IsTruncated><MaxItems>100</MaxItems></ListResourceRecordSetsResponse>`)
+ return
+ }
+ io.WriteString(w, `<ListHostedZonesResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/"><HostedZones></HostedZones><IsTruncated>false</IsTruncated><MaxItems>100</MaxItems></ListHostedZonesResponse>`)
+ }))
+ defer server.Close()
+ t.Setenv("AWS_ENDPOINT_URL_ROUTE_53", server.URL)
+ t.Setenv("AWS_ENDPOINT_URL", server.URL)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ h, err := New(ctx, Config{AccessKeyID: "ZONE_ACCESS", SecretAccessKey: "ZONE_SECRET", DelegationSetID: "NTEST", Nameservers: []string{"ns1.dns.example", "ns2.dns.example", "ns3.dns.example", "ns4.dns.example"}, SteeringZoneID: "ZSTEER", SteeringHost: "edge.apps.example"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := h.client.ListHostedZones(ctx, &route53.ListHostedZonesInput{}); err != nil {
+ t.Fatal(err)
+ }
+ targets, err := h.Steered().ApexTargets(ctx)
+ if err != nil || len(targets) != 1 || targets[0].IP != "192.0.2.1" {
+ t.Fatalf("steering targets: %v, %v", targets, err)
+ }
+ if len(paths) != 2 {
+ t.Fatal("expected zone and steering requests")
+ }
+ if got := <-paths; got != "/2013-04-01/hostedzone" {
+ t.Fatalf("zone path: %q", got)
+ }
+ if got := <-paths; got != "/2013-04-01/hostedzone/ZSTEER/rrset" {
+ t.Fatalf("steering path: %q", got)
+ }
+}