hosts-used scan: Paul's cut on 438 (plain prefixes, strict pages) and the probe dir (437)
Summary
- (a) A bucket's prefix is taken only in plain form: segments of [A-Za-z0-9._-]+ joined by single slashes, none "." or "..", or "" (the box's path.Join puts replicas at the top level then). The check runs in jq on the coords' JSON value for every roster bucket before any AWS call; any other prefix (or a non-string one) stops the run with exit 2 and no output. The trim-to-match-the-box code is gone. Witness: 17 non-plain prefixes, each exit 2, no file, zero aws calls; "", one and two segments listed as written. - (b) An S3 reply is a page only when it is exactly one JSON object whose Contents is absent or an array of objects with non-empty string Keys under the prefix, whose KeyCount counts them, and whose IsTruncated is a boolean, true with a non-empty NextContinuationToken and false with none. Witnesses: Contents false or null, two objects in one reply, truncated with no token, a token while not truncated, a numeric Key, an array reply, plus round 1's cases. - (c) The header no longer calls the box listing sorted. - (d) layout.HostsFromBoxListing skips instances/_probe and .instances/_probe (instancectl.ProbeDirName, exact match, with whatever the probe leaves inside); _probex, _Probe and _probe.example.com stay unmapped.
Agent notes
tests failed first, then passed: cmd/console -run TestHostsUsedScanAWS, internal/layout (whole package), internal/console -run 'Activate|Invalidate'. Dev dry run again (read-only): 5 ok, r10w NoSuchBucket; through the fixed mapper every dev listing maps with no unmapped entry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+175
−82
cmd/console/hostsused_scan_test.go+95 −55internal/layout/hostsused.go+10 −1internal/layout/hostsused_test.go+23 −0scripts/hosts-used-scan-aws.sh+47 −26
diff --git a/cmd/console/hostsused_scan_test.go b/cmd/console/hostsused_scan_test.go| index 4539bcc89..bee972d08 100644 |
| --- a/cmd/console/hostsused_scan_test.go |
| +++ b/cmd/console/hostsused_scan_test.go |
| @@ -38,8 +38,8 @@ type fakeBucket struct { |
| Keys []string `json:"keys"` |
| Fail string `json:"fail"` // every call fails with this |
| FailPage int `json:"fail_page"` // the call for this page (1-based) fails |
| - // Malformed answers a page that is no listing: "nokey" (an entry |
| - // without a Key), "empty" ({}), "outside" (a key not under the prefix). |
| + // Malformed answers a page that is no listing: one of the keys of |
| + // malformedPages. |
| Malformed string `json:"malformed"` |
| } |
| @@ -106,15 +106,8 @@ func fakeListObjects(cfg fakeAWSConfig, opts map[string]string) int { |
| fmt.Fprintf(os.Stderr, "An error occurred (AccessDenied) when calling the ListObjectsV2 operation: %s\n", b.Fail) |
| return 254 |
| } |
| - switch b.Malformed { |
| - case "nokey": |
| - fmt.Println(`{"IsTruncated":false,"KeyCount":1,"Contents":[{"Size":1}]}`) |
| - return 0 |
| - case "empty": |
| - fmt.Println(`{}`) |
| - return 0 |
| - case "outside": |
| - fmt.Println(`{"IsTruncated":false,"KeyCount":1,"Contents":[{"Key":"elsewhere/a.example.com/x"}]}`) |
| + if page, ok := malformedPages[b.Malformed]; ok { |
| + fmt.Println(page) |
| return 0 |
| } |
| var keys []string |
| @@ -140,6 +133,20 @@ func fakeListObjects(cfg fakeAWSConfig, opts map[string]string) int { |
| return 0 |
| } |
| +// malformedPages are list-objects-v2 replies that are no listing. |
| +var malformedPages = map[string]string{ |
| + "nokey": `{"IsTruncated":false,"KeyCount":1,"Contents":[{"Size":1}]}`, |
| + "key-number": `{"IsTruncated":false,"KeyCount":1,"Contents":[{"Key":5}]}`, |
| + "empty": `{}`, |
| + "outside": `{"IsTruncated":false,"KeyCount":1,"Contents":[{"Key":"elsewhere/a.example.com/x"}]}`, |
| + "contents-false": `{"IsTruncated":false,"KeyCount":0,"Contents":false}`, |
| + "contents-null": `{"IsTruncated":false,"KeyCount":0,"Contents":null}`, |
| + "two-objects": "{\"IsTruncated\":true,\"KeyCount\":0,\"NextContinuationToken\":\"t\"}\n{\"IsTruncated\":false,\"KeyCount\":0}", |
| + "truncated-no-token": `{"IsTruncated":true,"KeyCount":0}`, |
| + "token-not-truncated": `{"IsTruncated":false,"KeyCount":0,"NextContinuationToken":"t"}`, |
| + "array": `[{"IsTruncated":false,"KeyCount":0}]`, |
| +} |
| + |
| func fakeSendCommand(dir string, cfg fakeAWSConfig, opts map[string]string) int { |
| inst, ok := cfg.Instances[opts["--instance-ids"]] |
| if !ok || inst.SendFail != "" { |
| @@ -524,9 +531,11 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) { |
| d = w.box("box:grows-once", "i-0a5", "shop.example.com.db") |
| w.cfg.Instances["i-0a5"] = fakeInstance{GrowDir: d, GrowAt: 2} |
| w.coordinates["box:badinst"] = map[string]string{"instance": "i-0a6; rm -rf /", "region": "eu-west-1"} |
| - for _, m := range []string{"nokey", "empty", "outside"} { |
| + var malformed []string |
| + for m := range malformedPages { |
| w.bucket("bucket:malformed-"+m, "instances") |
| w.cfg.Buckets["malformed-"+m] = fakeBucket{Malformed: m} |
| + malformed = append(malformed, "bucket:malformed-"+m) |
| } |
| for i, tool := range []string{"gzip", "sha256sum", "wc"} { |
| inst := fmt.Sprintf("i-0b%d", i) |
| @@ -536,7 +545,8 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) { |
| roster := map[string]any{"targets": []string{"bucket:ok", "bucket:denied", "bucket:page2", "bucket:noprefix", "bucket:nocoords", |
| "box:okbox", "box:unsent", "box:nodir", "box:cut", "box:grows", "box:grows-once", "box:badinst", "box:nocoords", "pool:p1", |
| - "bucket:malformed-nokey", "bucket:malformed-empty", "bucket:malformed-outside", "box:broken-gzip", "box:broken-sha256sum", "box:broken-wc"}} |
| + "box:broken-gzip", "box:broken-sha256sum", "box:broken-wc"}} |
| + roster["targets"] = append(roster["targets"].([]string), malformed...) |
| rosterPath := filepath.Join(w.dir, "roster.json") |
| writeJSON(t, rosterPath, roster) |
| got, stderr, code := w.scan(rosterPath, "HOSTS_SCAN_PAGE=40") |
| @@ -544,31 +554,11 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) { |
| t.Fatalf("scan exit %d, want 1\n%s", code, stderr) |
| } |
| ls := byTarget(got) |
| - if len(got) != 20 || len(ls) != 20 { |
| - t.Fatalf("want one line for each of 20 targets, got %d: %+v", len(got), got) |
| + if want := 17 + len(malformedPages); len(got) != want || len(ls) != want { |
| + t.Fatalf("want one line for each of %d targets, got %d: %+v", want, len(got), got) |
| } |
| - for target, want := range map[string]string{ |
| - "bucket:ok": "", |
| - "box:okbox": "", |
| - "box:grows-once": "", |
| - "bucket:denied": "AccessDenied", |
| - "bucket:page2": "AccessDenied", |
| - "bucket:noprefix": "no prefix for bucket:noprefix", |
| - "bucket:nocoords": "no prefix for bucket:nocoords", |
| - "box:unsent": "InvalidInstanceId", |
| - "box:nodir": "Failed (exit 3)", |
| - "box:cut": "cut short", |
| - "box:grows": "changed while it was paged", |
| - "box:badinst": "is not an instance id", |
| - "box:nocoords": "no instance for box:nocoords", |
| - "pool:p1": "does not know this kind of target", |
| - "bucket:malformed-nokey": "not a well-formed listing", |
| - "bucket:malformed-empty": "not a well-formed listing", |
| - "bucket:malformed-outside": "not a well-formed listing", |
| - "box:broken-gzip": "does not decode", |
| - "box:broken-sha256sum": "Failed (exit 6)", |
| - "box:broken-wc": "Failed (exit 6)", |
| - } { |
| + expect := func(target, want string) { |
| + t.Helper() |
| l, ok := ls[target] |
| switch { |
| case !ok: |
| @@ -579,6 +569,30 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) { |
| t.Errorf("%s: want ok:false with %q and no entries, got %+v", target, want, l) |
| } |
| } |
| + for target, want := range map[string]string{ |
| + "bucket:ok": "", |
| + "box:okbox": "", |
| + "box:grows-once": "", |
| + "bucket:denied": "AccessDenied", |
| + "bucket:page2": "AccessDenied", |
| + "bucket:noprefix": "no prefix for bucket:noprefix", |
| + "bucket:nocoords": "no prefix for bucket:nocoords", |
| + "box:unsent": "InvalidInstanceId", |
| + "box:nodir": "Failed (exit 3)", |
| + "box:cut": "cut short", |
| + "box:grows": "changed while it was paged", |
| + "box:badinst": "is not an instance id", |
| + "box:nocoords": "no instance for box:nocoords", |
| + "pool:p1": "does not know this kind of target", |
| + "box:broken-gzip": "does not decode", |
| + "box:broken-sha256sum": "Failed (exit 6)", |
| + "box:broken-wc": "Failed (exit 6)", |
| + } { |
| + expect(target, want) |
| + } |
| + for m := range malformedPages { |
| + expect("bucket:malformed-"+m, "not a well-formed listing") |
| + } |
| for _, c := range w.calls() { |
| if slices.Contains(c, "i-0a6; rm -rf /") { |
| t.Errorf("a bad instance id reached aws: %q", c) |
| @@ -586,31 +600,57 @@ func TestHostsUsedScanAWSFailsATargetClosed(t *testing.T) { |
| } |
| } |
| -// TestHostsUsedScanAWSPrefixAsTheBoxReadsIt: the coords' prefix is read as |
| -// the box reads CARLOS_HIBERNATE_PREFIX, strings.Trim(strings.TrimSpace(v), |
| -// "/"): "///" is the top level, so the whole bucket is listed, and |
| -// " //instances// " is instances. A prefix that is not printable ASCII fails. |
| -func TestHostsUsedScanAWSPrefixAsTheBoxReadsIt(t *testing.T) { |
| +// TestHostsUsedScanAWSPrefixInPlainFormOnly (Paul's cut on discussion 438): |
| +// a bucket's prefix is taken only in plain form, segments of |
| +// [A-Za-z0-9._-]+ joined by single slashes, none of them "." or "..", or |
| +// "" (replicas at the top level). Any other prefix stops the whole run |
| +// before any AWS call, with exit 2 and no output. A plain prefix is listed |
| +// as written. |
| +func TestHostsUsedScanAWSPrefixInPlainFormOnly(t *testing.T) { |
| + keys := []string{"top.example.com/db/1", "moves/m.example.com/x", "a/b.c-d_e/i.example.com/y", "instances/j.example.com/z"} |
| + for _, bad := range []string{"/instances", "instances/", "///", " //instances// ", "a//b", "a/./b", "./a", "a/..", "..", ".", |
| + "snapshots/../instances", " instances", "inst ances", "instances\t", "\u00edinstances", "a\nb", "a/b/"} { |
| + w := newScanWorld(t) |
| + w.bucket("bucket:good", "instances", keys...) |
| + w.bucket("bucket:bad", bad, keys...) |
| + rosterPath := filepath.Join(w.dir, "roster.json") |
| + writeJSON(t, rosterPath, map[string]any{"targets": []string{"bucket:good", "bucket:bad"}}) |
| + writeJSON(t, filepath.Join(w.fake, "config.json"), w.cfg) |
| + writeJSON(t, w.coordsPath, w.coordinates) |
| + out := filepath.Join(w.dir, "scan.jsonl") |
| + cmd := exec.Command(scanScript, "--profile", "scan-test", "--targets", w.coordsPath, rosterPath, out) |
| + cmd.Env = append(os.Environ(), w.env...) |
| + b, err := cmd.CombinedOutput() |
| + var ee *exec.ExitError |
| + if !errors.As(err, &ee) || ee.ExitCode() != 2 || !strings.Contains(string(b), "bucket:bad") || !strings.Contains(string(b), "plain form") { |
| + t.Errorf("prefix %q: %v, want exit 2 naming bucket:bad\n%s", bad, err, b) |
| + } |
| + if _, err := os.Stat(out); err == nil { |
| + t.Errorf("prefix %q: an output file was written", bad) |
| + } |
| + if calls := w.calls(); len(calls) != 0 { |
| + t.Errorf("prefix %q: %d aws calls before the refusal", bad, len(calls)) |
| + } |
| + } |
| w := newScanWorld(t) |
| - keys := []string{"top.example.com/db/1", "moves/m.example.com/x", "instances/i.example.com/y"} |
| - w.bucket("bucket:slashes", "///", keys...) |
| - w.bucket("bucket:padded", " //instances// ", keys...) |
| - w.bucket("bucket:tab", "instances\t", keys...) |
| + w.bucket("bucket:top", "", keys...) |
| + w.bucket("bucket:one", "instances", keys...) |
| + w.bucket("bucket:two", "a/b.c-d_e", keys...) |
| rosterPath := filepath.Join(w.dir, "roster.json") |
| - writeJSON(t, rosterPath, map[string]any{"targets": []string{"bucket:slashes", "bucket:padded", "bucket:tab"}}) |
| + writeJSON(t, rosterPath, map[string]any{"targets": []string{"bucket:top", "bucket:one", "bucket:two"}}) |
| got, stderr, code := w.scan(rosterPath) |
| - if code != 1 { |
| - t.Fatalf("scan exit %d, want 1\n%s", code, stderr) |
| + if code != 0 { |
| + t.Fatalf("plain prefixes: exit %d\n%s", code, stderr) |
| } |
| ls := byTarget(got) |
| - if l := ls["bucket:slashes"]; !l.OK || l.Prefix != "" || !slices.Equal(l.Entries, slices.Sorted(slices.Values(keys))) { |
| - t.Errorf("prefix /// = %+v, want the whole bucket with prefix \"\"", l) |
| + if l := ls["bucket:top"]; l.Prefix != "" || !slices.Equal(l.Entries, slices.Sorted(slices.Values(keys))) { |
| + t.Errorf("prefix \"\" = %+v, want the whole bucket", l) |
| } |
| - if l := ls["bucket:padded"]; !l.OK || l.Prefix != "instances" || !slices.Equal(l.Entries, []string{"instances/i.example.com/y", "moves/m.example.com/x"}) { |
| - t.Errorf("prefix \" //instances// \" = %+v, want instances", l) |
| + if l := ls["bucket:one"]; l.Prefix != "instances" || !slices.Equal(l.Entries, []string{"instances/j.example.com/z", "moves/m.example.com/x"}) { |
| + t.Errorf("prefix instances = %+v", l) |
| } |
| - if l := ls["bucket:tab"]; l.OK || !strings.Contains(l.Error, "not printable ASCII") { |
| - t.Errorf("a prefix with a tab = %+v, want ok:false", l) |
| + if l := ls["bucket:two"]; l.Prefix != "a/b.c-d_e" || !slices.Equal(l.Entries, []string{"a/b.c-d_e/i.example.com/y", "moves/m.example.com/x"}) { |
| + t.Errorf("prefix a/b.c-d_e = %+v", l) |
| } |
| } |
diff --git a/internal/layout/hostsused.go b/internal/layout/hostsused.go| index 538654666..034635933 100644 |
| --- a/internal/layout/hostsused.go |
| +++ b/internal/layout/hostsused.go |
| @@ -5,6 +5,7 @@ import ( |
| "strings" |
| "github.com/carlosframework/platform/internal/controlname" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/provision" |
| ) |
| @@ -22,7 +23,9 @@ import ( |
| // is unmapped: nothing is normalised. |
| // - instances/<id>/ and .instances/<id>/ map to <id>, or for a hashed id |
| // ("_" + prefix + hash, provision.InstanceID) to the full host a file |
| -// inside names; a hashed id with none is unmapped. |
| +// inside names; a hashed id with none is unmapped. The readiness |
| +// probe's own directory (instancectl.ProbeDirName) is the box's and |
| +// skipped, by that exact name only. |
| // - .offline-moves/<host>/ maps to <host>, or is unmapped. |
| // - Any other hidden entry (.parked/<hash>/<host>/, .moves/, .hostexec/ |
| // and the like) marks every host-like segment of its path, after the |
| @@ -46,6 +49,12 @@ func HostsFromBoxListing(paths []string) (hosts, unmapped []string) { |
| continue |
| } |
| id := segs[1] |
| + // The readiness probe's own directory (made at bootstrap, |
| + // internal/host/bootstrap.go), and whatever the probe leaves in |
| + // it, is the box's. Only that exact name: no host can have it. |
| + if id == instancectl.ProbeDirName { |
| + continue |
| + } |
| if strings.HasPrefix(id, "_") { |
| dir := segs[0] + "/" + id |
| if _, seen := hashed[dir]; !seen { |
diff --git a/internal/layout/hostsused_test.go b/internal/layout/hostsused_test.go| index 0023ef935..73d95e96a 100644 |
| --- a/internal/layout/hostsused_test.go |
| +++ b/internal/layout/hostsused_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "strings" |
| "testing" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/provision" |
| ) |
| @@ -143,3 +144,25 @@ func TestHashedInstanceDirWithoutHostIsUnmapped(t *testing.T) { |
| t.Fatalf("hosts %v unmapped %v", hosts, unmapped) |
| } |
| } |
| + |
| +// The readiness probe's own instance directory (instancectl.ProbeDirName, |
| +// made at bootstrap under .instances/ and seen as instances/ on a box) is |
| +// the box's, not a host's: skipped with whatever the probe left in it. Only |
| +// that exact name is skipped; any other "_" id is still a hashed id, and |
| +// unmapped without a host-named file inside (discussion 437). |
| +func TestBoxListingSkipsTheProbeDir(t *testing.T) { |
| + hosts, unmapped := HostsFromBoxListing([]string{ |
| + "instances/_probe", ".instances/_probe", "instances/_probe/link", ".instances/_probe/probe.example.com.db", |
| + "./instances/_probe/", |
| + }) |
| + if len(hosts) != 0 || len(unmapped) != 0 { |
| + t.Fatalf("the probe dir maps to %q, unmapped %q; want nothing", hosts, unmapped) |
| + } |
| + _, unmapped = HostsFromBoxListing([]string{"instances/_probex", ".instances/_Probe", "instances/_probe.example.com"}) |
| + if want := []string{".instances/_Probe", "instances/_probe.example.com", "instances/_probex"}; !reflect.DeepEqual(unmapped, want) { |
| + t.Fatalf("near-probe names: unmapped %q, want %q", unmapped, want) |
| + } |
| + if instancectl.ProbeDirName != "_probe" { |
| + t.Fatalf("ProbeDirName = %q: the dev listings and this test assume _probe", instancectl.ProbeDirName) |
| + } |
| +} |
diff --git a/scripts/hosts-used-scan-aws.sh b/scripts/hosts-used-scan-aws.sh| index 81a6ee40a..f1a11f1f8 100755 |
| --- a/scripts/hosts-used-scan-aws.sh |
| +++ b/scripts/hosts-used-scan-aws.sh |
| @@ -20,22 +20,26 @@ |
| # "bucket:<name>": {"prefix": "instances", "region": "eu-west-1"}} |
| # |
| # data_dir defaults to /data. prefix is required: it is the boxes' |
| -# CARLOS_HIBERNATE_PREFIX ("" puts replicas at the bucket's top level, and |
| -# then the whole bucket is listed). A wrong prefix misses that bucket's |
| -# replicas, so it is never defaulted. region is optional for a bucket. |
| +# CARLOS_HIBERNATE_PREFIX as the box resolves it ("" puts replicas at the |
| +# bucket's top level, and then the whole bucket is listed). A wrong prefix |
| +# misses that bucket's replicas, so it is never defaulted, and it is taken |
| +# only in plain form: segments of [A-Za-z0-9._-]+ joined by single slashes, |
| +# none of them "." or "..", or "". Any other prefix stops the whole run |
| +# before any AWS call. region is optional for a bucket. |
| # |
| # Any failure for a target (no coordinates, an AWS error, a command that |
| # failed or timed out, a listing that changed while it was paged) gives that |
| # target ok:false and the error, which activate refuses. SSM returns at most |
| -# 24,000 characters of output, so a box's listing comes back sorted, gzipped |
| -# and base64-encoded, in pages of HOSTS_SCAN_PAGE characters; every page |
| +# 24,000 characters of output, so a box's listing comes back in find's own |
| +# order, gzipped and base64-encoded, in pages of HOSTS_SCAN_PAGE characters; every page |
| # carries the whole listing's sha256, length and line count, and the |
| # reassembled listing must match all three. Nothing is truncated silently. |
| # |
| # Read-only: the only AWS calls are s3api list-objects-v2, ssm send-command |
| # (running find, which writes nothing on the box) and ssm |
| # get-command-invocation. Exit 0 when every target is ok, 1 when any is |
| -# not (the output file is still written), 2 on bad arguments. |
| +# not (the output file is still written), 2 on bad arguments, a prefix not |
| +# in plain form, or an output file that could not be written. |
| # HOSTS_SCAN_POLL, HOSTS_SCAN_WAIT and HOSTS_SCAN_PAGE exist for tests. |
| set -uo pipefail |
| export LC_ALL=C |
| @@ -64,6 +68,21 @@ command -v aws >/dev/null || { echo "hosts-used-scan: the aws CLI is required" > |
| targets="$(jq -r 'if (.targets|type) == "array" and all(.targets[]; type == "string") then .targets[] else error("no targets array") end' "$roster")" || { |
| echo "hosts-used-scan: $roster is not a roster: it needs a targets array of strings" >&2; exit 2; } |
| jq -e 'type == "object"' "$coords" >/dev/null 2>&1 || { echo "hosts-used-scan: $coords is not a JSON object" >&2; exit 2; } |
| +# Every bucket's prefix in plain form, checked on the JSON value itself (a |
| +# shell capture would drop a trailing newline), before anything is listed. |
| +notplain="$(jq -rn --slurpfile r "$roster" --slurpfile c "$coords" ' |
| + def plain: . == "" or (split("/") | all(. != "" and . != "." and . != ".." |
| + and (explode | all(. as $x | ($x >= 48 and $x <= 57) or ($x >= 65 and $x <= 90) or ($x >= 97 and $x <= 122) |
| + or $x == 45 or $x == 46 or $x == 95)))); |
| + $r[0].targets[] | select(startswith("bucket:")) as $t | $c[0][$t] |
| + | select(type == "object" and has("prefix")) | select((.prefix|type) != "string" or (.prefix|plain|not)) | $t')" || { |
| + echo "hosts-used-scan: could not check the prefixes in $coords" >&2; exit 2; } |
| +if [ -n "$notplain" ]; then |
| + while IFS= read -r t; do |
| + echo "hosts-used-scan: the prefix for $t in $coords is not in plain form. write it as the box resolves CARLOS_HIBERNATE_PREFIX: segments of letters, digits, '.', '_' and '-' joined by single slashes, with no '.' or '..' segment and no slash at either end, or \"\" for the top level" >&2 |
| + done <<<"$notplain" |
| + exit 2 |
| +fi |
| export AWS_PAGER="" |
| work="$(mktemp -d "${TMPDIR:-/tmp}/hosts-used-scan.XXXXXX")" || exit 2 |
| part="$(mktemp "$out.XXXXXX")" || { rm -rf "$work"; exit 2; } |
| @@ -93,25 +112,35 @@ coord() { # <roster target> <field>: the field, or exit 1 when absent |
| # list_prefix <bucket> <region> <prefix>: append every page's keys, one JSON |
| # array per line, to $work/keys; on failure set $err and return 1. |
| list_prefix() { |
| - local b="$1" r="$2" p="$3" token="" resp trunc n=0 |
| + local b="$1" r="$2" p="$3" token="" resp pg trunc n=0 |
| while :; do |
| set -- s3api list-objects-v2 --bucket "$b" --prefix "$p" --max-keys 1000 --no-paginate --output json |
| [ -n "$r" ] && set -- "$@" --region "$r" |
| [ -n "$token" ] && set -- "$@" --continuation-token "$token" |
| resp="$(awsp "$@" 2>"$work/err")" || { err="list s3://$b/$p: $(oneline <"$work/err")"; return 1; } |
| n=$((n + 1)) |
| - # A page is a listing only when it says whether it is the last, counts |
| - # its keys, and every key is a non-empty string under the prefix asked |
| - # for. Anything else fails the bucket, never reads as no keys. |
| - jq -ce --arg p "$p" 'if type == "object" and (.IsTruncated|type) == "boolean" and (.KeyCount|type) == "number" |
| - and ((.Contents // [])|type) == "array" and (.KeyCount == ((.Contents // [])|length)) |
| - and all((.Contents // [])[]; type == "object" and (.Key|type) == "string" and .Key != "" and (.Key|startswith($p))) |
| - then [(.Contents // [])[].Key] else error("malformed") end' <<<"$resp" >>"$work/keys" 2>/dev/null || { |
| + # A reply is a page only when it is exactly one JSON object whose |
| + # Contents is absent or an array of objects, each with a non-empty |
| + # string Key under the prefix asked for; whose KeyCount counts them; |
| + # and whose IsTruncated is a boolean, true with a non-empty |
| + # NextContinuationToken and false with none. Anything else fails the |
| + # bucket, and never reads as no keys or as the last page. |
| + pg="$(jq -cse --arg p "$p" ' |
| + if length == 1 and (.[0]|type) == "object" then .[0] else error("not one object") end |
| + | if has("Contents") and ((.Contents|type) != "array" |
| + or (all(.Contents[]; type == "object" and (.Key|type) == "string" and .Key != "" and (.Key|startswith($p))) | not)) |
| + then error("contents") else . end |
| + | (if has("Contents") then .Contents else [] end) as $c |
| + | if (.IsTruncated|type) != "boolean" then error("truncated") else . end |
| + | if (.KeyCount|type) != "number" or .KeyCount != ($c|length) then error("count") else . end |
| + | if .IsTruncated then (if (.NextContinuationToken|type) == "string" and .NextContinuationToken != "" then . else error("token") end) |
| + elif has("NextContinuationToken") and .NextContinuationToken != null then error("token") else . end |
| + | [[$c[].Key], .IsTruncated, (.NextContinuationToken // "")]' <<<"$resp" 2>/dev/null)" || { |
| err="list s3://$b/$p: page $n is not a well-formed listing"; return 1; } |
| - trunc="$(jq -r '.IsTruncated' <<<"$resp")" |
| + jq -c '.[0]' <<<"$pg" >>"$work/keys" || { err="list s3://$b/$p: could not keep page $n"; return 1; } |
| + trunc="$(jq -r '.[1]' <<<"$pg")" |
| [ "$trunc" = true ] || return 0 |
| - token="$(jq -r '.NextContinuationToken // empty | strings' <<<"$resp")" |
| - [ -n "$token" ] || { err="list s3://$b/$p: page $n is truncated with no continuation token"; return 1; } |
| + token="$(jq -r '.[2]' <<<"$pg")" |
| done |
| } |
| @@ -119,15 +148,7 @@ scan_bucket() { # <roster target> <bucket> |
| local t="$1" b="$2" prefix region p line |
| prefix="$(coord "$t" prefix)" || { emit_fail "$b" bucket "no prefix for $t in $coords"; return; } |
| region="$(coord "$t" region)" || region="" |
| - # The box reads its prefix as strings.Trim(strings.TrimSpace(v), "/") |
| - # (internal/activator/activator.go), and so must the scan, or it lists a |
| - # namespace the box does not write. Only printable ASCII is taken, so |
| - # the trims below are the same as Go's. |
| - case "$prefix" in *[!\ -~]*) emit_fail "$b" bucket "prefix for $t is not printable ASCII"; return ;; esac |
| - while [ "${prefix# }" != "$prefix" ]; do prefix="${prefix# }"; done |
| - while [ "${prefix% }" != "$prefix" ]; do prefix="${prefix% }"; done |
| - while [ "${prefix#/}" != "$prefix" ]; do prefix="${prefix#/}"; done |
| - while [ "${prefix%/}" != "$prefix" ]; do prefix="${prefix%/}"; done |
| + # The prefix is in plain form: checked for every bucket before the scan. |
| : >"$work/keys" |
| err="" |
| if [ -z "$prefix" ]; then |