Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/interplane-forge/blob/main/patch/tests/run.sh # interplane-forge INTERPLANE Forge Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `interplane-forge / patch / tests / run.sh` 1642 lines · 155247 bytes Raw Blame History 1 #!/bin/bash 2 # Git patch intake test (docs/API.md "Git patches"; ./run.sh check-patch). HOST test on spark, on a 3 # private copy of forged with fixture folders (patch/tests/lib.sh); nothing of the live forge is used. 4 # Every refusal of the upload has a negative control that must be refused with exactly its status 5 # and reason and must keep nothing (no stored patch, no staging folder, no work folder), and a 6 # matching positive that is accepted. Then the read routes, the interplane patch program against 7 # this forged, the imported proposals (SPEC prstore/r1 extension: item folders planted in the layout 8 # tools/ghimport writes, read back through every page, document and raw route, never writable by a 9 # POST; the list's count, states and damaged lines; diff_unavailable and the marker of a diff over 16 MiB; 10 # thread_truncated and the document budget; the id guard of the upload), and the mutants: each removes one guard from the test copy and 11 # must make the control that names it fail. 12 # Usage: bash patch/tests/run.sh (PATCH_TEST_CORES, default 2; PATCH_TEST_PORT, default 18487; 13 # KEEP=1 keeps the temp folder). Exit 0 only when every check passed and every mutant was killed. 14 . "$(dirname "$0")/lib.sh" 15 start 16 REPOF=$OWNER/fixrepo 17 N=0 18 # fresh NAME: a clone with one small text commit that no other test made (so its statement is new) 19 fresh() { N=$((N+1)); newclone "$1" && commitf "$T/$1" "notes/n$N.txt" "line $N" "note $N"; } 20 # std: a new one-commit patch with its own title, signed by the signed-in key 21 std() { fresh w; mkmbox "$T/w" origin/main; TITLE="Patch $N"; DESC="Description $N."; sigmake; } 22 # isref STATUS REASON: the last upload was refused exactly so and kept nothing 23 isref() { [ "$C" = "$1" ] && [ "$(reason)" = "$2" ] && [ "$(kept)" = "$KEPT" ] && [ "$(staged)" = 0 ] && [ "$(tmpleft)" = 0 ]; } 24 25 # ---- the negative controls, each a function that sends one upload: C is the status, WANT and WHY 26 # what a correct forge answers 27 n_unsigned() { std; s=$SES; SES=; C=$(upload); SES=$s; WANT=403; WHY="sign in first: this request carries no session"; } 28 n_csrf_stale() { std; t=$TOK; TOK=$OLDTOK; C=$(upload); TOK=$t; WANT=403; WHY="missing or wrong CSRF token"; } 29 n_csrf_foreign() { std; t=$TOK; TOK=$TOK2; C=$(upload); TOK=$t; WANT=403; WHY="missing or wrong CSRF token"; } 30 n_sig_forged() { # one letter of the armored signature's last full line is changed 31 std; python3 - "$SIGF" <<'EOF' 32 import sys 33 p = sys.argv[1]; L = open(p).read().split('\n'); i = len(L) - 4 34 c = L[i][10]; L[i] = L[i][:10] + ('A' if c != 'A' else 'B') + L[i][11:] 35 open(p, 'w').write('\n'.join(L)) 36 EOF 37 C=$(upload); WANT=403; WHY="the signature does not verify for this session's key and this patch"; } 38 n_sig_other_text() { std; t=$TITLE; TITLE="another title"; sigmake; TITLE=$t; C=$(upload); WANT=403; WHY="the signature does not verify for this session's key and this patch"; } 39 n_sig_other_key() { std; sigmake "$T/k3"; C=$(upload); WANT=403; WHY="the signature does not verify for this session's key and this patch"; } 40 n_base_unknown() { std; BASE=`1234567890123456789012345678901234567890`; sigmake; C=$(upload); WANT=422; WHY="unknown base: the repository has no such commit"; } 41 n_base_side() { N=$((N+1)); newclone w origin/side; commitf "$T/w" "notes/n$N.txt" "line $N" "note $N"; mkmbox "$T/w" origin/side 42 TITLE="Patch $N"; DESC=; sigmake; C=$(upload); WANT=422; WHY="base is not reachable from the repository's main branch"; } 43 n_mbox_big() { # one commit adding 21500 lines of 100 digits: the mbox is over 2 MiB, and its base64 form stays under 44 # the 3 MiB body the route reads (a larger mbox is refused before any handler, 413 with no reason) 45 N=$((N+1)); newclone w; yes `0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789` | head -n 21500 > "$T/w/big$N.txt" 46 G -C "$T/w" add -A; G -C "$T/w" commit -q -m "big $N"; mkmbox "$T/w" origin/main 47 m=$(stat -c %s "$MBOX"); [ "$m" -gt `2097152` ] && [ "$m" -lt `2300000` ] || bad "FIXTURE: the big mbox is $m bytes, not between 2 MiB and `2300000`" 48 TITLE="Big $N"; DESC=; sigmake; C=$(upload); WANT=413; WHY="the mbox is larger than `2097152` bytes"; } 49 n_commits_101() { N=$((N+1)); newclone w; for i in $(seq 101); do commitf "$T/w" "many/m$N.txt" "$i" "c $i"; done; mkmbox "$T/w" origin/main 50 TITLE="Many $N"; DESC=; sigmake; C=$(upload); WANT=413; WHY="the mbox holds more than 100 commits"; } 51 n_noapply() { # a patch made on main, sent with the first commit as its base: the context is not there 52 N=$((N+1)); newclone w; sed -i 's/^four$/FOUR '"$N"'/' "$T/w/src/a.txt"; G -C "$T/w" commit -q -am "edit four $N"; mkmbox "$T/w" origin/main 53 BASE=$A; TITLE="Edit $N"; DESC=; sigmake; C=$(upload); WANT=422; WHY="the mbox does not apply cleanly on base"; } 54 n_path_out() { std; sed -i "s|^diff --git a/notes/n$N.txt b/notes/n$N.txt|diff --git a/../n$N.txt b/../n$N.txt|; s|^+++ b/notes/n$N.txt|+++ b/../n$N.txt|" "$MBOX" 55 grep -q '^diff --git a/\.\./' "$MBOX" || bad "FIXTURE: the path was not rewritten" 56 sigmake; C=$(upload); WANT=422; WHY="a patch names a path outside the repository"; } 57 n_path_abs() { std; sed -i "s|^diff --git a/notes/n$N.txt b/notes/n$N.txt|diff --git a//tmp/n$N.txt b//tmp/n$N.txt|; s|^+++ b/notes/n$N.txt|+++ b//tmp/n$N.txt|" "$MBOX" 58 grep -q '^diff --git a//tmp/' "$MBOX" || bad "FIXTURE: the path was not rewritten" 59 sigmake; C=$(upload); WANT=422; WHY="a patch names a path outside the repository"; } 60 n_path_rename() { N=$((N+1)); newclone w; G -C "$T/w" mv docs/note.md "docs/moved$N.md"; G -C "$T/w" commit -q -m "move $N"; mkmbox "$T/w" origin/main 61 sed -i "s|^rename to docs/moved$N.md|rename to ../moved$N.md|" "$MBOX"; grep -q '^rename to \.\./' "$MBOX" || bad "FIXTURE: no rename line" 62 TITLE="Move $N"; DESC=; sigmake; C=$(upload); WANT=422; WHY="a patch names a path outside the repository"; } 63 n_copy_header() { 64 N=$((N+1)) 65 newclone w 66 cp "$T/w/docs/note.md" "$T/w/docs/copy.md" 67 G -C "$T/w" add docs/copy.md 68 G -C "$T/w" commit -q -m "copy fixture note" 69 mkmbox "$T/w" origin/main 70 G -C "$T/w" format-patch --stdout --no-signature --find-copies-harder origin/main..HEAD > "$MBOX" 71 grep -q '^copy to docs/copy.md$' "$MBOX" || bad "FIXTURE: expected a copy header" 72 if [ "$#" != 0 ]; then 73 encmail "$1" 74 fi 75 TITLE="Copy fixture" 76 DESC= 77 sigmake 78 C=$(upload) 79 WANT=422 80 WHY="patches with copy headers are not accepted" 81 } 82 n_path_plain() { # a plain diff without the git header: only git's own apply sees the path 83 std; sed -i "/^diff --git /d; /^new file mode /d; /^index /d; s|^+++ b/notes/n$N.txt|+++ b/../n$N.txt|" "$MBOX" 84 sigmake; C=$(upload); WANT=422; WHY="the mbox does not apply cleanly on base"; } 85 n_path_quoted() { # a C-quoted header ("a/\056\056/x" is a/../x): the header scan sees no literal .., git apply refuses it 86 std; sed -i 's|^diff --git a/notes/n'"$N"'.txt b/notes/n'"$N"'.txt|diff --git "a/\\056\\056/n'"$N"'.txt" "b/\\056\\056/n'"$N"'.txt"|; s|^+++ b/notes/n'"$N"'.txt|+++ "b/\\056\\056/n'"$N"'.txt"|' "$MBOX" 87 grep -qF "diff --git \"a/\\056\\056/n$N.txt\"" "$MBOX" || bad "FIXTURE: the path was not quoted" 88 sigmake; C=$(upload); WANT=422; WHY="the mbox does not apply cleanly on base"; } 89 n_binary() { N=$((N+1)); newclone w; printf 'bin\000\001\002%s' "$N" > "$T/w/blob$N.dat"; G -C "$T/w" add -A; G -C "$T/w" commit -q -m "binary $N"; mkmbox "$T/w" origin/main 90 grep -q '^GIT binary patch$' "$MBOX" || bad "FIXTURE: no binary patch in the mbox" 91 TITLE="Binary $N"; DESC=; sigmake; C=$(upload); WANT=422; WHY="binary patches are not accepted"; } 92 # encmail CTE: $MBOX (one commit) with its mail body sent in that Content-Transfer-Encoding (base64 or 93 # quoted-printable); git am decodes it before it applies, the mbox as sent shows none of the diff's lines 94 encmail() { python3 - "$MBOX" "$1" <<'EOF' 95 import sys, base64, quopri 96 p, cte = sys.argv[1], sys.argv[2] 97 h, b = open(p, 'rb').read().split(b'\n\n', 1) 98 h = [l for l in h.split(b'\n') if not l.lower().startswith((b'content-transfer-encoding:', b'mime-version:', b'content-type:'))] 99 h += [b'MIME-Version: 1.0', b'Content-Type: text/plain; charset=UTF-8', b'Content-Transfer-Encoding: ' + cte.encode()] 100 b = base64.encodebytes(b) if cte == 'base64' else quopri.encodestring(b) 101 open(p, 'wb').write(b'\n'.join(h) + b'\n\n' + b) 102 EOF 103 } 104 n_binary_b64() { # the binary patch with its mail body base64: only git's own numstat after the apply sees it 105 N=$((N+1)); newclone w; printf 'bin\000\001\002%s' "$N" > "$T/w/blob$N.dat"; G -C "$T/w" add -A; G -C "$T/w" commit -q -m "binary $N"; mkmbox "$T/w" origin/main 106 grep -q '^GIT binary patch$' "$MBOX" || bad "FIXTURE: no binary patch in the mbox" 107 encmail base64; ! grep -q '^GIT binary patch$\|^Binary files \|^diff --git ' "$MBOX" || bad "FIXTURE: the base64 mail still shows a diff line" 108 TITLE="Binary base64 $N"; DESC=; sigmake; C=$(upload); WANT=422; WHY="binary patches are not accepted"; } 109 n_binary_noapply() { # a binary file and an edit whose context the base lacks: the early scan refuses it before any git run 110 N=$((N+1)); newclone w; printf 'bin\000\001\002%s' "$N" > "$T/w/blob$N.dat"; sed -i 's/^four$/FOUR '"$N"'/' "$T/w/src/a.txt" 111 G -C "$T/w" add -A; G -C "$T/w" commit -q -m "binary and edit $N"; mkmbox "$T/w" origin/main 112 grep -q '^GIT binary patch$' "$MBOX" || bad "FIXTURE: no binary patch in the mbox" 113 BASE=$A; TITLE="Binary edit $N"; DESC=; sigmake; C=$(upload); WANT=422; WHY="binary patches are not accepted"; } 114 EMPTYT=`4b825dc642cb6eb9a060e54bf8d69288fbee4904` # the empty tree: git --attr-source=$EMPTYT reads no attributes 115 NOMARK='^GIT binary patch$\|^Binary files ' 116 tab=$'\t' 117 # n_binary_attr: the commit adds .gitattributes "*.dat diff" and a .dat file holding NUL bytes. The sender's 118 # git reads that attribute and formats the file as text (no marker in the mbox, the NUL bytes raw in it), and 119 # so would the forge's git (numstat counts lines) if it read the patch's attributes. The forge's git runs with 120 # --attr-source=, so its numstat marks the file binary (the byte check would refuse it as well) 121 n_binary_attr() { N=$((N+1)); newclone w; printf '*.dat diff\n' > "$T/w/.gitattributes"; printf 'bin\000\001\002\377zz %s\n' "$N" > "$T/w/blob$N.dat" 122 G -C "$T/w" add -A; G -C "$T/w" commit -q -m "attr binary $N"; mkmbox "$T/w" origin/main 123 ! grep -aq "$NOMARK" "$MBOX" && [ "$(tr -cd '\000' < "$MBOX" | wc -c)" -gt 0 ] || bad "FIXTURE: the attribute mbox shows a binary marker or holds no NUL byte" 124 G -C "$T/w" diff --numstat "$BASE" HEAD | grep -qx "1${tab}0${tab}blob$N.dat" || bad "FIXTURE: with its attribute git does not count blob$N.dat as text" 125 G -C "$T/w" --attr-source=$EMPTYT diff --numstat "$BASE" HEAD | grep -qx -- "-${tab}-${tab}blob$N.dat" || bad "FIXTURE: without attributes git does not mark blob$N.dat binary" 126 TITLE="Attr binary $N"; DESC=; sigmake; C=$(upload); WANT=422; WHY="binary patches are not accepted"; } 127 # n_binary_late: a file whose first NUL byte is after byte 8000 (8200 bytes of "a", then NUL bytes). git's 128 # binary test reads only the first 8000 bytes, so git calls it text everywhere (no marker in the mbox, numstat 129 # counts lines); only the byte check of the combined diff after the apply refuses it 130 n_binary_late() { N=$((N+1)); newclone w; { head -c 8200 /dev/zero | tr '\0' a; printf '\000\001\002\377 tail %s\n' "$N"; } > "$T/w/late$N.dat" 131 G -C "$T/w" add -A; G -C "$T/w" commit -q -m "late NUL $N"; mkmbox "$T/w" origin/main 132 ! grep -aq "$NOMARK" "$MBOX" && [ "$(tr -cd '\000' < "$MBOX" | wc -c)" -gt 0 ] || bad "FIXTURE: the late-NUL mbox shows a binary marker or holds no NUL byte" 133 G -C "$T/w" --attr-source=$EMPTYT diff --numstat "$BASE" HEAD | grep -qx "1${tab}0${tab}late$N.dat" || bad "FIXTURE: git does not count late$N.dat as text" 134 TITLE="Late NUL $N"; DESC=; sigmake; C=$(upload); WANT=422; WHY="binary patches are not accepted"; } 135 # p_attr_text: the commit adds .gitattributes ("*.dat diff" and "*.txt -diff") and text files blob.dat and 136 # plain.txt; the mbox is made with no attributes read (the sender's own git would mark plain.txt binary). It is 137 # accepted and the stored diff is git's diff with no attributes (the .txt's line is in it, its -diff is not 138 # read); a forge that read the patch's attributes would refuse it as binary. C=ok when so; WANT=ok. 139 p_attr_text() { N=$((N+1)); newclone w; printf '*.dat diff\n*.txt -diff\n' > "$T/w/.gitattributes"; printf 'text %s\n' "$N" > "$T/w/blob$N.dat"; printf 'plain %s\n' "$N" > "$T/w/plain$N.txt" 140 G -C "$T/w" add -A; G -C "$T/w" commit -q -m "attr text $N"; mkmbox "$T/w" origin/main 141 git -C "$T/w" --attr-source=$EMPTYT format-patch --stdout "$BASE..HEAD" > "$MBOX" 142 git -C "$T/w" diff "$BASE" HEAD | grep -qx "Binary files /dev/null and b/plain$N.txt differ" || bad "FIXTURE: -diff does not mark plain$N.txt binary in the sender's own diff" 143 ! grep -aq "$NOMARK" "$MBOX" || bad "FIXTURE: the attribute text mbox shows a binary marker" 144 git -C "$T/w" --attr-source=$EMPTYT diff --full-index -M "$BASE" HEAD > "$T/attr.oracle" 145 TITLE="Attr text $N"; DESC=; sigmake; C=$(upload); ID=$(newid) 146 if [ "$C" = 201 ] && [ "$(staged)" = 0 ] && [ "$(tmpleft)" = 0 ] && grep -qx "+plain $N" "$T/attr.oracle" \ 147 && cmp -s "$T/data/patches/$OWNER/fixrepo/$ID/diff" "$T/attr.oracle"; then C=ok; fi 148 WANT=ok; WHY=; KEPT=$(kept); } 149 n_submodule() { N=$((N+1)); newclone w; G -C "$T/w" update-index --add --cacheinfo "160000,$A,sub$N"; G -C "$T/w" commit -q -m "submodule $N"; mkmbox "$T/w" origin/main 150 grep -q '^new file mode 160000$' "$MBOX" || bad "FIXTURE: no submodule entry in the mbox" 151 TITLE="Submodule $N"; DESC=; sigmake; C=$(upload); WANT=422; WHY="the patch adds a submodule"; } 152 n_title_long() { std; TITLE=$(printf '%257s' '' | tr ' ' t); sigmake; C=$(upload); WANT=400; WHY="the title must be 1 to 256 bytes of UTF-8 text on one line"; } 153 n_title_empty() { std; TITLE=; sigmake; C=$(upload); WANT=400; WHY="the title must be 1 to 256 bytes of UTF-8 text on one line"; } 154 n_title_lines() { std; TITLE=$'two\nlines'; sigmake; C=$(upload); WANT=400; WHY="the title must be 1 to 256 bytes of UTF-8 text on one line"; } 155 n_title_utf8() { std; TITLE=$'bad \xff byte'; sigmake; C=$(upload); WANT=400; WHY="the title must be 1 to 256 bytes of UTF-8 text on one line"; } 156 n_desc_long() { std; DESC=$(printf '%60001s' '' | tr ' ' d); sigmake; C=$(upload); WANT=400; WHY="the description must be at most 60000 bytes of UTF-8 text without control bytes"; } 157 n_desc_ctl() { std; DESC=$'bell \a here'; sigmake; C=$(upload); WANT=400; WHY="the description must be at most 60000 bytes of UTF-8 text without control bytes"; } 158 # n_repo_field: the statement is signed for this repository, the repo field names another (only the field check sees it) 159 n_repo_field() { std; r=$REPOF; REPOF=$OWNER/nostore; C=$(upload); REPOF=$r; WANT=400; WHY="the repo field does not name this repository"; } 160 # n_repo_signed: the statement and the repo field both name another repository 161 n_repo_signed() { std; r=$REPOF; REPOF=$OWNER/nostore; sigmake; C=$(upload); REPOF=$r; WANT=400; WHY="the repo field does not name this repository"; } 162 n_replay() { C=$(upload); WANT=200; WHY=; } # the last accepted upload again (not a refusal: see below) 163 RATE="too many writes from this address or key; wait a minute" 164 # minute: wait until at most second 20 of a wall-clock minute, so a flood and its count sit in one minute of the 165 # per-key counter (social/30store.om soratev and sordok count a key's writes per minute, ts / 60) 166 minute() { s=$(( $(date +%s) % 60 )); [ "$s" -le 20 ] || sleep $((60 - s)); } 167 # events DID: the events of DID in the social log in the current minute (each counts as a write of that key) 168 events() { m=$(( $(date +%s) / 60 )); grep -F "\"did\":\"$1\"" "$T/social/social.log" | sed -n 's/^{"seq":[0-9]*,"ts":\([0-9]*\),.*/\1/p' | awk -v m="$m" 'int($1 / 60) == m' | wc -l; } 169 # n_perkey: 30 writes of the signed-in key in one minute, each from its own address (so no address limit is 170 # reached), then its signed upload from one more address 171 n_perkey() { minute; std; b=$BASE; BASE=zz; for i in $(seq 30); do IP=10.9.$((N % 200)).$i; upload > /dev/null; done 172 BASE=$b; IP=10.9.250.$((N % 200)); C=$(upload); WANT=429; WHY=$RATE; } 173 # n_perip: from the signed-in key's address, 20 writes by another key's session (SESA, TOKA) and 10 by this key, 174 # each key under its own limit, then this key's signed upload from that address 175 n_perip() { std; s=$SES; t=$TOK; b=$BASE; BASE=zz; SES=$SESA; TOK=$TOKA; for i in $(seq 20); do upload > /dev/null; done 176 SES=$s; TOK=$t; for i in $(seq 10); do upload > /dev/null; done; BASE=$b; C=$(upload); WANT=429; WHY=$RATE; } 177 178 neg() { # LABEL FUNCTION 179 KEPT=$(kept); "$2" 180 if isref "$WANT" "$WHY"; then ok "NEG $1: $C \"$WHY\", nothing kept" 181 else bad "NEG $1: want $WANT \"$WHY\" and $KEPT kept; got $C \"$(head -c 160 "$T/body" | tr '\n' ' ')\" kept $(kept) staged $(staged) work $(tmpleft)"; fi 182 } 183 pos() { KEPT=$(kept); C=$(upload "${@:2}"); accepted "$C" "$1"; } 184 185 # ---- keys and sessions. Each key stays under the gate's 30 writes a minute; addresses differ. 186 for k in k1 k2 k3 k4 k5 k6 k7 k8 k9 kp1 kp2; do newkey $k; done 187 signin k1 10.1.0.1 || exit 1; OLDSES=$SES; OLDTOK=$TOK 188 signin k3 10.1.0.3 || exit 1; SES3=$SES; TOK2=$TOK 189 signin k1 10.1.0.1 || exit 1; SES1=$SES; TOK1=$TOK; DID1=$DID 190 [ "$OLDTOK" != "$TOK1" ] && ok "a new session has a new CSRF token" || bad "the CSRF token did not change with the session" 191 192 echo "== session and CSRF" 193 neg "unsigned upload (no session)" n_unsigned 194 neg "stale CSRF token (of this key's earlier session)" n_csrf_stale 195 neg "foreign CSRF token (of another key's session)" n_csrf_foreign 196 std; pos "the same kind of upload with its session and token" 197 FIRST=$ID; FIRSTMB=$MBOX; FIRSTBASE=$BASE; FIRSTTITLE=$TITLE; FIRSTDESC=$DESC; cp "$T/stmt" "$T/first.stmt"; cp "$SIGF" "$T/first.sig" 198 199 echo "== replay of the same statement" 200 KEPT=$(kept); n_replay 201 if [ "$C" = 200 ] && [ "$(head -1 "$T/body")" = exists ] && [ "$(newid)" = "$FIRST" ] && [ "$(kept)" = "$KEPT" ] && [ "$(staged)" = 0 ] && [ "$(tmpleft)" = 0 ] \ 202 && [ "$(grep -c "^$FIRST\$" "$T/data/patches/$OWNER/fixrepo/index")" = 1 ]; then 203 ok "NEG replay: 200 exists with the first id $FIRST, nothing new kept, one index line" 204 else bad "NEG replay: got $C \"$(head -c 120 "$T/body" | tr '\n' ' ')\" kept $(kept) (was $KEPT)"; fi 205 206 echo "== signature" 207 neg "forged signature (one letter changed)" n_sig_forged 208 neg "signature over another title" n_sig_other_text 209 neg "signature by another key than the session's" n_sig_other_key 210 std; pos "the same kind of upload signed by the session's key" 211 212 echo "== base" 213 neg "unknown base" n_base_unknown 214 neg "base on a branch that is not main" n_base_side 215 std; pos "the same kind of upload with a base on main" 216 N=$((N+1)); newclone w "$A"; commitf "$T/w" "notes/n$N.txt" "line $N" "note $N"; mkmbox "$T/w" "$A"; TITLE="Old base $N"; DESC=; sigmake 217 pos "a base that is an older commit of main" 218 219 signin k2 10.1.0.2 || exit 1 220 echo "== sizes" 221 neg "mbox over 2 MiB" n_mbox_big 222 N=$((N+1)); newclone w; seq 1 250000 > "$T/w/large$N.txt"; G -C "$T/w" add -A; G -C "$T/w" commit -q -m "large $N"; mkmbox "$T/w" origin/main 223 TITLE="Large $N"; DESC=; sigmake; echo "the large mbox is $(stat -c %s "$MBOX") bytes" 224 pos "an mbox of more than 1.5 MiB and under 2 MiB" 225 neg "101 commits" n_commits_101 226 N=$((N+1)); newclone w; for i in $(seq 100); do commitf "$T/w" "many/m$N.txt" "$i" "c $i"; done; mkmbox "$T/w" origin/main; TITLE="Hundred $N"; DESC=; sigmake 227 pos "100 commits" 228 curl -s -H 'Accept: application/json' "$B$R/patches/$ID" | grep -q '"commits":100,' && ok "the 100-commit patch is stored as 100 commits" || bad "commit count of the 100-commit patch" 229 neg "title of 257 bytes" n_title_long 230 neg "empty title" n_title_empty 231 neg "title of two lines" n_title_lines 232 neg "title that is not UTF-8" n_title_utf8 233 std; TITLE=$(printf '%254s' '' | tr ' ' t)é; sigmake; pos "a title of exactly 256 bytes" 234 neg "description of 60001 bytes" n_desc_long 235 neg "description with a control byte" n_desc_ctl 236 std; DESC=$(printf '%59998s' '' | tr ' ' d)$'\n\t'; sigmake; pos "a description of exactly 60000 bytes with a tab and a line feed" 237 # a body over the 3 MiB the route reads is refused before any handler: 413, nothing kept 238 KEPT=$(kept); head -c `3200000` /dev/zero | tr '\0' a > "$T/huge" 239 C=$(curl -s -o "$T/body" -w '%{http_code}' -X POST -H "Cookie: __Host-forge_session=$SES" --data-binary "@$T/huge" "$B$R/patches/new") 240 [ "$C" = 413 ] && [ "$(kept)" = "$KEPT" ] && alive && ok "NEG a body over 3 MiB: 413 before any handler, nothing kept" || bad "NEG body over 3 MiB: $C" 241 # another POST keeps its 64 KiB body cap 242 head -c 70000 /dev/zero | tr '\0' a > "$T/mid" 243 C=$(curl -s -o /dev/null -w '%{http_code}' -X POST -H "Cookie: __Host-forge_session=$SES" --data-binary "@$T/mid" "$B$R/star") 244 check "$C" 413 "NEG a 70000-byte body on another POST route is still refused" 245 for route in "$R/extra/patches/new" "/$OWNER//patches/new"; do 246 C=$(curl -s -o /dev/null -w '%{http_code}' -X POST --data-binary "@$T/mid" "$B$route") 247 check "$C" 413 "only the exact patch upload route gets the larger request limit ($route)" 248 done 249 250 signin k4 10.1.0.4 || exit 1 251 echo "== the mbox applies" 252 neg "mbox that does not apply on its base" n_noapply 253 BASE=$MAIN; sigmake; pos "the same mbox with the base it was made on" 254 neg "path outside the repository (.. in the git diff header)" n_path_out 255 neg "absolute path in the git diff header" n_path_abs 256 neg "rename to a path outside the repository" n_path_rename 257 neg "Git copy headers are refused" n_copy_header 258 n_copy_encoded() { n_copy_header base64; } 259 neg "Git copy headers are refused after mail decoding" n_copy_encoded 260 neg "path outside the repository in a plain diff (refused by git apply)" n_path_plain 261 neg "C-quoted path outside the repository (\"a/\\056\\056/x\", refused by git apply)" n_path_quoted 262 std; pos "the same kind of patch with its path inside the repository" 263 neg "binary patch" n_binary 264 N=$((N+1)); newclone w; printf 'text %s\n' "$N" > "$T/w/blob$N.dat"; G -C "$T/w" add -A; G -C "$T/w" commit -q -m "text $N"; mkmbox "$T/w" origin/main; TITLE="Text $N"; DESC=; sigmake 265 pos "the same file as text" 266 neg "binary patch in a base64 mail body (git numstat after the apply)" n_binary_b64 267 neg "binary patch that also does not apply on its base (the early scan, before any git run)" n_binary_noapply 268 signin k7 10.1.0.7 || exit 1 # the binary controls below and the rest of this part: k4 has used most of its 30 writes a minute 269 neg "a .gitattributes (*.dat diff) that makes git call a file with NUL bytes text (no attribute file of the patch is read)" n_binary_attr 270 neg "a file whose first NUL byte is after byte 8000 (git's binary test misses it; the byte check of the applied diff)" n_binary_late 271 K0=$(kept); p_attr_text 272 [ "$C" = ok ] && [ "$(kept)" = $((K0 + 1)) ] && ok "POS a .gitattributes (*.dat diff, *.txt -diff) with text files: 201, the stored diff is git's diff without attributes (the -diff file's line is in it)" \ 273 || bad "POS attribute text: $C \"$(head -c 120 "$T/body" | tr '\n' ' ')\" kept $(kept) (was $K0)" 274 N=$((N+1)); newclone w; { head -c 8200 /dev/zero | tr '\0' a; printf '\001\002\377 tail %s\n' "$N"; } > "$T/w/late$N.dat"; G -C "$T/w" add -A; G -C "$T/w" commit -q -m "late text $N" 275 mkmbox "$T/w" origin/main; TITLE="Late text $N"; DESC=; sigmake 276 pos "the late shape without the NUL byte (8200 bytes of a, then bytes 1, 2 and 377)" 277 LC_ALL=C grep -aqxF "+$(head -c 8200 /dev/zero | tr '\0' a)"$'\001\002\377'" tail $N" "$T/data/patches/$OWNER/fixrepo/$ID/diff" && ok "the stored diff holds the late line as sent" || bad "late text: stored diff lacks the line" 278 N=$((N+1)); newclone w; printf 'text=%s\n' "$N" > "$T/w/blob$N.dat"; G -C "$T/w" add -A; G -C "$T/w" commit -q -m "text $N"; mkmbox "$T/w" origin/main; encmail quoted-printable 279 grep -q '^Content-Transfer-Encoding: quoted-printable$' "$MBOX" && grep -q '^+text=3D' "$MBOX" || bad "FIXTURE: the mail body is not quoted-printable" 280 TITLE="Text QP $N"; DESC=; sigmake 281 pos "the same file as text in a quoted-printable mail body" 282 grep -qx "+text=$N" "$T/data/patches/$OWNER/fixrepo/$ID/diff" && ok "the stored diff holds the decoded line (git am decoded the quoted-printable body)" \ 283 || bad "QP stored diff: $(grep '^+text' "$T/data/patches/$OWNER/fixrepo/$ID/diff")" 284 neg "submodule entry" n_submodule 285 neg "repo field naming another repository (the statement signed for this one)" n_repo_field 286 neg "repo field and signed statement both naming another repository" n_repo_signed 287 # a symbolic link and a deep folder are ordinary git content: accepted, and the work folder is gone 288 N=$((N+1)); newclone w; ln -s ../../../etc/passwd "$T/w/link$N"; mkdir -p "$T/w/$(printf 'd/%.0s' $(seq 40))"; echo deep > "$T/w/$(printf 'd/%.0s' $(seq 40))f$N" 289 G -C "$T/w" add -A; G -C "$T/w" commit -q -m "link and deep $N"; mkmbox "$T/w" origin/main; TITLE="Link $N"; DESC=; sigmake 290 pos "a symbolic link and a file 40 folders deep" 291 [ -z "$(find "$T/data" -type l)" ] && ok "no symbolic link was left in the data folder" || bad "a symbolic link exists under the data folder" 292 293 echo "== the form and the repository" 294 UPATH=/$OWNER/nope/patches/new; std; KEPT=$(kept); C=$(upload) 295 isref 404 "no such public repository" && ok "NEG a repository outside the public list: 404 after the gate" || bad "NEG unlisted repository: $C $(reason)" 296 s=$SES; SES=; C=$(upload); SES=$s 297 isref 403 "sign in first: this request carries no session" && ok "NEG unlisted repository, unsigned: the gate answers first (403)" || bad "NEG unlisted unsigned: $C $(reason)" 298 # the catalog serves a project only while its repo.git is there when the list is loaded, so the store's nostore 299 # repository is moved away while the server runs (and put back): the row is still listed, its git store is gone 300 check "$(code GET "/$OWNER/nostore/patches")" 200 "the second project's patch list answers before its git store is moved away" 301 mv "$T/store/projects/nostore/repo.git" "$T/nostore.away" 302 UPATH=/$OWNER/nostore/patches/new; REPOF=$OWNER/nostore; sigmake; C=$(upload); REPOF=$OWNER/fixrepo 303 isref 404 "this repository has no git store on this forge" && ok "NEG a listed repository whose git store is gone: 404" || bad "NEG no git store: $C $(reason)" 304 mv "$T/nostore.away" "$T/store/projects/nostore/repo.git" 305 UPATH= 306 form() { : > "$T/body"; curl -s -o "$T/body" -w '%{http_code}' -X POST -H "X-Real-IP: $IP" -H "Cookie: __Host-forge_session=$SES" "$@" "$B$R/patches/new"; } 307 F=(--data-urlencode "csrf=$TOK" --data-urlencode "repo=$REPOF" --data-urlencode "base=$MAIN" --data-urlencode "title=t" --data-urlencode "description=" --data-urlencode "sig@$SIGF") 308 KEPT=$(kept) 309 C=$(form "${F[@]}"); isref 400 "the body is not the patch form: fields csrf, repo, base, title, description, mbox and sig, each once" && ok "NEG a form without the mbox field: 400" || bad "NEG missing field: $C $(reason)" 310 C=$(form "${F[@]}" --data-urlencode "mbox=AAAA" --data-urlencode "mbox=AAAA"); isref 400 "the body is not the patch form: fields csrf, repo, base, title, description, mbox and sig, each once" && ok "NEG a field twice: 400" || bad "NEG field twice: $C $(reason)" 311 C=$(form "${F[@]}" --data-urlencode "mbox=AAAA" --data-urlencode "extra=1"); isref 400 "the body is not the patch form: fields csrf, repo, base, title, description, mbox and sig, each once" && ok "NEG an unknown field: 400" || bad "NEG unknown field: $C $(reason)" 312 C=$(form "${F[@]}" --data-urlencode "mbox=not base64!"); isref 400 "the mbox field is not base64url without padding" && ok "NEG an mbox that is not base64url: 400" || bad "NEG not base64url: $C $(reason)" 313 C=$(form "${F[@]}" --data-urlencode "mbox=QQ=="); isref 400 "the mbox field is not base64url without padding" && ok "NEG a padded mbox: 400" || bad "NEG padded: $C $(reason)" 314 C=$(form "${F[@]}" --data-urlencode "mbox=QR"); isref 400 "the mbox field is not base64url without padding" && ok "NEG an mbox with unused bits set: 400" || bad "NEG unused bits: $C $(reason)" 315 C=$(form "${F[@]}" --data-urlencode "mbox=aGVsbG8K"); isref 400 "the mbox is not git format-patch output" && ok "NEG an mbox that is not format-patch output: 400" || bad "NEG not format-patch: $C $(reason)" 316 F[5]="base=${MAIN:0:39}G" 317 C=$(form "${F[@]}" --data-urlencode "mbox=AAAA"); isref 400 "base is not a commit id of 40 lowercase hex digits" && ok "NEG a base that is not 40 hex: 400" || bad "NEG bad base: $C $(reason)" 318 std; echo "not a signature" > "$T/bad.sig"; SIGF=$T/bad.sig; KEPT=$(kept); C=$(upload) 319 isref 400 "the sig field is not an armored SSH signature" && ok "NEG a sig that is not an armored signature: 400" || bad "NEG bad sig field: $C $(reason)" 320 sigmake; C=$(upload -H 'Origin: https://evil.example'); [ "$C" = 403 ] && [ "$(kept)" = "$KEPT" ] && ok "NEG an upload naming another Origin: 403" || bad "NEG other origin: $C" 321 C=$(code POST "$R/patches" -H "Cookie: __Host-forge_session=$SES" -d x=1); check "$C" 405 "NEG POST to the list" 322 C=$(code POST "$R/patches/$FIRST" -H "Cookie: __Host-forge_session=$SES" -d x=1); check "$C" 405 "NEG POST to a patch page" 323 alive && ok "forged is still running after every refusal" || { bad "forged ended"; start; } 324 325 echo "== read routes" 326 SD=$T/data/patches/$OWNER/fixrepo/$FIRST 327 cmp -s "$SD/mbox" "$FIRSTMB" && ok "the stored mbox is byte-equal to the mbox that was sent" || bad "stored mbox differs" 328 cmp -s "$SD/statement" "$T/first.stmt" && ok "the stored statement is the signed statement" || bad "stored statement differs" 329 cmp -s "$SD/signature" "$T/first.sig" && ok "the stored signature is the signature that was sent" || bad "stored signature differs" 330 [ "$(cat "$SD/status")" = open ] && ok "status file says open" || bad "status file" 331 [ "$(sha < "$T/first.stmt" | cut -c1-16)" = "$FIRST" ] && ok "the id is the first 16 hex of the statement's SHA-256" || bad "id is not sha256(statement)[0:16]" 332 printf '%s' "$(cat "$T/first.stmt")" | ssh-keygen -Y check-novalidate -n interplane-patch -f "$T/k1.pub" -s "$SD/signature" > /dev/null 2>&1 < "$T/first.stmt" \ 333 && ok "ssh-keygen verifies the stored signature over the stored statement with the author's key" || bad "ssh-keygen does not verify the stored pair" 334 [ "$(ls "$SD" | tr '\n' ' ')" = "description diff head mbox meta signature statement status title " ] && ok "the patch folder holds exactly the nine files" || bad "patch folder: $(ls "$SD" | tr '\n' ' ')" 335 # oracle: git am of the raw route onto the base in a fresh clone, with the forge's committer, gives the stored head 336 curl -s -o "$T/raw.patch" -w '%{http_code}' "$B$R/patches/$FIRST.patch" > "$T/rc" 337 [ "$(cat "$T/rc")" = 200 ] && cmp -s "$T/raw.patch" "$FIRSTMB" && ok "GET .patch is byte-equal to the mbox that was sent" || bad "raw .patch route" 338 rm -rf "$T/am"; git clone -q "$GITS" "$T/am"; git -C "$T/am" checkout -q --detach "$FIRSTBASE" 339 git -C "$T/am" -c user.name=interplane-forge -c user.email=forge@interplane.io am -q --committer-date-is-author-date "$T/raw.patch" 2> "$T/am.err" 340 [ "$(git -C "$T/am" rev-parse HEAD)" = "$(cat "$SD/head")" ] && ok "git am of the raw route onto the base in a fresh clone gives the stored head $(cut -c1-12 "$SD/head")" || bad "git am oracle: $(git -C "$T/am" rev-parse HEAD) is not $(cat "$SD/head") $(cat "$T/am.err")" 341 curl -s -o "$T/raw.diff" "$B$R/patches/$FIRST.diff" 342 git -C "$T/am" diff --full-index -M "$FIRSTBASE" HEAD > "$T/oracle.diff" 343 cmp -s "$T/raw.diff" "$T/oracle.diff" && ok "GET .diff equals git diff --full-index -M base head of that clone" || bad ".diff differs from the oracle" 344 grep -qi '^content-type: text/plain' <(curl -s -D- -o /dev/null "$B$R/patches/$FIRST.patch") && ok ".patch is text/plain" || bad ".patch content type" 345 # jsoncheck LABEL: forge/patch/1 of the first patch and every page of forge/patch-list/1, under both bases 346 jsoncheck() { 347 python3 - "$B" "$R" "$FIRST" "$DID1" "$FIRSTBASE" "$(cat "$SD/head")" "$(sha < "$FIRSTMB")" "$(stat -c %s "$FIRSTMB")" "$FIRSTTITLE" "$FIRSTDESC" "$(kept)" > "$T/json.out" 2>&1 <<'EOF' 348 import json, sys, urllib.request 349 B, R, ID, DID, BASE, HEAD, SHA, BYTES, TITLE, DESC, KEPT = sys.argv[1:] 350 def get(path, base='/'): 351 rq = urllib.request.Request(B + path, headers={'Accept': 'application/json', 'X-Forge-Base': base}) 352 with urllib.request.urlopen(rq) as r: 353 assert r.headers['Content-Type'] == 'application/json; charset=utf-8', r.headers['Content-Type'] 354 return json.loads(r.read().decode('utf-8')) 355 for base in ('/', '/forge/'): 356 p = base.rstrip('/') + R + '/patches/' + ID 357 d = get(R + '/patches/' + ID, base) 358 # the key set of SPEC-ext section 3: the same keys for a signed patch and an imported item, in this order 359 want = {'schema': 'forge/patch/1', 'base': base, 'owner': R.split('/')[1], 'repo': R.split('/')[2], 'id': ID, 'title': TITLE, 360 'description': DESC, 'status': 'open', 'state_derived': False, 'author': {'did': DID, 'name': None}, 'imported': None, 361 'base_commit': BASE, 'head_commit': HEAD, 'commits': 1, 'files': 1, 'bytes': int(BYTES), 'code': 'mbox', 'mbox_sha256': SHA, 362 'opened': None, 'closed': None, 'merge': None, 'labels': [], 'comments': [], 'thread_truncated': False, 'thread_reason': None, 363 'created': None, 'path': p, 'patch': p + '.patch', 'diff': p + '.diff', 'diff_unavailable': None, 'bundle': None} 364 assert list(d.keys()) == list(want.keys()), list(d.keys()) 365 created = d.pop('created'); want.pop('created') 366 assert len(created) == 20 and created.endswith('Z'), created 367 assert d == want, (d, want) 368 assert list(d['author'].keys()) == ['did', 'name'], d['author'] 369 rows = []; page = 1; l = None 370 while True: 371 l = get(R + '/patches?page=%d' % page, base) 372 assert l['schema'] == 'forge/patch-list/1' and l['base'] == base and l['page'] == page and l['per_page'] == 30, l 373 assert l['count'] == int(KEPT), (l['count'], KEPT) 374 assert list(l.keys()) == ['schema', 'base', 'owner', 'repo', 'page', 'per_page', 'count', 'states', 'damaged', 'patches', 'next', 'prev'], list(l.keys()) 375 # the listed items by state, on every page; here the store holds signed patches only: each counts as open, no index line is damaged 376 assert l['states'] == {'open': int(KEPT), 'closed': 0, 'merged': 0} and list(l['states'].keys()) == ['open', 'closed', 'merged'], l['states'] 377 assert l['damaged'] == 0 and type(l['damaged']) is int, l['damaged'] 378 assert len(l['patches']) <= 30 379 rows += l['patches'] 380 assert (l['prev'] is None) == (page == 1) 381 if l['next'] is None: break 382 assert l['next'] == base.rstrip('/') + R + '/patches?page=%d' % (page + 1), l['next'] 383 page += 1 384 assert len(rows) == int(KEPT), (len(rows), KEPT) 385 assert len(set(x['id'] for x in rows)) == len(rows) 386 assert rows[-1]['id'] == ID, 'the first patch is the last row (newest first)' 387 row = dict(rows[-1]) 388 assert list(row.keys()) == ['id', 'title', 'status', 'state_derived', 'author', 'imported', 'base_commit', 'head_commit', 'commits', 'files', 389 'bytes', 'code', 'created', 'comments_count', 'path', 'patch', 'diff', 'diff_unavailable', 'bundle'], list(row.keys()) 390 for k in ('schema', 'base', 'owner', 'repo', 'description', 'mbox_sha256', 'opened', 'closed', 'merge', 'labels', 'comments', 'thread_truncated', 'thread_reason'): want.pop(k) 391 rc = row.pop('created'); assert rc == created 392 want['comments_count'] = 0 393 assert row == want, (row, want) 394 ts = [x['created'] for x in rows]; assert ts == sorted(ts, reverse=True), 'newest first' 395 print('json ok') 396 EOF 397 grep -qx 'json ok' "$T/json.out" && ok "$1: forge/patch/1 and forge/patch-list/1 under both bases: every key, value, order and page" || bad "JSON ($1): $(tail -3 "$T/json.out")" 398 } 399 jsoncheck "read routes, $(kept) patches" 400 untr() { sed -i 's/\([^<]*\)<\/span>/\1/g; s/ translate="no"//g' "$T/body"; } 401 # listcheck BASE: list page 1 under BASE, and page 2 when the store holds more than 30 (at most 60): rows, 402 # the newest patch ($ID) on page 1, the first patch on the last page, and the pager links 403 listcheck() { 404 P=${1%/}; k=$(kept); r1=$k; [ "$k" -gt 30 ] && r1=30 405 c=$(code GET "$R/patches" -H "X-Forge-Base: $1"); untr; n=$(grep -o '
  • Older" "$T/body"; o=$?; else ! grep -qF '">Older' "$T/body"; o=$?; fi 407 [ "$c" = 200 ] && [ "$n" = "$r1" ] && [ "$o" = 0 ] && grep -qF "href=\"$P$R/patches/$ID\"" "$T/body" && ! grep -qF '">Newer' "$T/body" \ 408 && { [ "$k" -gt 30 ] || grep -qF "href=\"$P$R/patches/$FIRST\"" "$T/body"; } \ 409 && ok "[$1] list page 1: $n rows of $k, the newest first, a link to page 2 exactly when more than 30" || bad "[$1] list page 1 ($c, $n rows of $k, older-link check $o)" 410 [ "$k" -gt 30 ] || return 0 411 c=$(code GET "$R/patches?page=2" -H "X-Forge-Base: $1"); untr; n=$(grep -o '
  • Newer" "$T/body" \ 413 && ! grep -qF '">Older' "$T/body" && ok "[$1] list page 2: the other $n rows, the first patch among them, a link back to page 1" || bad "[$1] list page 2 ($c, $n rows of $k)" 414 } 415 for base in / /forge/; do 416 P=${base%/} 417 c=$(code GET "$R/patches/$FIRST" -H "X-Forge-Base: $base") 418 untr 419 if [ "$c" = 200 ] && grep -qF "

    $FIRSTTITLE

    " "$T/body" && grep -qF "href=\"$P$R/patches/$FIRST.patch\"" "$T/body" && grep -qF "href=\"$P$R/commit/$FIRSTBASE\"" "$T/body" \ 420 && grep -qF "${DID1}" "$T/body" && grep -qF "interplane-patch 1" "$T/body" && grep -qF -- "-----BEGIN SSH SIGNATURE-----" "$T/body"; then 421 ok "[$base] the patch page shows title, author, base, statement, signature and the raw links" 422 else bad "[$base] patch page ($c)"; fi 423 listcheck "$base" 424 c=$(code GET "$R/patches/new" -H "X-Forge-Base: $base"); [ "$c" = 200 ] && grep -qF "interplane patch $OWNER/fixrepo" "$T/body" && ok "[$base] the how-to page names the command" || bad "[$base] how-to page ($c)" 425 done 426 # markup in a title and a description is shown as text 427 std; TITLE='bold & "q"'; DESC=''; sigmake; pos "a title and a description holding markup" 428 c=$(code GET "$R/patches/$ID"); grep -qF '<b>bold</b> & "q"' "$T/body" && grep -qF '<script>x</script>' "$T/body" && ! grep -qF ' & "x"' 'hostile subject'; H=$(git -C "$T/gh" rev-parse HEAD) 628 impnew 120 "$H" open "$MAIN"; impmbox "$T/gh"; want IHOST open 629 printf 'Fix "quoted" & more' > "$I/title" 630 printf '# Head \n\nRaw HTML: bold a\n\n[link](javascript:pwn(5)) [link2](JaVaScRiPt:pwn(6)) [data](data:text/html,) ![img](javascript:pwn(8)) \n\n"quoted" & ampersand < entity\n\n\n' > "$I/description" 631 printf 'bug\n\nla"bel & \n' > "$I/labels" 632 impgh 120 'ev"il&x' 2026-11-10T11:00:00Z - - 633 thc 2026-11-10T11:05:00Z 'ev"il&x' 'Comment [x](javascript:pwn(12)) "q" & ' 634 thr 2026-11-10T12:00:00Z 'rev' '' 'Review ' 635 thrc 2026-11-10T13:00:00Z 'rc"' 3 'src/&"y".txt' 'Inline ' 636 # hostile owner and repository names in source.json; and a name holding a JSON escape (the reader cuts the value at 637 # the backslash and never decodes it) 638 GHO='ev'; GHR='re&po'; impnew 121 "$MAIN" open "$A"; want IHOSTSRC open 639 GHO='back\"sl'; GHR=gh-repo; impnew 122 "$MAIN" open "$A"; want IHOSTESC open 640 GHO=aien-dev 641 # bytes that are not text: control bytes, a NUL and ill-formed UTF-8 in title, description, labels, login and a body 642 impnew 123 "$MAIN" open "$A"; want IBYTES open 643 printf 'ctl \001\037\177 bad \377\376 end' > "$I/title"; printf 'nul \000 and \377 here\n' > "$I/description"; printf 'l\001a\nb\377\n' > "$I/labels" 644 impgh 123 $'lo\200gin' 2026-11-10T11:00:00Z - -; printf 'comment 2026-11-10T11:05:00Z b\200b 6\nx\377\000y\001z\n' >> "$I/thread" 645 646 # ---- malformed items (each must give its documented answer and never end forged) 647 # status not one of the three words (the first also holds an mbox, a diff and a bundle: no raw route may serve them) 648 pr 130 "$MAIN"; impnew 130 "$H" open "$MAIN"; impmbox "$T/gh"; cp "$IMPD/$IBUND/head.bundle" "$I/head.bundle"; printf 'draft\n' > "$I/status"; want XSTATUS 404 649 impnew 131 "$MAIN" open "$A"; printf 'Open\n' > "$I/status"; want XSTATCAP 404 650 impnew 132 "$MAIN" open "$A"; printf 'open' > "$I/status"; want XSTATNOLF 404 651 # head not 40 lowercase hex and a line feed: uppercase, 39 digits, a line after it, another byte in place of the line feed 652 U=$(printf '%s' "$MAIN" | tr a-f A-F); [ "$U" != "$MAIN" ] || bad "FIXTURE: main's id holds no letter" 653 impnew 133 "$MAIN" open "$A"; printf '%s\n' "$U" > "$I/head"; want XHEADUP 404 654 impnew 134 "$MAIN" open "$A"; printf '%s\n' "${MAIN:0:39}" > "$I/head"; want XHEADSHORT 404 655 impnew 135 "$MAIN" open "$A"; printf '%s\nmore\n' "$MAIN" > "$I/head"; want XHEADLONG 404 656 impnew 136 "$MAIN" open "$A"; printf '%sx' "$MAIN" > "$I/head"; want XHEADNOLF 404 657 # a thread whose second record is malformed: the item is whole, the thread stops after its first record 658 thbad() { impnew "$1" "$MAIN" open "$A"; thc 2026-11-10T11:05:00Z bob 'ok first'; printf "$2" >> "$I/thread"; want "$3" open; XTHREADS="$XTHREADS $3"; } 659 XTHREADS=; W300=$(printf '%300s' '' | tr ' ' a); P5000=$(printf '%5000s' '' | tr ' ' p) 660 thbad 140 'comment 2026-11-10T11:06:00Z bob `99999999`\nshort\n' XTPAST # a body length past the end of the file 661 thbad 141 'note 2026-11-10T11:06:00Z bob 1\nx\n' XTKIND # a kind that is not one of the three 662 thbad 142 "comment 2026-11-10T11:06:00Z $W300 1\nx\n" XTWORD # a login of 300 bytes 663 thbad 143 'comment 2026-11-10T11:06:00Z bob `1234567890123456789012`\nx\n' XTDIGITS # a length of 22 digits 664 thbad 144 'comment 2026-11-10T11:06:00Z bob \n' XTNOLEN # no length 665 thbad 145 "review-comment 2026-11-10T11:06:00Z bob 1 5000 1\n$P5000\nx\n" XTPATHBIG # a path of 5000 bytes 666 thbad 146 'review-comment 2026-11-10T11:06:00Z bob 3 4 5\nabcdX12345\n' XTPATHLF # a path not followed by a line feed 667 thbad 147 'comment 2026-11-10T11:06:00Z bob 3\nabcX' XTBODYLF # a body not followed by a line feed 668 thbad 148 'comment 2026-11-10 bob 1\nx\n' XTTIME # a time that is neither 20 bytes nor "-" 669 # thread, labels and gh missing; and the least a loadable item holds (source.json, status, head) 670 impnew 150 "$MAIN" open "$A"; rm "$I/thread" "$I/labels" "$I/gh"; want XMISSING open 671 impnew 151 "$MAIN" closed "$A"; rm "$I/thread" "$I/labels" "$I/gh" "$I/title" "$I/description" "$I/base" "$I/statement"; want XBARE closed 672 # a merged item whose reach file is not the importer's line, one without a reach file, one without the merged file 673 pr 170 "$A"; impnew 170 "$H" merged "$A"; impmbox "$T/gh"; impgh 170 nina 2026-11-10T11:00:00Z 2026-11-13T08:00:00Z 2026-11-13T08:00:00Z 674 printf '%s\n' "$SIDE" > "$I/merged"; printf 'sideways %s 2026-11-17T09:30:00Z\n' "$MAIN" > "$I/reach"; want XREACHBAD merged 675 pr 171 "$A"; impnew 171 "$H" merged "$A"; impmbox "$T/gh"; impgh 171 nina 2026-11-10T11:00:00Z 2026-11-13T08:00:00Z 2026-11-13T08:00:00Z 676 printf '%s\n' "$SIDE" > "$I/merged"; want XREACHNONE merged 677 pr 172 "$A"; impnew 172 "$H" merged "$A"; impmbox "$T/gh"; impgh 172 nina 2026-11-10T11:00:00Z 2026-11-13T08:00:00Z 2026-11-13T08:00:00Z; impreach reachable "$MAIN"; want XMERGEDNONE merged 678 # source.json without the github-import start: another kind (same length, the difference inside the start), cut 679 # inside the start, absent 680 impnew 152 "$MAIN" open "$A"; sed -i 's/^{"kind":"github-import"/{"kind":"github-export"/' "$I/source.json"; want XSRCKIND 404 681 impnew 153 "$MAIN" open "$A"; printf '{"kind":"github-import"' > "$I/source.json"; want XSRCSHORT 404 682 impnew 154 "$MAIN" open "$A"; rm "$I/source.json"; want XSRCNONE 404 683 # an item folder with both a meta file and source.json: with a meta that does not load it is no item at all 684 impnew 155 "$MAIN" open "$A"; printf 'not a meta file\n' > "$I/meta"; want XBOTH 404 685 # titles of 1024 bytes (kept), 1025 bytes (cut to 1024) and 1023 bytes followed by a two-byte letter (the cut 686 # falls inside the letter) 687 impnew 156 "$MAIN" open "$A"; printf '%1024s' '' | tr ' ' t > "$I/title"; want XT1024 open 688 impnew 157 "$MAIN" open "$A"; printf '%1025s' '' | tr ' ' t > "$I/title"; want XT1025 open 689 impnew 158 "$MAIN" open "$A"; { printf '%1023s' '' | tr ' ' t; printf 'é tail'; } > "$I/title"; want XT1025U open 690 # a description and a thread that together pass the 5,000,000 bytes an imported page gives them (NOTES-A PAPGMX): 691 # 2,600,000 bytes of description, then 30 comments of 100,000 bytes each 692 impnew 160 "$MAIN" open "$A"; want XBIG open 693 python3 - "$I" <<'EOF' 694 import sys 695 d = sys.argv[1] 696 line = b'Words of a long description, line %07d of many, in Markdown.\n\n' 697 open(d + '/description', 'wb').write(b''.join(line % i for i in range(`2600000` // len(line % 0)))) 698 body = b''.join(b'comment body line %07d of a very long thread\n\n' % i for i in range(100000 // 47))[:100000] 699 open(d + '/thread', 'wb').write(b''.join(b'comment 2026-11-10T11:%02d:00Z bob %d\n' % (i, len(body)) + body + b'\n' for i in range(30))) 700 EOF 701 # a description that alone passes it 702 impnew 161 "$MAIN" open "$A"; want XBIGD open 703 python3 -c "import sys; l = b'A long description line %07d.\n\n'; open(sys.argv[1], 'wb').write(b''.join(l % i for i in range(`5500000` // len(l % 0))))" "$I/description" 704 # a thread file larger than the 16 MiB the forge reads of a file: 170 comments of 100,000 bytes (167 of them whole 705 # inside the first 16 MiB) 706 impnew 163 "$MAIN" open "$A"; want XTHUGE open 707 python3 - "$I/thread" <<'EOF' 708 import sys 709 body = b''.join(b'comment body line %07d of a very long thread\n\n' % i for i in range(100000 // 47))[:100000] 710 open(sys.argv[1], 'wb').write(b''.join(b'comment 2026-11-10T11:00:00Z bob %d\n' % len(body) + body + b'\n' for i in range(170))) 711 EOF 712 [ "$(stat -c %s "$I/thread")" -gt `16777216` ] || bad "FIXTURE: the huge thread is $(stat -c %s "$I/thread") bytes" 713 # a thread whose second record is larger than the 16 MiB the forge reads of a file: a small comment, then one of 17,000,000 bytes 714 impnew 164 "$MAIN" open "$A"; want XTLARGE open; thc 2026-11-10T11:05:00Z bob 'ok first' 715 python3 -c "import sys; open(sys.argv[1], 'ab').write(b'comment 2026-11-10T11:06:00Z bob `17000000`\n' + b'x' * `17000000` + b'\n')" "$I/thread" 716 # a description whose JSON form (8,334,920 bytes: 75772 paragraphs of 98 bytes and two line feeds, 6 bytes each) takes the 717 # document past its budget of 8,323,072 bytes and still fits a response of 8,388,608; and one small comment 718 impnew 165 "$MAIN" open "$A"; want XDESCBUD open; thc 2026-11-10T11:05:00Z bob 'a small comment' 719 python3 -c "import sys; open(sys.argv[1], 'wb').write(b''.join(b'paragraph %07d ' % i + b'a' * 80 + b'\n\n' for i in range(75772)))" "$I/description" 720 # a description that alone does not fit a response (8,500,000 bytes) 721 impnew 166 "$MAIN" open "$A"; want XDESC500 open 722 python3 -c "import sys; open(sys.argv[1], 'wb').write(b''.join(b'paragraph %07d ' % i + b'a' * 80 + b'\n\n' for i in range(85000)))" "$I/description" 723 [ "$(stat -c %s "$IMPD/$XDESCBUD/description") $(stat -c %s "$I/description")" = "`7577200` `8500000`" ] || bad "FIXTURE: the two long descriptions" 724 # a bundle whose diff is larger than the 16 MiB the forge reads of a command's output: one commit adding 18 MB 725 G -C "$T/gh" checkout -q -B pr-162 "$MAIN"; yes `0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789` | head -n 180000 > "$T/gh/huge.txt" 726 G -C "$T/gh" add -A; G -C "$T/gh" commit -q -m "a huge file"; H=$(git -C "$T/gh" rev-parse HEAD); rm -f "$T/gh/huge.txt" 727 impnew 162 "$H" open "$MAIN"; impbundle "$T/gh" 162; want XDIFF open 728 n=$(git -C "$T/gh" diff --no-color --no-ext-diff --no-textconv "$MAIN...$H" | wc -c) 729 [ "$n" -gt `16777216` ] && ok "FIXTURE the huge bundle's diff is $n bytes (over `16777216`), its bundle $(stat -c %s "$I/head.bundle")" || bad "FIXTURE: the huge diff is $n bytes" 730 G -C "$T/gh" checkout -q work 731 NIMP=$(grep -c . "$IMPX"); echo "$NIMP imported fixtures beside $SIGNED signed patches" 732 [ "$(kept)" = $((SIGNED + NIMP)) ] && [ "$(grep -c . "$IMPD/index")" = $((SIGNED + NIMP)) ] && [ "$(cut -f1 "$IMPX" | sort -u | wc -l)" = "$NIMP" ] \ 733 && ok "FIXTURE every fixture has its own folder and index line ($NIMP)" || bad "FIXTURE: $(kept) folders, $(grep -c . "$IMPD/index") index lines, $NIMP fixtures" 734 H0=$(imphash) 735 736 echo "== imported proposals: pages and documents" 737 # every fixture: its page and its JSON document (kept in $T/imp for the oracle below); 200 for an item, 404 for the rest 738 while IFS=$tab read -r i name st; do 739 w=200; [ "$st" = 404 ] && w=404 740 c1=$(code GET "$R/patches/$i"); cp "$T/body" "$T/imp/$i.html"; t1=$(hdr content-type) 741 c2=$(code GET "$R/patches/$i" -H 'Accept: application/json'); cp "$T/body" "$T/imp/$i.json"; t2=$(hdr content-type) 742 echo "$c1 $c2" > "$T/imp/$i.code"; [ "$name $c2" = "XDESC500 500" ] && c2=200 && t2="application/json; charset=utf-8" 743 if [ "$c1 $c2" = "$w $w" ] && { [ "$w" = 404 ] || [ "$t1 | $t2" = "text/html; charset=utf-8 | application/json; charset=utf-8" ]; }; then ok "$name ($st): page $c1, JSON $c2" 744 else bad "$name ($st): page $c1 ($t1) and JSON $c2 ($t2), want $w"; fi 745 done < "$IMPX" 746 alive && ok "forged is still running after every imported page, the malformed ones among them" || { bad "forged ended on an imported page"; start; } 747 # the list: every page of it, HTML and JSON 748 LP=$(( ($(grep -c . "$IMPD/index") + 29) / 30 )) 749 for p in $(seq $LP); do 750 c1=$(code GET "$R/patches?page=$p"); cp "$T/body" "$T/imp/list.$p.html"; c2=$(code GET "$R/patches?page=$p" -H 'Accept: application/json'); cp "$T/body" "$T/imp/list.$p.json" 751 check "$c1 $c2" "200 200" "list page $p of $LP with the imported items" 752 done 753 check "$(code GET "$R/patches?page=$((LP + 1))")" 404 "NEG the list page after the last" 754 # The oracle: an independent reader of the item folders (SPEC section 1) gives the forge/patch/1 document and the 755 # list row of every fixture (SPEC section 3 and NOTES-G: key order, types, every value; the document budget; diff and 756 # diff_unavailable as they are after each item's first page view, which the loop above made), the provenance line and the list row 757 # of the HTML (SPEC section 2), and looks for what must never be on a page. 758 python3 - "$T" "$R" "$IMPD" "$IMPX" "$SIGNED" "$LP" "$GITS" > "$T/imp.out" 2>&1 <<'EOF' 759 import json, os, re, sys 760 from html.parser import HTMLParser 761 import subprocess 762 T, R, IMPD, EXPF, SIGNED, LP, GITS = sys.argv[1:8]; SIGNED = int(SIGNED); LP = int(LP) 763 FXO = `16777216`; FOB = `8388608`; PAJMX = `8323072` # what the forge reads of a file or a command; a response; the document budget 764 GENV = {'PATH': os.environ['PATH'], 'HOME': T + '/home'} 765 def instore(c): return subprocess.run(['git', '--git-dir=' + GITS, 'cat-file', '-e', c + '^{commit}'], env=GENV, stderr=subprocess.DEVNULL).returncode == 0 766 def difflen(b, h): return len(subprocess.run(['git', '-C', T + '/gh', 'diff', '--no-color', '--no-ext-diff', '--no-textconv', b + '...' + h], env=GENV, stdout=subprocess.PIPE, check=True).stdout) 767 NC = {} # the records of each item's thread, whatever the document leaves out (comments_count of its list row) 768 OWNER, REPO = R.split('/')[1:3] 769 def P(c, msg): 770 print(('PASS ' if c else 'FAIL ') + msg); return c 771 def nodup(pairs): 772 assert len(set(k for k, _ in pairs)) == len(pairs), 'a key twice: %r' % [k for k, _ in pairs] 773 return dict(pairs) 774 def J(b): return json.loads(b.decode('utf-8'), object_pairs_hook=nodup) 775 def rd(d, f, cap=None): 776 try: b = open(os.path.join(d, f), 'rb').read() 777 except OSError: return None 778 return b if cap is None else b[:cap] 779 def txt(b): return b.decode('utf-8', 'replace') # an ill-formed byte is U+FFFD in a JSON string 780 def esc(b): return b.replace(b'&', b'&').replace(b'<', b'<').replace(b'>', b'>').replace(b'"', b'"') 781 PRE = b'{"kind":"github-import","owner":"' 782 HEX = re.compile(rb'[0-9a-f]{40}\n') 783 def sjv(sj, key): # the string after the key text, up to its closing quote or a backslash 784 i = sj.find(key) 785 if i < 0: return None 786 p = q = i + len(key) 787 while q < len(sj) and sj[q] not in (0x22, 0x5c): q += 1 788 return sj[p:q] 789 def ghv(gh, key): # the value of the first whole line "\n" 790 for l in gh.split(b'\n')[:-1]: 791 if l.startswith(key): return l[len(key):] 792 return None 793 def record(b, p): # one thread record at p: (comment, index after it), or None when it is malformed 794 n = len(b) 795 def word(p): 796 q = p 797 while q < n and b[q] > 32: q += 1 798 return None if q >= n or q == p or q - p > 256 or b[q] != 32 else (b[p:q], q + 1) 799 def num(p, t): 800 q = p 801 while q < n and 48 <= b[q] <= 57: q += 1 802 return None if q == p or q - p > 18 or q >= n or b[q] != t else (int(b[p:q]), q + 1) 803 w = word(p) 804 if not w or w[0] not in (b'comment', b'review', b'review-comment'): return None 805 kind, p = w 806 w = word(p) 807 if not w: return None 808 tm, p = w 809 w = word(p) 810 if not w: return None 811 c = {'author': None, 'login': txt(w[0]), 'kind': kind.decode()}; p = w[1] 812 if kind == b'review': 813 w = word(p) 814 if not w: return None 815 c['state'] = None if w[0] == b'-' else txt(w[0]); p = w[1] 816 if kind == b'review-comment': 817 w = num(p, 32) 818 if not w: return None 819 line, p = w 820 w = num(p, 32) 821 if not w: return None 822 plen, p = w 823 w = num(p, 10) 824 if not w or not (len(tm) == 20 or tm == b'-'): return None 825 blen, p = w 826 if kind == b'review-comment': 827 if plen > 4096 or p + plen >= n or b[p + plen] != 10: return None 828 c['path'] = txt(b[p:p + plen]); c['line'] = line; p += plen + 1 829 if p + blen >= n or b[p + blen] != 10: return None 830 c['time'] = txt(tm) if len(tm) == 20 else None 831 c['body'] = txt(b[p:p + blen]) 832 return c, p + blen + 1 833 def thread(b): # the records up to the first malformed one, and whether one stopped them 834 out = []; p = 0 835 while p < len(b): 836 r = record(b, p) 837 if r is None: return out, True 838 out.append(r[0]); p = r[1] 839 return out, False 840 def jstr(t): # a string as the forge writes it (server/json.om fjstr): \" \\, \u00XX for control bytes, DEL, < > &; an ill-formed byte \ufffd 841 return b'"' + re.sub(r'["\\\x00-\x1f\x7f<>&\ufffd]', lambda m: {'"': '\\"', '\\': '\\\\', '\ufffd': '\\ufffd'}.get(m.group(0)) or '\\u%04x' % ord(m.group(0)), t).encode('utf-8') + b'"' 842 def jcom(c): # one comment as the forge writes it 843 o = b'{"author":null,"login":' + jstr(c['login']) + b',"kind":"' + c['kind'].encode() + b'"' 844 if c['kind'] == 'review': o += b',"state":' + (b'null' if c['state'] is None else jstr(c['state'])) 845 if c['kind'] == 'review-comment': o += b',"path":' + jstr(c['path']) + b',"line":%d' % c['line'] 846 return o + b',"time":' + (b'null' if c['time'] is None else jstr(c['time'])) + b',"body":' + jstr(c['body']) + b'}' 847 def budget(raw, coms): # the records that fit the document budget from where the served comments start: how many, their bytes, the start, the size of the next 848 pos = raw.find(b',"comments":[') + 13; seg = []; at = pos 849 for n, c in enumerate(coms): 850 piece = (b',\n' if n else b'\n') + jcom(c) 851 if at + len(piece) > PAJMX: return n, b''.join(seg), pos, len(piece) 852 seg.append(piece); at += len(piece) 853 return len(coms), b''.join(seg), pos, 0 854 def reach(d): 855 b = rd(d, 'reach') 856 if b is None or not 5 <= len(b) <= 255 or b[-1] != 10: return 'unknown', None, None 857 w = b[:-1].split(b' ', 2) 858 if len(w) != 3 or w[0] not in (b'reachable', b'not-reachable', b'unknown') or not (re.fullmatch(rb'[0-9a-f]{40}', w[1]) or w[1] == b'-') \ 859 or not 1 <= len(w[2]) <= 32: return 'unknown', None, None 860 return w[0].decode(), (w[1].decode() if len(w[1]) == 40 else None), txt(w[2]) 861 def item(i): # the forge/patch/1 document of the imported item folder i under base "/", None when it is not an item 862 d = os.path.join(IMPD, i) 863 if os.path.exists(os.path.join(d, 'meta')): return None 864 sj = rd(d, 'source.json', 4096) 865 st = {b'open\n': 'open', b'closed\n': 'closed', b'merged\n': 'merged'}.get(rd(d, 'status')) 866 hd = rd(d, 'head') 867 if sj is None or not sj.startswith(PRE) or st is None or hd is None or not HEX.fullmatch(hd): return None 868 derived = b'"state_derived":true' in sj 869 gh = rd(d, 'gh', 2048) or b'' 870 def ghs(k): 871 v = ghv(gh, k) 872 return None if v in (None, b'', b'-') else txt(v) 873 def s(k): 874 v = sjv(sj, k) 875 return None if v is None else txt(v) 876 num = ghv(gh, b'number ') 877 if num is not None and re.fullmatch(rb'[0-9]{1,18}', num): num = int(num) 878 else: 879 m = re.search(rb'"number":([0-9]*)', sj); num = int(m.group(1)) if m and 1 <= len(m.group(1)) <= 18 else 0 880 bs = rd(d, 'base'); bs = bs[:40].decode() if bs is not None and HEX.fullmatch(bs) else None 881 code, size = 'none', 0 882 for f, k in (('head.bundle', 'bundle'), ('mbox', 'mbox')): 883 if os.path.exists(os.path.join(d, f)): code, size = k, os.path.getsize(os.path.join(d, f)) 884 merge = None; mg = rd(d, 'merged') 885 if st == 'merged' and mg is not None and HEX.fullmatch(mg): 886 w, m, o = reach(d) 887 merge = {'commit': mg[:40].decode(), 'time': ghs(b'merged '), 'reach': w, 'main': m, 'observed': o} 888 p = '/%s/%s/patches/%s' % (OWNER, REPO, i) 889 tb = rd(d, 'thread') or b''; coms, stopped = thread(tb[:FXO]); NC[i] = len(coms) 890 why = 'too-large' if len(tb) >= FXO else 'malformed-record' if stopped else None 891 if code == 'mbox': diff, du = p + '.diff', None 892 elif code == 'none': diff, du = None, 'no-code-file' 893 elif bs is None: diff, du = None, 'no-base' 894 elif not instore(bs): diff, du = None, 'base-not-in-store' 895 elif difflen(bs, hd[:40].decode()) >= FXO: diff, du = None, 'too-large' 896 else: diff, du = p + '.diff', None 897 return {'schema': 'forge/patch/1', 'base': '/', 'owner': OWNER, 'repo': REPO, 'id': i, 'title': txt(rd(d, 'title', 1024) or b''), 898 'description': txt(rd(d, 'description', `16777216`) or b''), 'status': st, 'state_derived': derived, 'author': None, 899 'imported': {'from': 'github', 'owner': s(b'"owner":"'), 'repo': s(b'"repo":"'), 'number': num, 'url': s(b'"url":"'), 900 'login': None if derived else ghs(b'login ')}, 901 'base_commit': bs, 'head_commit': hd[:40].decode(), 'commits': None, 'files': None, 'bytes': size, 'code': code, 'mbox_sha256': None, 902 'opened': ghs(b'opened '), 'closed': ghs(b'closed '), 'merge': merge, 903 'labels': [txt(x) for x in (rd(d, 'labels', 65536) or b'').split(b'\n') if x], 'comments': coms, 'thread_truncated': why is not None, 'thread_reason': why, 904 'created': s(b'"imported_utc":"'), 'path': p, 'patch': p + '.patch' if code == 'mbox' else None, 905 'diff': diff, 'diff_unavailable': du, 'bundle': p + '.bundle' if code == 'bundle' else None} 906 FULL = ['schema', 'base', 'owner', 'repo', 'id', 'title', 'description', 'status', 'state_derived', 'author', 'imported', 'base_commit', 'head_commit', 907 'commits', 'files', 'bytes', 'code', 'mbox_sha256', 'opened', 'closed', 'merge', 'labels', 'comments', 'thread_truncated', 'thread_reason', 908 'created', 'path', 'patch', 'diff', 'diff_unavailable', 'bundle'] 909 ROW = ['id', 'title', 'status', 'state_derived', 'author', 'imported', 'base_commit', 'head_commit', 'commits', 'files', 'bytes', 'code', 'created', 910 'comments_count', 'path', 'patch', 'diff', 'diff_unavailable', 'bundle'] 911 def row(d): 912 r = {k: d[k] for k in ROW if k != 'comments_count'}; r['comments_count'] = NC[d['id']] 913 return {k: r[k] for k in ROW} 914 def deep(a, b, at=''): # where two documents differ first (keys in order, types, values) 915 if type(a) != type(b): return '%s: %r is not %r' % (at, a if not isinstance(a, (str, list, dict)) else type(a).__name__, b if not isinstance(b, (str, list, dict)) else type(b).__name__) 916 if isinstance(a, dict): 917 if list(a) != list(b): return '%s: keys %r, want %r' % (at, list(a), list(b)) 918 for k in a: 919 x = deep(a[k], b[k], at + '/' + k) 920 if x: return x 921 elif isinstance(a, list): 922 if len(a) != len(b): return '%s: %d elements, want %d' % (at, len(a), len(b)) 923 for k in range(len(a)): 924 x = deep(a[k], b[k], '%s/%d' % (at, k)) 925 if x: return x 926 elif a != b: return '%s: %r, want %r' % (at, a[:80] if isinstance(a, str) else a, b[:80] if isinstance(b, str) else b) 927 return '' 928 def types(d): # SPEC section 3, said without the oracle 929 S = str; N = type(None); im = d['imported'] 930 return (isinstance(d['title'], S) and isinstance(d['description'], S) and d['status'] in ('open', 'closed', 'merged') and type(d['state_derived']) is bool 931 and d['author'] is None and type(im) is dict and list(im) == ['from', 'owner', 'repo', 'number', 'url', 'login'] and im['from'] == 'github' 932 and type(im['number']) is int and isinstance(im['login'], (S, N)) and isinstance(d['base_commit'], (S, N)) and isinstance(d['head_commit'], S) 933 and d['commits'] is None and d['files'] is None and type(d['bytes']) is int and d['code'] in ('mbox', 'bundle', 'none') and d['mbox_sha256'] is None 934 and isinstance(d['opened'], (S, N)) and isinstance(d['closed'], (S, N)) and isinstance(d['merge'], (dict, N)) 935 and type(d['labels']) is list and all(isinstance(x, S) for x in d['labels']) and type(d['comments']) is list 936 and all(c['author'] is None and isinstance(c['login'], S) and c['kind'] in ('comment', 'review', 'review-comment') and isinstance(c['body'], S) 937 and isinstance(c['time'], (S, N)) for c in d['comments']) 938 and isinstance(d['created'], (S, N)) and isinstance(d['path'], S) and all(isinstance(d[k], (S, N)) for k in ('patch', 'diff', 'bundle')) 939 and type(d['thread_truncated']) is bool and d['thread_reason'] in (None, 'malformed-record', 'too-large', 'document-budget') and (d['thread_reason'] is None) == (not d['thread_truncated']) 940 and d['diff_unavailable'] in (None, 'no-code-file', 'no-base', 'base-not-in-store', 'too-large') and (d['diff'] is None) == (d['diff_unavailable'] is not None)) 941 def untr(b): return re.sub(rb' translate="no"', b'', re.sub(rb'([^<]*)', rb'\1', b)) 942 class Scan(HTMLParser): # what must never come out of imported bytes: a marker in a tag, an attribute or a script; a script link; a login as a link 943 def __init__(s, logins): 944 super().__init__(convert_charrefs=True); s.bad = []; s.a = 0; s.raw = None; s.logins = logins 945 def handle_starttag(s, tag, attrs): 946 if tag == 'a': s.a += 1 947 if tag in ('script', 'style'): s.raw = tag 948 for k, v in attrs: 949 v = v or '' 950 if 'pwn' in k or 'pwn(' in v or '<' in v or 'pwn' in tag: s.bad.append('marker in <%s %s="%s">' % (tag, k, v[:60])) 951 if k in ('href', 'src', 'action', 'formaction') and re.match(r'[\s\x00-\x20]*(javascript|data|vbscript)\s*:', v, re.I): s.bad.append('%s="%s"' % (k, v[:60])) 952 def handle_endtag(s, tag): 953 if tag == 'a': s.a -= 1 954 if tag == s.raw: s.raw = None 955 def handle_data(s, data): 956 if s.raw and 'pwn' in data: s.bad.append('marker inside <%s>' % s.raw) 957 if s.a > 0: 958 for l in s.logins: 959 if l in data: s.bad.append('login %r inside a link' % l) 960 exp = [l.rstrip('\n').split('\t') for l in open(EXPF)] 961 docs = {} 962 for i, name, st in exp: 963 raw = open('%s/imp/%s.json' % (T, i), 'rb').read(); page = untr(open('%s/imp/%s.html' % (T, i), 'rb').read()); w = item(i) 964 jcode = open('%s/imp/%s.code' % (T, i)).read().split()[1] 965 if st == '404': 966 P(w is None, '%s: the oracle too reads no item in the folder' % name); continue 967 if not P(w is not None and w['status'] == st, '%s: the fixture is a loadable item in state %s' % (name, st)): continue 968 try: d = J(raw) 969 except Exception as e: 970 P(False, '%s: JSON does not parse: %s' % (name, e)); continue 971 docs[i] = w 972 desc = rd(os.path.join(IMPD, i), 'description') or b'' 973 if jcode == '500': # a document that does not fit a response without any comment: the forge's whole 500, never a cut 200 974 P(len(desc) >= FOB and len(raw) < 1000 and 'description' not in d, '%s: its description of %d bytes alone does not fit a response: a whole 500 notice (%d bytes of valid JSON), not a cut document' % (name, len(desc), len(raw))) 975 else: 976 full = w['comments']; n, seg, pos, nxt = budget(raw, full) 977 if n < len(full): w['comments'] = full[:n]; w['thread_truncated'] = True; w['thread_reason'] = 'document-budget' 978 x = deep(d, w) 979 P(x == '' and list(d) == FULL, '%s: forge/patch/1 has the documented keys in order and every value the folder gives%s' % (name, x and ' -- ' + x)) 980 P(list(d) == FULL and types(d), '%s: forge/patch/1 value types (author null, imported object, commits/files/mbox_sha256 null, thread_truncated bool, exactly one of diff and diff_unavailable null)' % name) 981 P(pos > 12 and raw[pos:pos + len(seg) + 1] == seg + b']', '%s: the comments array is byte for byte the %d of %d records that fit the document' % (name, n, len(full))) 982 if n < len(full): 983 e = pos + len(seg) 984 P(len(raw) < FOB and (e <= PAJMX or n == 0) and PAJMX < e + nxt and d.get('thread_truncated') is True and d.get('thread_reason') == 'document-budget', 985 '%s: the document budget: a valid document of %d bytes (under %d) says document-budget; its %d comments end whole at byte %d (budget %d) and the next record of %d bytes would pass it' % (name, len(raw), FOB, n, e, PAJMX, nxt)) 986 im = w['imported']; own = esc((im['owner'] or '').encode()); rep = esc((im['repo'] or '').encode()) 987 gh = rd(os.path.join(IMPD, i), 'gh', 2048) or b'' 988 login = ghv(gh, b'login ') 989 if w['state_derived']: prov = b'Imported from GitHub %s/%s#%d (code only)' % (own, rep, im['number']) 990 elif not login: prov = b'Imported from GitHub %s/%s#%d' % (own, rep, im['number']) # no login line, or an empty one: the line ends after the number 991 else: prov = b'Imported from GitHub %s/%s#%d, by %s' % (own, rep, im['number'], esc(login)) 992 w['_prov'] = prov 993 if prov is not None: 994 P(page.count(b'

    ' + prov + b'

    ') == 1 and page.count(b'Imported from GitHub') == 1, 995 '%s: the page has the provenance line once, as text: %s' % (name, prov.decode('utf-8', 'replace')[:90])) 996 logins = set(c['login'] for c in w['comments'] if len(c['login']) > 2) | ({im['login']} if im['login'] and len(im['login']) > 2 else set()) 997 sc = Scan(logins); sc.feed(page.decode('utf-8', 'replace')); sc.close() 998 P(not sc.bad and b'did:key:' not in page, '%s: no did:key: on the page, no login inside a link, no imported byte in a tag, an attribute or a script%s' % (name, sc.bad and ' -- ' + '; '.join(sc.bad[:3]) or '')) 999 P(page.rstrip().endswith(b'') and page.count(b'') == 1, '%s: the page is a whole document' % name) 1000 # ---- the list: every page 1001 states = {'open': SIGNED, 'closed': 0, 'merged': 0} 1002 for i, name, st in exp: 1003 if st != '404': states[st] += 1 1004 index = [l for l in open(os.path.join(IMPD, 'index')).read().split('\n') if l] 1005 gone = set(i for i, name, st in exp if st == '404') 1006 wantids = [i for i in reversed(index) if i not in gone] 1007 count = sum(states.values()); damaged = len(index) - count # the items the pages list; the index lines whose folder is no item 1008 rows = []; html = b''; ok = True; why = '' 1009 for p in range(1, LP + 1): 1010 l = J(open('%s/imp/list.%d.json' % (T, p), 'rb').read()); html += untr(open('%s/imp/list.%d.html' % (T, p), 'rb').read()) 1011 if not (list(l) == ['schema', 'base', 'owner', 'repo', 'page', 'per_page', 'count', 'states', 'damaged', 'patches', 'next', 'prev'] and l['schema'] == 'forge/patch-list/1' 1012 and l['page'] == p and l['count'] == count and l['states'] == states and list(l['states']) == ['open', 'closed', 'merged'] and l['damaged'] == damaged 1013 and (l['next'] is None) == (p == LP) and (l['prev'] is None) == (p == 1)): 1014 ok = False; why = 'page %d: %r' % (p, {k: l[k] for k in l if k != 'patches'}) 1015 want = [i for i in list(reversed(index))[(p - 1) * 30:p * 30] if i not in gone] 1016 if [r['id'] for r in l['patches']] != want: ok = False; why = 'page %d holds %d rows, want %d' % (p, len(l['patches']), len(want)) 1017 rows += l['patches'] 1018 h = untr(open('%s/imp/list.%d.html' % (T, p), 'rb').read()) 1019 hs = b'%d patches %d open · %d closed · %d merged %d damaged items are not shown 1, 1025 'count (%d) is the sum of the states and the rows of all pages; count + damaged (%d) is the index lines (%d); the damaged are the %d fixtures that are no item' % (count, damaged, len(index), len(gone))) 1026 byid = {r['id']: r for r in rows} 1027 for i, name, st in exp: 1028 if st == '404': 1029 P(i not in byid and html.count(i.encode()) == 0, '%s: left out of the list (JSON rows and HTML)' % name); continue 1030 if i not in docs: continue 1031 w = docs[i]; x = deep(byid.get(i), row(w)) 1032 P(x == '', '%s: its forge/patch-list/1 row has the keys in order and every value%s' % (name, x and ' -- ' + x)) 1033 if w['_prov'] is None: continue 1034 badge = {'open': b'open', 'closed': b'closed', 'merged': b'merged'}[w['status']] 1035 if w['state_derived']: badge += b' derived'; when = b' imported ' + (w['created'] or '-')[:10].encode() 1036 else: when = b' opened ' + (w['opened'][:10].encode() if w['opened'] and len(w['opened']) == 20 else b'-') 1037 title = esc(rd(os.path.join(IMPD, i), 'title', 1024) or b'') or b'(untitled)' 1038 li = b'
  • %s
    %s %s%s · %s
  • ' % (w['path'].encode(), title, badge, i.encode(), when, w['_prov']) 1039 P(html.count(li) == 1, '%s: its HTML list row is title link, badge, id, date and the provenance text, no counts' % name) 1040 sc = Scan(set()); sc.feed(html.decode('utf-8', 'replace')); sc.close() 1041 P(not sc.bad and b'