| 1 | <?php |
| 2 | /************************************************************* |
| 3 | # 076 License |
| 4 | |
| 5 | Copyright (c) テクニカル諏訪子 |
| 6 | |
| 7 | Permission is hereby granted to any person obtaining a copy of the software |
| 8 | Little Beast (the "Software") to use, modify, merge, copy, publish, distribute, |
| 9 | sublicense, and/or sell copies of the Software, subject to the following conditions: |
| 10 | |
| 11 | 1. **Origin Attribution**: |
| 12 | - You must not misrepresent the origin of the Software; you must not claim |
| 13 | you created the original Software. |
| 14 | - If the Software is used in a product, you must either: |
| 15 | a. Provide clear attribution in the product's documentation, user interface, |
| 16 | or other visible areas, **OR** |
| 17 | b. Pay the original developers a fee they specify in writing. |
| 18 | 2. **Usage Restriction**: |
| 19 | - The Software, or any derivative works, dependencies, or libraries |
| 20 | incorporating it, must not be used for censorship or to suppress freedom of |
| 21 | speech, expression, or creativity. Prohibited uses include, but are not |
| 22 | limited to: |
| 23 | - Censorship of so-called "hate speech", visuals, non-mainstream opinions, |
| 24 | ideas, or objective reality. |
| 25 | - Tools or systems designed to restrict access to information or |
| 26 | artistic works. |
| 27 | 3. **Notice Preservation**: |
| 28 | - This license and the above copyright notice must remain intact in all copies |
| 29 | of the source code. |
| 30 | |
| 31 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, |
| 32 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A |
| 33 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT |
| 34 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF |
| 35 | CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE |
| 36 | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 37 | */ |
| 38 | namespace Std\Test; |
| 39 | |
| 40 | require_once __DIR__.'/../../../autoload.php'; |
| 41 | |
| 42 | use Std\Lib\Tester; |
| 43 | use Std\Lib\Activitypub; |
| 44 | use Std\Lib\Fedi\{Fedi, Actor, Social, Delivery, Inbox, Timeline, Remote, Notes, Html, Media}; |
| 45 | |
| 46 | $test = new Tester([ |
| 47 | 'colorOutput' => true, |
| 48 | 'verboseOutput' => true |
| 49 | ]); |
| 50 | |
| 51 | // 2つのサーバー(A・B)を1つのプロセスで動かす。公開IPのURLなので名前解決は要らない |
| 52 | $tmp = sys_get_temp_dir().'/lbfedi_'.bin2hex(random_bytes(6)); |
| 53 | $inst = ['A' => 'https://1.1.1.1', 'B' => 'https://8.8.8.8']; |
| 54 | $use = function(string $n) use ($tmp, $inst): void { |
| 55 | Fedi::$baseUrl = $inst[$n]; |
| 56 | Fedi::$dataDir = "{$tmp}/{$n}/ap"; |
| 57 | Fedi::$userDir = "{$tmp}/{$n}/user/"; |
| 58 | if (!is_dir(Fedi::$userDir)) mkdir(Fedi::$userDir, 0700, true); |
| 59 | }; |
| 60 | $mkuser = function(string $n, string $name, int $id, int $role = 1) use ($use): void { |
| 61 | $use($n); |
| 62 | file_put_contents(Fedi::$userDir."{$id}.{$name}.json", json_encode([ |
| 63 | 'id' => $id, 'username' => $name, 'displayname' => ucfirst($name), 'bio' => "I am {$name}", 'avatar' => '', |
| 64 | 'email' => "{$name}@example.com", 'regDate' => time(), 'gender' => -1, 'role' => $role, 'namecolor' => '', |
| 65 | ])); |
| 66 | }; |
| 67 | // 相手のサーバーのアクターをキャッシュに入れる(取得しなくても良い様に) |
| 68 | $seed = function(string $from, string $to, string $name) use ($use): void { |
| 69 | $use($to); |
| 70 | $doc = Actor::document(Fedi::localActor($name)); |
| 71 | $use($from); |
| 72 | Remote::cacheActor($doc); |
| 73 | }; |
| 74 | // 待ち行列を相手のサーバーの受付ボックスに届ける |
| 75 | $pump = function() use ($use, $inst): array { |
| 76 | $log = []; |
| 77 | for ($round = 0; $round < 5; $round++) { |
| 78 | $any = false; |
| 79 | foreach (array_keys($inst) as $n) { |
| 80 | $use($n); |
| 81 | foreach (glob(Fedi::path('queue/').'*.json') ?: [] as $f) { |
| 82 | $job = json_decode(file_get_contents($f), true); |
| 83 | unlink($f); |
| 84 | $any = true; |
| 85 | $dest = array_search('https://'.parse_url($job['inbox'], PHP_URL_HOST), $inst, true); |
| 86 | $use($dest); |
| 87 | [$code] = Inbox::handle($job['activity']); |
| 88 | $log[] = "{$job['activity']['type']}:{$code}"; |
| 89 | $use($n); |
| 90 | } |
| 91 | } |
| 92 | if (!$any) break; |
| 93 | } |
| 94 | return $log; |
| 95 | }; |
| 96 | $alice = 'https://1.1.1.1/ap/users/alice'; |
| 97 | $carol = 'https://1.1.1.1/ap/users/carol'; |
| 98 | $bob = 'https://8.8.8.8/ap/users/bob'; |
| 99 | |
| 100 | $test->describe('Fediverseの本文', function($test): void { |
| 101 | if (!ACTIVITYPUB_ENABLED) { |
| 102 | $test->skipAll('ACTIVITYPUB_ENABLEDが無効'); |
| 103 | } |
| 104 | $test->it('メンションとハッシュタグを取り出すはず', function($test): void { |
| 105 | $t = "Hi @bob@b.example and @alice! #タグ #php https://x.example/#notatag @not@url"; |
| 106 | $test->assertEquals(['@bob@b.example' => ['bob', 'b.example'], '@alice' => ['alice', null]], Html::mentions($t)); |
| 107 | $test->assertEquals(['タグ', 'php'], Html::hashtags($t)); |
| 108 | }); |
| 109 | |
| 110 | $test->it('プレーンテキストをHTMLにするはず', function($test): void { |
| 111 | Fedi::$baseUrl = 'https://1.1.1.1'; |
| 112 | $html = Html::render("Hi @bob@b.example <b>\nhttps://x.example/a?b=1, #tag\n\nnext", ['@bob@b.example' => 'https://8.8.8.8/ap/users/bob']); |
| 113 | $test->assertStringContains('<span class="h-card"><a href="https://8.8.8.8/ap/users/bob" class="u-url mention">@<span>bob</span></a></span>', $html); |
| 114 | $test->assertStringContains('<b><br />', $html); |
| 115 | $test->assertStringContains('<a href="https://x.example/a?b=1" rel="nofollow noopener noreferrer">x.example/a?b=1</a>,', $html); |
| 116 | $test->assertStringContains('<a href="https://1.1.1.1/microblog/tag/tag" class="mention hashtag" rel="tag">#<span>tag</span></a>', $html); |
| 117 | $test->assertStringContains('</p><p>next</p>', $html); |
| 118 | // 解決出来なかったメンションはリンクにしない |
| 119 | $test->assertEquals('<p>@nobody@x.example</p>', Html::render('@nobody@x.example')); |
| 120 | }); |
| 121 | |
| 122 | $test->it('Markdownを描画するはず', function($test): void { |
| 123 | Fedi::$baseUrl = 'https://1.1.1.1'; |
| 124 | $r = fn(string $t) => Html::render($t); |
| 125 | $test->assertEquals('<p><strong>太字</strong>と<em>斜体</em>と<del>線</del>と<code><b>*x*</code></p>', $r('**太字**と*斜体*と~~線~~と`<b>*x*`')); |
| 126 | $test->assertEquals('<p><a href="https://x.example/a" rel="nofollow noopener noreferrer"><strong>リンク</strong></a></p>', $r('[**リンク**](https://x.example/a)')); |
| 127 | // javascript:等はリンクにしない |
| 128 | $test->assertEquals('<p>[x](javascript:alert(1))</p>', $r('[x](javascript:alert(1))')); |
| 129 | $test->assertEquals('<ul><li>a</li><li><em>b</em></li></ul><ol><li>one</li><li>two</li></ol>', $r("- a\n* *b*\n\n1. one\n2. two")); |
| 130 | $test->assertEquals('<blockquote><p>引用<br /><strong>強</strong></p></blockquote><p>本文</p>', $r("> 引用\n> **強**\n\n本文")); |
| 131 | $test->assertEquals("<pre><code>**そのまま** #tag @bob\n<script></code></pre>", $r("```php\n**そのまま** #tag @bob\n<script>\n```")); |
| 132 | // snake_caseや@user_nameは斜体にしない、\*はそのまま |
| 133 | $test->assertEquals('<p>snake_case_name @a_b_c 2*3 \\ *x*</p>', $r('snake_case_name @a_b_c 2\*3 \\\\ \*x\*')); |
| 134 | // コードの中のメンションとタグは使わない |
| 135 | $test->assertEquals([], Html::mentions("`@bob@b.example`\n```\n@carol\n```")); |
| 136 | $test->assertEquals(['real'], Html::hashtags("`#code` #real")); |
| 137 | // 見出しは扱わない(「# 」はタグでもない) |
| 138 | $test->assertEquals('<p># 見出し</p>', $r('# 見出し')); |
| 139 | }); |
| 140 | |
| 141 | $test->it('リモートのHTMLを安全にするはず', function($test): void { |
| 142 | $out = Html::sanitize('<p onclick="x">Hi <a href="javascript:alert(1)">x</a> <a href="https://e.x/" class="mention evil" target="_blank">@u</a>' |
| 143 | .'<script>alert(1)</script><img src=x onerror=alert(1)><style>p{}</style><iframe src="https://e.x"></iframe><b>日本語</b></p>'); |
| 144 | $test->assertFalse(str_contains($out, '<script')); |
| 145 | $test->assertFalse(str_contains($out, 'onerror')); |
| 146 | $test->assertFalse(str_contains($out, 'onclick')); |
| 147 | $test->assertFalse(str_contains($out, 'javascript:')); |
| 148 | $test->assertFalse(str_contains($out, '<img')); |
| 149 | $test->assertFalse(str_contains($out, '<iframe')); |
| 150 | $test->assertFalse(str_contains($out, 'target=')); |
| 151 | $test->assertStringContains('<a href="https://e.x/" class="mention" rel="nofollow noopener noreferrer">@u</a>', $out); |
| 152 | $test->assertStringContains('<b>日本語</b>', $out); |
| 153 | $test->assertEquals("a\nb", Html::text('<p>a<br>b</p>')); |
| 154 | }); |
| 155 | |
| 156 | $test->it('FEDIINFOのdomainをURLにするはず', function($test): void { |
| 157 | $test->assertEquals('https://technicalsuwako.moe', Fedi::normalizeDomain('technicalsuwako.moe')); |
| 158 | $test->assertEquals('https://technicalsuwako.moe', Fedi::normalizeDomain('https://technicalsuwako.moe/')); |
| 159 | $test->assertEquals('http://127.0.0.1:8000', Fedi::normalizeDomain('http://127.0.0.1:8000')); |
| 160 | $test->assertEquals('', Fedi::normalizeDomain('')); |
| 161 | }); |
| 162 | |
| 163 | $test->it('公開範囲を判断するはず', function($test): void { |
| 164 | $f = 'https://x.example/users/a/followers'; |
| 165 | $test->assertEquals('public', Fedi::visibility([Fedi::PUBLIC], [$f])); |
| 166 | $test->assertEquals('unlisted', Fedi::visibility([$f], [Fedi::PUBLIC])); |
| 167 | $test->assertEquals('followers', Fedi::visibility([$f], [])); |
| 168 | $test->assertEquals('direct', Fedi::visibility(['https://x.example/users/b'], [])); |
| 169 | }); |
| 170 | }); |
| 171 | |
| 172 | $test->describe('アップロードした画像', function($test): void { |
| 173 | $test->it('中身で種類を判断するはず', function($test): void { |
| 174 | $test->assertEquals('image/png', Media::detect("\x89PNG\r\n\x1a\nxxxx")); |
| 175 | $test->assertEquals('image/jpeg', Media::detect("\xff\xd8\xff\xe0xxxx")); |
| 176 | $test->assertEquals('image/gif', Media::detect('GIF89axxxx')); |
| 177 | $test->assertEquals('image/webp', Media::detect('RIFF'.pack('V', 100).'WEBPVP8 ')); |
| 178 | $test->assertNull(Media::detect('<?php echo 1;')); |
| 179 | $test->assertEquals('video/mp4', Media::detect("\0\0\0\x20ftypisom\0\0\x02\0")); |
| 180 | $test->assertEquals('video/mp4', Media::detect("\0\0\0\x18ftypmp42\0\0\0\0")); |
| 181 | $test->assertNull(Media::detect("\0\0\0\x1cftypavif\0\0\0\0")); |
| 182 | $test->assertNull(Media::detect("\0\0\0\x14ftypqt \0\0\0\0")); |
| 183 | $test->assertEquals('video/webm', Media::detect("\x1a\x45\xdf\xa3\x9f\x42\x86\x81\x01\x42\x82\x84webm")); |
| 184 | $test->assertEquals('video/matroska', Media::detect("\x1a\x45\xdf\xa3\x9f\x42\x86\x81\x01\x42\x82\x88matroska")); |
| 185 | $test->assertNull(Media::detect("\x1a\x45\xdf\xa3\x9f\x42\x86\x81\x01")); |
| 186 | }); |
| 187 | |
| 188 | $test->it('アイコンには動画を使えないはず', function($test): void { |
| 189 | $tmp = tempnam(sys_get_temp_dir(), 'lbmedia'); |
| 190 | file_put_contents($tmp, "\0\0\0\x18ftypmp42\0\0\0\0".str_repeat("\0", 16)); |
| 191 | $file = ['name' => 'a.mp4', 'tmp_name' => $tmp, 'size' => filesize($tmp), 'error' => UPLOAD_ERR_OK]; |
| 192 | $res = Media::save($file, 'test', '', false); |
| 193 | @unlink($tmp); |
| 194 | $test->assertFalse($res->isSuccess); |
| 195 | $test->assertStringContains('画像だけ', $res->message); |
| 196 | }); |
| 197 | |
| 198 | $test->it('MP4のメタデータを同じ大きさの空きにするはず', function($test): void { |
| 199 | $box = fn(string $t, string $d) => pack('N', strlen($d) + 8).$t.$d; |
| 200 | $mdat = $box('mdat', 'FRAMES'); |
| 201 | $mp4 = $box('ftyp', 'isom'.pack('N', 512).'isomiso2') |
| 202 | .$box('moov', $box('mvhd', "\0\0\0\0".'DATEDATE'.str_repeat("\1", 12)) |
| 203 | .$box('trak', $box('tkhd', 'TKHD').$box('udta', $box("\xa9xyz", '+35.6+139.7/'))) |
| 204 | .$box('udta', $box("\xa9day", '2026-11-11')).$box('meta', 'Apple iPhone')) |
| 205 | .$box('uuid', 'XMPxmp:CreatorTool') |
| 206 | .$mdat; |
| 207 | $out = Media::strip($mp4, 'video/mp4'); |
| 208 | $test->assertEquals(strlen($mp4), strlen($out)); |
| 209 | foreach (['+35.6+139.7', '2026-11-11', 'iPhone', 'CreatorTool', 'udta', 'meta', 'uuid', 'DATEDATE'] as $s) $test->assertFalse(str_contains($out, $s)); |
| 210 | foreach (['mvhd', 'tkhd', 'TKHD', 'mdat', 'FRAMES'] as $s) $test->assertStringContains($s, $out); |
| 211 | // 動画のデータの位置は変わらない |
| 212 | $test->assertEquals(strpos($mp4, $mdat), strpos($out, $mdat)); |
| 213 | }); |
| 214 | |
| 215 | $test->it('JPEG・PNG・WebPのメタデータを取り除くはず', function($test): void { |
| 216 | $exif = "\xff\xe1".pack('n', 12).'Exif'."\0\0GPS!"; |
| 217 | $jfif = "\xff\xe0".pack('n', 6).'JFIF'; |
| 218 | $com = "\xff\xfe".pack('n', 6).'note'; |
| 219 | $jpeg = "\xff\xd8".$jfif.$exif.$com."\xff\xda".pack('n', 2)."DATA\xff\xd9"; |
| 220 | $out = Media::strip($jpeg, 'image/jpeg'); |
| 221 | $test->assertFalse(str_contains($out, 'GPS!')); |
| 222 | $test->assertFalse(str_contains($out, 'note')); |
| 223 | $test->assertStringContains('JFIF', $out); |
| 224 | $test->assertTrue(str_ends_with($out, "DATA\xff\xd9")); |
| 225 | |
| 226 | $chunk = fn($t, $d) => pack('N', strlen($d)).$t.$d.pack('N', crc32($t.$d)); |
| 227 | $png = "\x89PNG\r\n\x1a\n".$chunk('IHDR', pack('NNCCCCC', 1, 1, 8, 2, 0, 0, 0)).$chunk('tEXt', "Comment\0secret") |
| 228 | .$chunk('eXIf', 'MM').$chunk('IDAT', 'x').$chunk('IEND', ''); |
| 229 | $out = Media::strip($png, 'image/png'); |
| 230 | $test->assertFalse(str_contains($out, 'secret')); |
| 231 | $test->assertFalse(str_contains($out, 'eXIf')); |
| 232 | $test->assertStringContains('IDAT', $out); |
| 233 | $test->assertStringContains('IEND', $out); |
| 234 | |
| 235 | $riff = fn($t, $d) => $t.pack('V', strlen($d)).$d.(strlen($d) & 1 ? "\0" : ''); |
| 236 | $body = $riff('VP8X', "\x0c\0\0\0\0\0\0\0\0\0").$riff('VP8L', 'IMG').$riff('EXIF', 'GPS!').$riff('XMP ', '<x:secret/>'); |
| 237 | $out = Media::strip('RIFF'.pack('V', 4 + strlen($body)).'WEBP'.$body, 'image/webp'); |
| 238 | $test->assertFalse(str_contains($out, 'GPS!')); |
| 239 | $test->assertFalse(str_contains($out, 'secret')); |
| 240 | $test->assertStringContains('IMG', $out); |
| 241 | $test->assertEquals(0, ord($out[20]) & 0x0c); |
| 242 | $test->assertEquals(strlen($out) - 8, unpack('V', substr($out, 4, 4))[1]); |
| 243 | }); |
| 244 | }); |
| 245 | |
| 246 | $test->describe('マルチユーザーのFediverse(2つのサーバー)', function($test) use ($use, $mkuser, $seed, $pump, $tmp, $alice, $bob, $carol): void { |
| 247 | if (!ACTIVITYPUB_MULTIUSER) { |
| 248 | $test->skipAll('マルチユーザーモードが無効(FEDIINFOのisSingleUserがtrue、又はAUTH_ENABLEDが無効)'); |
| 249 | } |
| 250 | if (ACTIVITYPUB_MULTIUSER) { |
| 251 | $mkuser('A', 'alice', 1); |
| 252 | $mkuser('A', 'carol', 2); |
| 253 | $mkuser('A', 'dave', 3, 0); // BANされた |
| 254 | $mkuser('B', 'bob', 1); |
| 255 | $seed('A', 'B', 'bob'); |
| 256 | $seed('B', 'A', 'alice'); |
| 257 | $seed('B', 'A', 'carol'); |
| 258 | $use('A'); |
| 259 | Fedi::write(Fedi::path('remote/webfinger/'.sha1('bob@b.example').'.json'), ['url' => $bob, 'at' => time()]); |
| 260 | } |
| 261 | |
| 262 | $test->it('アクターとWebFingerを返すはず', function($test) use ($use, $alice): void { |
| 263 | $use('A'); |
| 264 | $doc = Actor::document(Fedi::localActor('alice')); |
| 265 | $test->assertEquals($alice, $doc['id']); |
| 266 | $test->assertEquals("{$alice}/inbox", $doc['inbox']); |
| 267 | $test->assertEquals('https://1.1.1.1/ap/inbox', $doc['endpoints']['sharedInbox']); |
| 268 | $test->assertStringContains('I am alice', $doc['summary']); |
| 269 | $test->assertEquals(ass_url('user/noicon.png', 'https://1.1.1.1'), $doc['icon']['url']); |
| 270 | $test->assertEquals($alice, Actor::webfinger('acct:alice@1.1.1.1')['links'][0]['href']); |
| 271 | $test->assertNull(Actor::webfinger('acct:alice@other.example')); |
| 272 | $test->assertNull(Actor::webfinger('acct:nobody@1.1.1.1')); |
| 273 | // BANされたユーザーはアクターにならない |
| 274 | $test->assertNull(Fedi::localActor('dave')); |
| 275 | }); |
| 276 | |
| 277 | $test->it('このサイトのアカウントを検索出来るはず(ブログのアカウントも)', function($test) use ($use, $alice): void { |
| 278 | $use('A'); |
| 279 | // テストのサーバーはIPアドレスなので、「@user@host」はWebFingerで確認する |
| 280 | $test->assertEquals($alice, Remote::webfinger('alice', '1.1.1.1')); |
| 281 | $test->assertEquals($alice, Remote::resolve('@alice')); |
| 282 | $blog = FEDIINFO['actor']; |
| 283 | $test->assertEquals(Fedi::blogActorUrl(), Remote::webfinger($blog, '1.1.1.1')); |
| 284 | $test->assertEquals(Fedi::blogActorUrl(), Remote::webfinger(strtoupper($blog), '1.1.1.1')); |
| 285 | $test->assertEquals(Fedi::blogActorUrl(), Remote::resolve("@{$blog}")); |
| 286 | $test->assertNull(Remote::webfinger('nobody', '1.1.1.1')); |
| 287 | $test->assertNull(Remote::resolve('@dave'), 'BANされたユーザー'); |
| 288 | }); |
| 289 | |
| 290 | $test->it('リモートのユーザーをフォローして承認されるはず', function($test) use ($use, $pump, $alice, $bob): void { |
| 291 | $use('A'); |
| 292 | $test->assertTrue(Social::follow('alice', $bob)->isSuccess); |
| 293 | $test->assertEquals('pending', Actor::following('alice')[$bob]['state']); |
| 294 | $test->assertEquals(['Follow:202', 'Accept:202'], $pump()); |
| 295 | $use('A'); |
| 296 | $test->assertTrue(Actor::isFollowing('alice', $bob)); |
| 297 | // 承認されたら、相手の最近の投稿を次の配信の時に取得する |
| 298 | $test->assertArrayHasKey($bob, Fedi::read(Fedi::path('backfill.json'))); |
| 299 | $use('B'); |
| 300 | $test->assertTrue(Actor::isFollowedBy('bob', $alice)); |
| 301 | $test->assertEquals('follow', Actor::notifications('bob')[0]['type']); |
| 302 | }); |
| 303 | |
| 304 | $test->it('送信ボックスからはそのアクターの公開・未収載の投稿だけを取り出すはず', function($test) use ($bob): void { |
| 305 | $doc = ['id' => $bob, 'followers' => "{$bob}/followers"]; |
| 306 | $note = fn(string $n, array $to, array $cc = [], ?string $by = null) => ['type' => 'Create', 'object' => [ |
| 307 | 'id' => "https://8.8.8.8/n/{$n}", 'type' => 'Note', 'attributedTo' => $by ?? $bob, 'to' => $to, 'cc' => $cc, 'content' => $n]]; |
| 308 | $items = [ |
| 309 | $note('public', [Fedi::PUBLIC]), |
| 310 | $note('unlisted', ["{$bob}/followers"], [Fedi::PUBLIC]), |
| 311 | $note('followers', ["{$bob}/followers"]), |
| 312 | $note('direct', ['https://1.1.1.1/ap/users/alice']), |
| 313 | $note('other', [Fedi::PUBLIC], [], 'https://8.8.8.8/ap/users/eve'), |
| 314 | ['type' => 'Announce', 'object' => 'https://9.9.9.9/n/x'], |
| 315 | ['type' => 'Create', 'object' => 'https://8.8.8.8/n/string'], |
| 316 | ['type' => 'Create', 'object' => ['id' => 'https://9.9.9.9/n/spoof', 'type' => 'Note', 'attributedTo' => $bob, 'to' => [Fedi::PUBLIC]]], |
| 317 | ]; |
| 318 | $got = array_map(fn($o) => $o['content'], Remote::outboxNotes($doc, $items)); |
| 319 | $test->assertEquals(['public', 'unlisted'], $got); |
| 320 | }); |
| 321 | |
| 322 | $test->it('リモートの画像は署名付きでこのサイト経由にするはず', function($test) use ($use): void { |
| 323 | $use('A'); |
| 324 | $test->assertEquals('', Remote::imageUrl('')); |
| 325 | $test->assertEquals(Fedi::base().'/static/a.png', Remote::imageUrl(Fedi::base().'/static/a.png')); |
| 326 | $url = 'https://8.8.8.8/media/a.webp'; |
| 327 | $test->assertEquals('/microblog/media?u='.rawurlencode($url).'&s='.Remote::imageSig($url), Remote::imageUrl($url)); |
| 328 | $test->assertTrue(Remote::imageSig($url) !== Remote::imageSig($url.'?x')); |
| 329 | // 形式は中身で判断し、SVG等は受け付けない |
| 330 | $test->assertEquals('image/png', Remote::imageType("\x89PNG\r\n\x1a\n....")); |
| 331 | $test->assertEquals('image/jpeg', Remote::imageType("\xff\xd8\xff\xe0....")); |
| 332 | $test->assertEquals('image/gif', Remote::imageType('GIF89a....')); |
| 333 | $test->assertEquals('image/webp', Remote::imageType('RIFF....WEBPVP8 ')); |
| 334 | $test->assertEquals('image/avif', Remote::imageType("\x00\x00\x00\x1cftypavif")); |
| 335 | $test->assertNull(Remote::imageType('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>')); |
| 336 | $test->assertNull(Remote::imageType('<html>')); |
| 337 | }); |
| 338 | |
| 339 | $test->it('フォローしている人の投稿がホームに届くはず', function($test) use ($use, $pump): void { |
| 340 | $use('B'); |
| 341 | $test->assertTrue(Social::post('bob', 'Hello #fedi')->isSuccess); |
| 342 | $test->assertEquals(['Create:202'], $pump()); |
| 343 | $use('A'); |
| 344 | [$home] = Timeline::query('home', 'alice'); |
| 345 | $test->assertCount(1, $home); |
| 346 | $test->assertStringContains('Hello', $home[0]['object']['content']); |
| 347 | $test->assertCount(1, Timeline::query('federated', null)[0]); |
| 348 | $test->assertCount(0, Timeline::query('local', null)[0]); |
| 349 | $test->assertCount(1, Timeline::query('tag', null, ['tag' => 'fedi'])[0]); |
| 350 | }); |
| 351 | |
| 352 | $test->it('いいね・ブースト・返信が相手に届くはず', function($test) use ($use, $pump): void { |
| 353 | $use('A'); |
| 354 | $id = Timeline::query('home', 'alice')[0][0]['object']['id']; |
| 355 | $test->assertTrue(Social::like('alice', $id)->isSuccess); |
| 356 | $test->assertTrue(Social::boost('alice', $id)->isSuccess); |
| 357 | $test->assertTrue(Social::post('alice', '@bob@b.example いいね!', ['inReplyTo' => $id])->isSuccess); |
| 358 | $pump(); |
| 359 | $use('B'); |
| 360 | $note = Notes::get(Fedi::localNoteId($id)[1]); |
| 361 | $test->assertCount(1, $note['likes']); |
| 362 | $test->assertCount(1, $note['boosts']); |
| 363 | $test->assertCount(1, $note['replies']); |
| 364 | $types = array_column(Actor::notifications('bob'), 'type'); |
| 365 | foreach (['like', 'boost', 'reply'] as $t) $test->assertTrue(in_array($t, $types, true), "通知「{$t}」が無い"); |
| 366 | // 返信は返信先のスレッドに出る |
| 367 | $test->assertCount(1, Timeline::replies($id)); |
| 368 | }); |
| 369 | |
| 370 | $test->it('取り消しも届くはず', function($test) use ($use, $pump): void { |
| 371 | $use('A'); |
| 372 | $id = Timeline::query('home', 'alice', ['limit' => 50])[0][count(Timeline::query('home', 'alice', ['limit' => 50])[0]) - 1]['object']['id']; |
| 373 | $test->assertTrue(Social::unlike('alice', $id)->isSuccess); |
| 374 | $test->assertTrue(Social::unboost('alice', $id)->isSuccess); |
| 375 | $pump(); |
| 376 | $use('B'); |
| 377 | $note = Notes::get(Fedi::localNoteId($id)[1]); |
| 378 | $test->assertCount(0, $note['likes']); |
| 379 | $test->assertCount(0, $note['boosts']); |
| 380 | }); |
| 381 | |
| 382 | $test->it('承認制のアカウントはリクエストを承認するまでフォローされないはず', function($test) use ($use, $pump, $alice, $carol): void { |
| 383 | $use('A'); |
| 384 | Actor::saveSettings('alice', ['locked' => true]); |
| 385 | $test->assertTrue(Social::follow('carol', $alice)->isSuccess); |
| 386 | $test->assertEquals('pending', Actor::following('carol')[$alice]['state']); |
| 387 | $test->assertTrue(isset(Actor::requests('alice')[$carol])); |
| 388 | $test->assertTrue(Social::answerRequest('alice', $carol, true)->isSuccess); |
| 389 | $test->assertTrue(Actor::isFollowing('carol', $alice)); |
| 390 | $test->assertTrue(Actor::isFollowedBy('alice', $carol)); |
| 391 | Actor::saveSettings('alice', ['locked' => false]); |
| 392 | }); |
| 393 | |
| 394 | $test->it('フォロワー限定とダイレクトは関係ある人だけ見えるはず', function($test) use ($use, $pump): void { |
| 395 | $use('A'); |
| 396 | $test->assertTrue(Social::post('alice', 'followers only', ['visibility' => 'followers'])->isSuccess); |
| 397 | $test->assertTrue(Social::post('alice', '@bob@b.example secret', ['visibility' => 'direct'])->isSuccess); |
| 398 | $pump(); |
| 399 | $use('A'); |
| 400 | $texts = fn($items) => array_map(fn($i) => Html::text($i['object']['content']), $items); |
| 401 | $carolHome = $texts(Timeline::query('home', 'carol')[0]); |
| 402 | $test->assertTrue(in_array('followers only', $carolHome, true), 'フォロワーに見えない'); |
| 403 | $test->assertFalse(in_array('@bob secret', $carolHome, true), '関係無い人にダイレクトが見える'); |
| 404 | $test->assertFalse(in_array('followers only', $texts(Timeline::query('local', null)[0]), true)); |
| 405 | $test->assertFalse(in_array('followers only', $texts(Timeline::query('user', null, ['user' => 'alice'])[0]), true)); |
| 406 | |
| 407 | $use('B'); |
| 408 | $bobHome = $texts(Timeline::query('home', 'bob')[0]); |
| 409 | $test->assertTrue(in_array('@bob secret', $bobHome, true), 'ダイレクトが届かない'); |
| 410 | // bobはaliceのフォロワーではない |
| 411 | $test->assertFalse(in_array('followers only', $bobHome, true)); |
| 412 | $test->assertTrue(in_array('mention', array_column(Actor::notifications('bob'), 'type'), true)); |
| 413 | }); |
| 414 | |
| 415 | $test->it('編集と削除が届くはず', function($test) use ($use, $pump): void { |
| 416 | $use('B'); |
| 417 | $own = Timeline::query('user', 'bob', ['user' => 'bob'])[0][0]['object']['id']; |
| 418 | $id = Fedi::localNoteId($own)[1]; |
| 419 | $test->assertTrue(Social::edit('bob', $id, 'Edited #changed')->isSuccess); |
| 420 | $pump(); |
| 421 | $use('A'); |
| 422 | $test->assertEquals('Edited #changed', Html::text(Remote::stored($own)['content'])); |
| 423 | $test->assertCount(1, Timeline::query('tag', null, ['tag' => 'changed'])[0]); |
| 424 | $test->assertCount(0, Timeline::query('tag', null, ['tag' => 'fedi'])[0]); |
| 425 | |
| 426 | $use('B'); |
| 427 | $test->assertTrue(Social::delete('bob', $id)->isSuccess); |
| 428 | $pump(); |
| 429 | $use('A'); |
| 430 | $test->assertNull(Remote::stored($own)); |
| 431 | $test->assertFalse(in_array($own, array_map(fn($i) => $i['object']['id'], Timeline::query('federated', null)[0]), true)); |
| 432 | }); |
| 433 | |
| 434 | $test->it('他人の投稿は編集・削除出来ないはず', function($test) use ($use): void { |
| 435 | $use('A'); |
| 436 | $mine = Timeline::query('user', 'alice', ['user' => 'alice'])[0][0]['object']['id']; |
| 437 | $id = Fedi::localNoteId($mine)[1]; |
| 438 | $test->assertFalse(Social::edit('carol', $id, 'x')->isSuccess); |
| 439 | $test->assertFalse(Social::delete('carol', $id)->isSuccess); |
| 440 | }); |
| 441 | |
| 442 | $test->it('偽装したアクティビティは受け付けないはず', function($test) use ($use, $alice, $bob): void { |
| 443 | $use('A'); |
| 444 | // ローカルのアクターを名乗るリモートのアクティビティ |
| 445 | $test->assertEquals(403, Inbox::handle(['type' => 'Like', 'actor' => $alice, 'object' => 'x'])[0]); |
| 446 | // 他人の投稿として作られたCreate |
| 447 | $test->assertEquals(403, Inbox::handle(['type' => 'Create', 'actor' => $bob, |
| 448 | 'object' => ['type' => 'Note', 'id' => 'https://8.8.8.8/n/1', 'attributedTo' => 'https://8.8.8.8/ap/users/eve', 'to' => [Fedi::PUBLIC]]])[0]); |
| 449 | // 違うサーバーのIDのNote |
| 450 | $test->assertEquals(403, Inbox::handle(['type' => 'Create', 'actor' => $bob, |
| 451 | 'object' => ['type' => 'Note', 'id' => 'https://9.9.9.9/n/1', 'attributedTo' => $bob, 'to' => [Fedi::PUBLIC]]])[0]); |
| 452 | // 他人のフォローの取り消し |
| 453 | $test->assertEquals(202, Inbox::handle(['type' => 'Undo', 'actor' => $bob, |
| 454 | 'object' => ['type' => 'Follow', 'actor' => 'https://8.8.8.8/ap/users/eve', 'object' => $alice]])[0]); |
| 455 | // 誰にも関係の無い投稿は保存しない |
| 456 | Inbox::handle(['type' => 'Create', 'actor' => 'https://8.8.8.8/ap/users/stranger', |
| 457 | 'object' => ['type' => 'Note', 'id' => 'https://8.8.8.8/n/spam', 'attributedTo' => 'https://8.8.8.8/ap/users/stranger', 'to' => [Fedi::PUBLIC], 'content' => 'spam']]); |
| 458 | $test->assertNull(Remote::stored('https://8.8.8.8/n/spam')); |
| 459 | }); |
| 460 | |
| 461 | $test->it('ブロックするとフォロー関係が無くなり、投稿が見えなくなるはず', function($test) use ($use, $pump, $alice, $bob): void { |
| 462 | $use('B'); |
| 463 | $test->assertTrue(Social::block('bob', $alice)->isSuccess); |
| 464 | $pump(); |
| 465 | $use('A'); |
| 466 | $test->assertFalse(Actor::isFollowing('alice', $bob)); |
| 467 | $use('B'); |
| 468 | $test->assertFalse(Actor::isFollowedBy('bob', $alice)); |
| 469 | $test->assertTrue(Actor::isBlocked('bob', $alice)); |
| 470 | // ブロックしている人からのフォローは拒否する |
| 471 | $use('A'); |
| 472 | Social::follow('alice', $bob); |
| 473 | $pump(); |
| 474 | $use('A'); |
| 475 | $test->assertFalse(isset(Actor::following('alice')[$bob])); |
| 476 | $use('B'); |
| 477 | $test->assertTrue(Social::unblock('bob', $alice)->isSuccess); |
| 478 | $pump(); |
| 479 | }); |
| 480 | |
| 481 | $test->it('サイト全体でドメインをブロック出来るはず', function($test) use ($use, $bob): void { |
| 482 | $use('A'); |
| 483 | $test->assertFalse(Social::blockInstance('1.1.1.1')->isSuccess); |
| 484 | $test->assertTrue(Social::blockInstance('evil.example')->isSuccess); |
| 485 | $test->assertTrue(Actor::isDomainBlocked('https://sub.evil.example/u/x')); |
| 486 | $test->assertFalse(Actor::isDomainBlocked('https://notevil.example/u/x')); |
| 487 | $test->assertEquals(403, Inbox::handle(['type' => 'Follow', 'actor' => 'https://evil.example/u/x', 'object' => 'x'])[0]); |
| 488 | // 待ち行列にも入れない |
| 489 | Delivery::enqueue('alice', ['type' => 'Note', 'id' => 'x'], ['https://evil.example/inbox']); |
| 490 | $test->assertEquals(0, Delivery::pending()); |
| 491 | $test->assertTrue(Social::blockInstance('evil.example', false)->isSuccess); |
| 492 | $test->assertFalse(Actor::isDomainBlocked('https://evil.example/u/x')); |
| 493 | }); |
| 494 | |
| 495 | $test->it('通報を記録し、相手のサーバーにも送るはず', function($test) use ($use, $pump, $bob): void { |
| 496 | $use('A'); |
| 497 | $test->assertTrue(Social::report('alice', $bob, [], '迷惑です')->isSuccess); |
| 498 | $test->assertEquals('迷惑です', Social::reports()[0]['content']); |
| 499 | $pump(); |
| 500 | $use('B'); |
| 501 | $test->assertTrue((bool)Social::reports()[0]['remote']); |
| 502 | $test->assertEquals('迷惑です', Social::reports()[0]['content']); |
| 503 | }); |
| 504 | |
| 505 | $test->it('アカウントの削除で全部から消えるはず', function($test) use ($use, $pump, $bob): void { |
| 506 | $use('A'); |
| 507 | Social::follow('alice', $bob); |
| 508 | $pump(); |
| 509 | $use('A'); |
| 510 | $test->assertTrue(Actor::isFollowing('alice', $bob)); |
| 511 | Inbox::handle(['type' => 'Delete', 'actor' => $bob, 'object' => $bob]); |
| 512 | $test->assertFalse(isset(Actor::following('alice')[$bob])); |
| 513 | $test->assertNull(Remote::cachedActor($bob)); |
| 514 | }); |
| 515 | |
| 516 | $test->it('待ち行列は失敗したら間隔を空けて再試行するはず', function($test) use ($use): void { |
| 517 | $use('A'); |
| 518 | foreach (glob(Fedi::path('queue/').'*.json') ?: [] as $f) unlink($f); |
| 519 | $failing = new class extends Delivery { |
| 520 | public static int $calls = 0; |
| 521 | public static bool $ok = false; |
| 522 | protected static function send(string $from, string $inbox, array $activity): bool { |
| 523 | self::$calls++; |
| 524 | return self::$ok; |
| 525 | } |
| 526 | protected static function runBackfill(int $budget): int { |
| 527 | return 0; |
| 528 | } |
| 529 | }; |
| 530 | $failing::enqueue('alice', ['type' => 'Like', 'id' => 'x'], ['https://9.9.9.9/inbox']); |
| 531 | $res = $failing::run(); |
| 532 | $test->assertEquals(['sent' => 0, 'failed' => 1, 'dropped' => 0, 'backfilled' => 0], $res->data); |
| 533 | // 次の時刻までは送らない |
| 534 | $failing::run(); |
| 535 | $test->assertEquals(1, $failing::$calls); |
| 536 | $job = glob(Fedi::path('queue/').'*.json')[0]; |
| 537 | $data = Fedi::read($job); |
| 538 | $data['next'] = time() - 1; |
| 539 | Fedi::write($job, $data); |
| 540 | $failing::$ok = true; |
| 541 | $test->assertEquals(['sent' => 1, 'failed' => 0, 'dropped' => 0, 'backfilled' => 0], $failing::run()->data); |
| 542 | $test->assertEquals(0, Delivery::pending()); |
| 543 | }); |
| 544 | |
| 545 | $test->it('古いリモートの投稿を消すはず', function($test) use ($use): void { |
| 546 | $use('A'); |
| 547 | $old = ['id' => 'https://8.8.8.8/n/old', 'type' => 'Note', 'attributedTo' => 'https://8.8.8.8/ap/users/x', |
| 548 | 'to' => [Fedi::PUBLIC], 'content' => 'old', 'published' => Fedi::now(time() - 200 * 86400)]; |
| 549 | Remote::store($old); |
| 550 | Timeline::add($old); |
| 551 | $res = Timeline::cleanup(90); |
| 552 | $test->assertTrue($res->data['removed'] >= 1); |
| 553 | $test->assertNull(Remote::stored($old['id'])); |
| 554 | // ローカルの投稿は消さない |
| 555 | $test->assertTrue(count(Timeline::query('user', 'alice', ['user' => 'alice'])[0]) > 0); |
| 556 | }); |
| 557 | |
| 558 | $test->it('GETの署名を検証出来るはず', function($test) use ($use, $alice): void { |
| 559 | $use('A'); |
| 560 | $key = Actor::privateKey('alice'); |
| 561 | $test->assertNotNull($key); |
| 562 | $ap = new class extends Activitypub { |
| 563 | public array $docs = []; |
| 564 | public function fetchRemoteJson(string $url): ?array { return $this->docs[$url] ?? null; } |
| 565 | }; |
| 566 | $ap->docs[$alice] = Actor::document(Fedi::localActor('alice')); |
| 567 | $headers = []; |
| 568 | foreach ($ap->signRequest('https://8.8.8.8/ap/users/bob/notes/x', '', $key, 'get', Actor::keyId('alice')) as $line) { |
| 569 | [$k, $v] = explode(': ', $line, 2); |
| 570 | $headers[$k] = $v; |
| 571 | } |
| 572 | $server = $_SERVER; |
| 573 | try { |
| 574 | $_SERVER['REQUEST_METHOD'] = 'GET'; |
| 575 | $_SERVER['REQUEST_URI'] = '/ap/users/bob/notes/x'; |
| 576 | $_SERVER['HTTP_HOST'] = $headers['Host']; |
| 577 | $_SERVER['HTTP_DATE'] = $headers['Date']; |
| 578 | $_SERVER['HTTP_SIGNATURE'] = $headers['Signature']; |
| 579 | $test->assertEquals($alice, $ap->signer()); |
| 580 | $_SERVER['REQUEST_URI'] = '/ap/users/bob/notes/y'; |
| 581 | $test->assertNull($ap->signer()); |
| 582 | } finally { |
| 583 | $_SERVER = $server; |
| 584 | } |
| 585 | }); |
| 586 | }); |
| 587 | |
| 588 | // 後片付け |
| 589 | Fedi::$baseUrl = Fedi::$dataDir = Fedi::$userDir = null; |
| 590 | $rm = function(string $dir) use (&$rm): void { |
| 591 | foreach (scandir($dir) ?: [] as $f) { |
| 592 | if ($f === '.' || $f === '..') continue; |
| 593 | is_dir("{$dir}/{$f}") ? $rm("{$dir}/{$f}") : @unlink("{$dir}/{$f}"); |
| 594 | } |
| 595 | @rmdir($dir); |
| 596 | }; |
| 597 | if (is_dir($tmp)) $rm($tmp); |
| 598 | |
| 599 | $test->printSummary(); |