carlos / platform Public

media: repeat only known AWS error codes in diagnostics

Astra round 2, Paul's option A. An error code is text from the response,
so its shape proves nothing: whatever answers at the endpoint could put
a credential or a hostname there, and describe repeated it.

knownAPICodes is now the one list of codes a diagnostic may repeat.
Any other code reads as the HTTP status alone, or as the request having
failed when there is no status. SafeCause and opError inherit this from
describe. A refused RunTask built its reason from the code separately,
so runError now uses the same list.

isCode still compares the response's own code, so classification does
not change. TestEveryComparedCodeIsKnown fails a comparison whose code
is not listed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e8736b3188d1ce1c225c47c1b36a14a9896b1f92 parent 1f63dfc
4 files changed, +227 −19
  • cmd/console/media_serve_test.go +21 −5
  • internal/mediaaws/config.go +78 −7
  • internal/mediaaws/engine.go +8 −7
  • internal/mediaaws/mediaaws_test.go +120 −0

CI passed — run details

diff --git a/cmd/console/media_serve_test.go b/cmd/console/media_serve_test.go
index e18243205..711b40cbc 100644
--- a/cmd/console/media_serve_test.go
+++ b/cmd/console/media_serve_test.go
@@ -41,6 +41,7 @@ type mediaCloudStub struct {
mu sync.Mutex
account string
denyIdent bool
+ denyCode string
identities int
revisions map[string]int
}
@@ -84,7 +85,7 @@ func (s *mediaCloudStub) serve(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/xml")
if s.denyIdent {
w.WriteHeader(http.StatusForbidden)
- fmt.Fprintf(w, `<ErrorResponse><Error><Type>Sender</Type><Code>InvalidClientTokenId</Code><Message>%[1]s</Message></Error><RequestId>%[1]s</RequestId></ErrorResponse>`, mediaCloudSecret)
+ fmt.Fprintf(w, `<ErrorResponse><Error><Type>Sender</Type><Code>%[1]s</Code><Message>%[2]s</Message></Error><RequestId>%[2]s</RequestId></ErrorResponse>`, s.denyCode, mediaCloudSecret)
return
}
fmt.Fprintf(w, `<GetCallerIdentityResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"><GetCallerIdentityResult><Arn>arn:aws:iam::%[1]s:role/console</Arn><UserId>stub</UserId><Account>%[1]s</Account></GetCallerIdentityResult><ResponseMetadata><RequestId>stub</RequestId></ResponseMetadata></GetCallerIdentityResponse>`, s.account)
@@ -93,11 +94,11 @@ func (s *mediaCloudStub) serve(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}
-// denyIdentity makes GetCallerIdentity answer as AWS does a bad credential.
-func (s *mediaCloudStub) denyIdentity() {
+// denyIdentity makes GetCallerIdentity answer 403 with this error code.
+func (s *mediaCloudStub) denyIdentity(code string) {
s.mu.Lock()
defer s.mu.Unlock()
- s.denyIdent = true
+ s.denyIdent, s.denyCode = true, code
}
func (s *mediaCloudStub) identityCalls() int {
@@ -396,7 +397,7 @@ func TestServeMediaWiring(t *testing.T) {
t.Run("a cloud that refuses leaves the console up with media off", func(t *testing.T) {
w := mediaWitness{bin: bin, stub: newMediaCloudStub(t)}
- w.stub.denyIdentity()
+ w.stub.denyIdentity("InvalidClientTokenId")
c := w.boot(t, "CARLOS_STORE_CONVERSION=1", "CARLOS_MEDIA_ENGINE="+testMediaEngine(t, nil))
if got := c.status(t); got.Configured || got.Region != "" {
t.Fatalf("status = %+v", got)
@@ -415,6 +416,21 @@ func TestServeMediaWiring(t *testing.T) {
}
})
+ t.Run("a secret in the error code stays out of the log", func(t *testing.T) {
+ w := mediaWitness{bin: bin, stub: newMediaCloudStub(t)}
+ w.stub.denyIdentity(mediaCloudSecret)
+ c := w.boot(t, "CARLOS_STORE_CONVERSION=1", "CARLOS_MEDIA_ENGINE="+testMediaEngine(t, nil))
+ if strings.Contains(c.output(), mediaCloudSecret) {
+ t.Fatalf("the boot log repeats the response's error code:\n%s", c.output())
+ }
+ if n := strings.Count(c.output(), strings.TrimSuffix(mediaOffAtBoot, "%v")); n != 1 {
+ t.Fatalf("the boot log says media is off %d times, want once:\n%s", n, c.output())
+ }
+ if !strings.Contains(c.output(), "sts GetCallerIdentity: HTTP 403") {
+ t.Fatalf("the boot log does not name the step and the status:\n%s", c.output())
+ }
+ })
+
t.Run("a transport failure keeps its URL out of the log", func(t *testing.T) {
w := mediaWitness{bin: bin, stub: newMediaCloudStub(t)}
// Nothing listens here, and the SDK's error quotes the request URL.
diff --git a/internal/mediaaws/config.go b/internal/mediaaws/config.go
index b585ba566..9d1d6926d 100644
--- a/internal/mediaaws/config.go
+++ b/internal/mediaaws/config.go
@@ -266,13 +266,13 @@ func opError(op string, err error) error {
return out
}
-// SafeCause names err in words safe for a log: the context's end, an AWS error
-// code and HTTP status, or that the request failed. It never repeats err's own
-// text, which can hold a request URL or the service's response.
+// SafeCause names err in words safe for a log: the context's end, a known AWS
+// error code and HTTP status, or that the request failed. It never repeats
+// err's own text, which can hold a request URL or the service's response.
func SafeCause(err error) string { return describe(err) }
-// describe names err without quoting it: the context's end, or an API code
-// and HTTP status, or a bare status, or that the request failed.
+// describe names err without quoting it: the context's end, or a known API
+// code and HTTP status, or a bare status, or that the request failed.
func describe(err error) string {
switch {
case errors.Is(err, context.Canceled):
@@ -281,7 +281,7 @@ func describe(err error) string {
return "timed out"
}
status := httpStatus(err)
- if code := apiCode(err); code != "" {
+ if code := shownCode(err); code != "" {
if status != 0 {
return code + " (HTTP " + strconv.Itoa(status) + ")"
}
@@ -293,8 +293,79 @@ func describe(err error) string {
return "the request failed before an answer came back"
}
+// knownAPICodes are the only error codes a diagnostic repeats. A code is text
+// from the response, so its shape proves nothing: whatever answers at the
+// endpoint can put a credential or a hostname there. Every code this package
+// compares with isCode is listed, and TestEveryComparedCodeIsKnown holds that.
+var knownAPICodes = map[string]bool{
+ // Compared by this package.
+ "AccessDenied": true,
+ "ConflictException": true,
+ "ExpiredTokenException": true,
+ "Forbidden": true,
+ "InvalidParameterException": true,
+ "InvalidRange": true,
+ "NoSuchBucket": true,
+ "NoSuchBucketPolicy": true,
+ "NoSuchCORSConfiguration": true,
+ "NoSuchKey": true,
+ "NoSuchLifecycleConfiguration": true,
+ "NoSuchTagSet": true,
+ "ThrottlingException": true,
+ "TooManyRequestsException": true,
+ "ServerSideEncryptionConfigurationNotFoundError": true,
+
+ // Credentials and signing.
+ "AuthFailure": true,
+ "ExpiredToken": true,
+ "IncompleteSignature": true,
+ "InvalidAccessKeyId": true,
+ "InvalidClientTokenId": true,
+ "InvalidToken": true,
+ "RequestExpired": true,
+ "RequestTimeTooSkewed": true,
+ "SignatureDoesNotMatch": true,
+ "UnrecognizedClientException": true,
+
+ // Permissions.
+ "AccessDeniedException": true,
+ "AccountProblem": true,
+ "AllAccessDisabled": true,
+ "RegionDisabledException": true,
+ "UnauthorizedOperation": true,
+ "MalformedPolicyDocument": true,
+ "PackedPolicyTooLarge": true,
+
+ // Throttling.
+ "RequestLimitExceeded": true,
+ "SlowDown": true,
+ "Throttling": true,
+
+ // The service's own faults.
+ "InternalError": true,
+ "InternalFailure": true,
+ "InternalServerError": true,
+ "RequestTimeout": true,
+ "ServerException": true,
+ "ServiceUnavailable": true,
+
+ // ECS's refusals of a task.
+ "ClientException": true,
+ "ClusterNotFoundException": true,
+ "PlatformUnknownException": true,
+}
+
+// shownCode is err's API error code if a diagnostic may repeat it, else "".
+// It decides what is printed and nothing else: apiCode and isCode classify.
+func shownCode(err error) string {
+ if code := apiCode(err); knownAPICodes[code] {
+ return code
+ }
+ return ""
+}
+
// apiCodePattern is the shape of an AWS error code. Anything else is not
-// repeated: it did not come from the API's own vocabulary.
+// compared: it did not come from the API's own vocabulary.
var apiCodePattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
// apiCode is err's API error code, "" when it has none or an unusable one.
diff --git a/internal/mediaaws/engine.go b/internal/mediaaws/engine.go
index c9914595d..7c1426ea2 100644
--- a/internal/mediaaws/engine.go
+++ b/internal/mediaaws/engine.go
@@ -171,21 +171,22 @@ func runError(err error) error {
if isCode(err, "ConflictException") {
return opError("ecs RunTask", err)
}
- code := apiCode(err)
+ // The reason reaches operators, so it holds only a code they may see.
+ reason := shownCode(err)
if httpStatus(err) == http.StatusTooManyRequests {
- if code == "" {
- code = "HTTP 429"
+ if reason == "" {
+ reason = "HTTP 429"
}
- return &media.Rejected{Retryable: true, Reason: code}
+ return &media.Rejected{Retryable: true, Reason: reason}
}
var api smithy.APIError
if !errors.As(err, &api) || !clientFault(err, api) {
return opError("ecs RunTask", err)
}
- if code == "" {
- code = "the API refused the request"
+ if reason == "" {
+ reason = "the API refused the request"
}
- return &media.Rejected{Retryable: retryableRefusals[code], Reason: code}
+ return &media.Rejected{Retryable: retryableRefusals[apiCode(err)], Reason: reason}
}
// clientFault reports whether the API refused the request without acting on
diff --git a/internal/mediaaws/mediaaws_test.go b/internal/mediaaws/mediaaws_test.go
index d71f2d70b..ba2331e72 100644
--- a/internal/mediaaws/mediaaws_test.go
+++ b/internal/mediaaws/mediaaws_test.go
@@ -8,6 +8,9 @@ import (
"encoding/json"
"errors"
"fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
"io"
"net"
"net/http"
@@ -35,6 +38,7 @@ import (
"github.com/aws/aws-sdk-go-v2/service/sts"
ststypes "github.com/aws/aws-sdk-go-v2/service/sts/types"
"github.com/aws/smithy-go"
+ smithyhttp "github.com/aws/smithy-go/transport/http"
"github.com/carlosframework/platform/internal/media"
"github.com/carlosframework/platform/internal/mediahandler"
@@ -2763,3 +2767,119 @@ func TestHandlerTransfersAgainstASigningStore(t *testing.T) {
t.Fatalf("x-id did not arrive: %v", store.seen)
}
}
+
+// A code compared for control flow must also be one a diagnostic can name, or
+// a new comparison would silently lose its diagnostic.
+func TestEveryComparedCodeIsKnown(t *testing.T) {
+ fset := token.NewFileSet()
+ pkgs, err := parser.ParseDir(fset, ".", func(fi os.FileInfo) bool {
+ return !strings.HasSuffix(fi.Name(), "_test.go")
+ }, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ compared := 0
+ for _, pkg := range pkgs {
+ for _, f := range pkg.Files {
+ ast.Inspect(f, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ if fn, ok := call.Fun.(*ast.Ident); !ok || fn.Name != "isCode" || len(call.Args) != 2 {
+ return true
+ }
+ lit, ok := call.Args[1].(*ast.BasicLit)
+ if !ok || lit.Kind != token.STRING {
+ t.Errorf("%s: isCode is not given a string literal", fset.Position(call.Pos()))
+ return true
+ }
+ code, err := strconv.Unquote(lit.Value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ compared++
+ if !knownAPICodes[code] {
+ t.Errorf("%s: isCode compares %q, which knownAPICodes does not list", fset.Position(call.Pos()), code)
+ }
+ return true
+ })
+ }
+ }
+ if compared < 10 {
+ t.Fatalf("found only %d isCode comparisons; the walk no longer sees them", compared)
+ }
+ for code := range retryableRefusals {
+ if !knownAPICodes[code] {
+ t.Errorf("retryableRefusals holds %q, which knownAPICodes does not list", code)
+ }
+ }
+}
+
+// statusAPIError is an API error as the SDK wraps it, with an HTTP status.
+func statusAPIError(code string, status int) error {
+ return fmt.Errorf("operation error: %w", &smithyhttp.ResponseError{
+ Response: &smithyhttp.Response{Response: &http.Response{StatusCode: status}},
+ Err: &smithy.GenericAPIError{Code: code, Message: "the message"},
+ })
+}
+
+// hostileAPICodes all have the shape of an error code, and none is one.
+var hostileAPICodes = map[string]string{
+ "secret": "hunter2-cloud-secret",
+ "access key": "AKIAIOSFODNN7EXAMPLE",
+ "hostname": "store.internal.example.com",
+}
+
+// A code from the response is repeated only if it is a known one. The status
+// is still reported, and the code still classifies.
+func TestUnknownCodesAreNeverRepeated(t *testing.T) {
+ for name, code := range hostileAPICodes {
+ t.Run(name, func(t *testing.T) {
+ err := statusAPIError(code, http.StatusForbidden)
+ if got := SafeCause(err); got != "HTTP 403" {
+ t.Errorf("SafeCause = %q, want the status alone", got)
+ }
+ if got := opError("sts AssumeRole", err).Error(); got != "media: sts AssumeRole: HTTP 403" {
+ t.Errorf("opError = %q, want the status alone", got)
+ }
+ bare := &smithy.GenericAPIError{Code: code}
+ if got := SafeCause(bare); got != "the request failed before an answer came back" {
+ t.Errorf("SafeCause with no status = %q", got)
+ }
+ if !isCode(err, code) {
+ t.Error("isCode no longer sees the response's code")
+ }
+ })
+ }
+ if got := SafeCause(statusAPIError("ExpiredToken", http.StatusForbidden)); got != "ExpiredToken (HTTP 403)" {
+ t.Errorf("a known code reads %q", got)
+ }
+}
+
+// A refused launch's reason reaches operators by a path of its own.
+func TestRunErrorNeverRepeatsAnUnknownCode(t *testing.T) {
+ for name, code := range hostileAPICodes {
+ t.Run(name, func(t *testing.T) {
+ for status, want := range map[int]string{
+ http.StatusTooManyRequests: "HTTP 429",
+ http.StatusBadRequest: "the API refused the request",
+ } {
+ var rej *media.Rejected
+ if err := runError(statusAPIError(code, status)); !errors.As(err, &rej) {
+ t.Fatalf("status %d: %v is not a refusal", status, err)
+ }
+ if rej.Reason != want {
+ t.Errorf("status %d: reason = %q, want %q", status, rej.Reason, want)
+ }
+ }
+ })
+ }
+ var rej *media.Rejected
+ if err := runError(statusAPIError("ThrottlingException", http.StatusBadRequest)); !errors.As(err, &rej) {
+ t.Fatalf("%v is not a refusal", err)
+ }
+ if rej.Reason != "ThrottlingException" || !rej.Retryable {
+ t.Errorf("a known retryable refusal reads %+v", rej)
+ }
+}