Explorar o código

🔒️ POST /v2/share 加鉴权:只有资源拥有者能添加协作者

原实现既不校验登录、也不校验资源归属,任何人(包括匿名请求)都能给任意
channel / 文章 / 文集签 editor 权限,再凭它改别人的译文与术语——属于
「会污染数据库数据」,按 CLAUDE.md 铁律 2 第 ② 条直接修 v2。

- 未登录 401,非拥有者 403;拥有者按 res_type 到对应表里查
  (channel、文章、文集、工作流 / 项目、AI 模型),谎报 res_type 只会被拒
- 拥有者的请求与响应形状不变(v4 的 CollaboratorAdd 还在调),先录快照测试再改
- 顺带:store 补了中文说明与 @bodyParam,规格与 schema.d.ts 随之重生

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda hai 3 días
pai
achega
f93d6ebfa7

+ 47 - 2
api-v13/app/Http/Controllers/ShareController.php

@@ -4,7 +4,12 @@ namespace App\Http\Controllers;
 
 use App\Http\Api\ShareApi;
 use App\Http\Resources\ShareResource;
+use App\Models\AiModel;
+use App\Models\Article;
+use App\Models\Channel;
+use App\Models\Collection;
 use App\Models\GroupInfo;
+use App\Models\Project;
 use App\Models\Share;
 use App\Services\AuthService;
 use Illuminate\Http\Request;
@@ -80,13 +85,32 @@ class ShareController extends Controller
     }
 
     /**
-     * Store a newly created resource in storage.
+     * 为资源添加协作者。
+     *
+     * 只有资源拥有者能调用(与 update / destroy 的「power > 20」同口径)。
+     * 资源归属按 res_type 到对应表里查,查不到即拒绝——客户端谎报 res_type
+     * 只会让自己被拒,不会绕过校验。
+     *
+     * @bodyParam res_id string required 资源 uid
+     * @bodyParam res_type integer required 资源类型:2 channel、3 文章、4 文集、6 工作流、7 项目、8 AI 模型
+     * @bodyParam user_id string[] required 协作者 uid 列表(用户或群组)
+     * @bodyParam user_type string required 协作者类型。Enum: user,group
+     * @bodyParam role string required 协作者角色。Enum: manager,editor,reader
      *
      * @return Response
      */
     public function store(Request $request)
     {
-        //
+        $currUser = AuthService::current($request);
+        if (! $currUser) {
+            return $this->error(__('auth.failed'), null, 401);
+        }
+        $resId = (string) $request->input('res_id');
+        $owner = $this->resourceOwner((int) $request->input('res_type'), $resId);
+        if ($owner !== $currUser['user_uid']) {
+            return $this->error(__('auth.failed'), null, 403);
+        }
+
         foreach ($request->input('user_id') as $key => $value) {
             if (! Str::isUuid($value)) {
                 continue;
@@ -119,6 +143,27 @@ class ShareController extends Controller
         return $this->ok(count($request->input('user_id')));
     }
 
+    /**
+     * 按资源类型查资源拥有者的 uid,类型不认识或资源不存在时返回 null。
+     *
+     * 类型编号见 ShareApi::getResList() 的注释与前端 EResType。
+     */
+    private function resourceOwner(int $resType, string $resId): ?string
+    {
+        if ($resId === '') {
+            return null;
+        }
+
+        return match ($resType) {
+            2 => Channel::where('uid', $resId)->value('owner_uid'),
+            3 => Article::where('uid', $resId)->value('owner'),
+            4 => Collection::where('uid', $resId)->value('owner'),
+            6, 7 => Project::where('uid', $resId)->value('owner_id'),
+            8 => AiModel::where('uid', $resId)->value('owner_id'),
+            default => null,
+        };
+    }
+
     /**
      * Display the specified resource.
      *

+ 165 - 0
api-v13/tests/Feature/ShareStoreTest.php

@@ -0,0 +1,165 @@
+<?php
+
+use App\Models\AiModel;
+use App\Models\Article;
+use App\Models\Project;
+use App\Models\Share;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/**
+ * POST /v2/share(添加协作者)的快照测试。
+ *
+ * 原实现不校验登录也不校验资源归属,任何人都能给任意资源签 editor(power 20),
+ * 再凭它改别人的译文。修复只收紧「谁能调」,拥有者的请求与响应形状保持不变——
+ * v4 的 CollaboratorAdd 还在调它。
+ */
+function shareChannelPayload(string $resId, array $userIds, string $role = 'editor', int $resType = 2): array
+{
+    return [
+        'res_id' => $resId,
+        'res_type' => $resType,
+        'user_id' => $userIds,
+        'user_type' => 'user',
+        'role' => $role,
+    ];
+}
+
+function makeShareArticle(string $ownerUid): string
+{
+    $uid = (string) Str::uuid();
+    (new Article)->forceFill([
+        'id' => random_int(1, PHP_INT_MAX),
+        'uid' => $uid,
+        'title' => 'article',
+        'owner' => $ownerUid,
+        'owner_id' => 0,
+        'editor_id' => 0,
+        'create_time' => time() * 1000,
+        'modify_time' => time() * 1000,
+    ])->save();
+
+    return $uid;
+}
+
+function makeShareProject(string $ownerUid): string
+{
+    $uid = (string) Str::uuid();
+    (new Project)->forceFill([
+        'uid' => $uid,
+        'title' => 'project',
+        'owner_id' => $ownerUid,
+        'editor_id' => $ownerUid,
+    ])->save();
+
+    return $uid;
+}
+
+function makeShareAiModel(string $ownerUid): string
+{
+    $uid = (string) Str::uuid();
+    (new AiModel)->forceFill([
+        'id' => random_int(1, PHP_INT_MAX),
+        'uid' => $uid,
+        'name' => 'model',
+        'real_name' => 'model-'.Str::random(6),
+        'model' => 'gpt-4',
+        'owner_id' => $ownerUid,
+        'editor_id' => $ownerUid,
+    ])->save();
+
+    return $uid;
+}
+
+it('lets the channel owner add an editor', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $friend = makeStudio('friend');
+
+    $this->postJson('/api/v2/share', shareChannelPayload($channel, [$friend]), authHeader($owner))
+        ->assertOk()
+        ->assertJsonPath('ok', true)
+        ->assertJsonPath('data', 1);
+
+    $row = Share::where('res_id', $channel)->where('cooperator_id', $friend)->first();
+    expect($row)->not->toBeNull();
+    expect((int) $row->power)->toBe(20);
+    expect((int) $row->cooperator_type)->toBe(0);
+});
+
+it('maps the reader role to power 10', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $friend = makeStudio('friend');
+
+    $this->postJson('/api/v2/share', shareChannelPayload($channel, [$friend], 'reader'), authHeader($owner))
+        ->assertJsonPath('ok', true);
+
+    expect((int) Share::where('res_id', $channel)->value('power'))->toBe(10);
+});
+
+it('lets owners share articles, projects and ai models', function (int $resType, Closure $make) {
+    $owner = makeStudio('owner');
+    $resId = $make($owner);
+    $friend = makeStudio('friend');
+
+    $this->postJson('/api/v2/share', shareChannelPayload($resId, [$friend], 'editor', $resType), authHeader($owner))
+        ->assertJsonPath('ok', true);
+
+    expect(Share::where('res_id', $resId)->where('cooperator_id', $friend)->exists())->toBeTrue();
+})->with([
+    'article' => [3, fn (string $owner) => makeShareArticle($owner)],
+    'project' => [7, fn (string $owner) => makeShareProject($owner)],
+    'ai model' => [8, fn (string $owner) => makeShareAiModel($owner)],
+]);
+
+it('rejects anonymous requests', function () {
+    $channel = makeChannel(makeStudio('owner'));
+    $attacker = makeStudio('attacker');
+
+    $this->postJson('/api/v2/share', shareChannelPayload($channel, [$attacker]))
+        ->assertStatus(401)
+        ->assertJsonPath('ok', false);
+
+    expect(Share::where('res_id', $channel)->exists())->toBeFalse();
+});
+
+it('rejects users who do not own the resource', function () {
+    $channel = makeChannel(makeStudio('owner'));
+    $attacker = makeStudio('attacker');
+
+    $this->postJson('/api/v2/share', shareChannelPayload($channel, [$attacker]), authHeader($attacker))
+        ->assertStatus(403)
+        ->assertJsonPath('ok', false);
+
+    expect(Share::where('res_id', $channel)->exists())->toBeFalse();
+});
+
+it('rejects a wrong res_type that would hide the real owner', function () {
+    $owner = makeStudio('owner');
+    $article = makeShareArticle($owner);
+    $attacker = makeStudio('attacker');
+
+    // 资源是 article,attacker 却谎称它是自己名下的 channel
+    $this->postJson('/api/v2/share', shareChannelPayload($article, [$attacker], 'editor', 2), authHeader($attacker))
+        ->assertStatus(403);
+
+    expect(Share::where('res_id', $article)->exists())->toBeFalse();
+});
+
+it('does not let an editor collaborator add more collaborators', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $editor = makeStudio('editor');
+    $outsider = makeStudio('outsider');
+
+    $this->postJson('/api/v2/share', shareChannelPayload($channel, [$editor]), authHeader($owner))
+        ->assertJsonPath('ok', true);
+
+    $this->postJson('/api/v2/share', shareChannelPayload($channel, [$outsider]), authHeader($editor))
+        ->assertStatus(403);
+
+    expect(Share::where('res_id', $channel)->where('cooperator_id', $outsider)->exists())->toBeFalse();
+});

+ 23 - 9
dashboard-v6/src/api/schema.d.ts

@@ -5841,8 +5841,12 @@ export interface paths {
         get: operations["get_api_v2_share"];
         put?: never;
         /**
-         * 新建 share
-         * @description 实现:`ShareController@store`
+         * 为资源添加协作者。
+         * @description 只有资源拥有者能调用(与 update / destroy 的「power > 20」同口径)。
+         *     资源归属按 res_type 到对应表里查,查不到即拒绝——客户端谎报 res_type
+         *     只会让自己被拒,不会绕过校验。
+         *
+         *     实现:`ShareController@store`
          */
         post: operations["post_api_v2_share"];
         delete?: never;
@@ -28302,15 +28306,25 @@ export interface operations {
             path?: never;
             cookie?: never;
         };
-        requestBody?: {
+        requestBody: {
             content: {
                 "application/json": {
-                    user_id?: string;
-                    res_id?: string;
-                    res_type?: string;
-                    user_type?: string;
-                    /** @enum {string} */
-                    role?: "manager" | "editor" | "reader";
+                    /** @description 资源 uid */
+                    res_id: string;
+                    /** @description 资源类型:2 channel、3 文章、4 文集、6 工作流、7 项目、8 AI 模型 */
+                    res_type: number;
+                    /** @description 协作者 uid 列表(用户或群组) */
+                    user_id: unknown[];
+                    /**
+                     * @description 协作者类型
+                     * @enum {string}
+                     */
+                    user_type: "user" | "group";
+                    /**
+                     * @description 协作者角色
+                     * @enum {string}
+                     */
+                    role: "manager" | "editor" | "reader";
                 };
             };
         };

+ 1 - 1
openapi/public/assets/protocol/main.yaml

@@ -7,7 +7,7 @@ info:
 
     由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。
     响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
-  version: 2026.11.12
+  version: 2026.11.13
 servers:
   -
     url: /api

+ 25 - 6
openapi/public/assets/protocol/resources/auto/v2-share.yaml

@@ -77,32 +77,51 @@ get:
     422:
       $ref: '../../main.yaml#/components/responses/ValidationError'
 post:
-  summary: '新建 share'
+  summary: 为资源添加协作者。
   tags:
     - share
   operationId: post_api_v2_share
-  description: 实现:`ShareController@store`
+  description: |-
+    只有资源拥有者能调用(与 update / destroy 的「power > 20」同口径)。
+    资源归属按 res_type 到对应表里查,查不到即拒绝——客户端谎报 res_type
+    只会让自己被拒,不会绕过校验。
+
+    实现:`ShareController@store`
   requestBody:
-    required: false
+    required: true
     content:
       application/json:
         schema:
           type: object
           properties:
-            user_id:
-              type: string
             res_id:
               type: string
+              description: '资源 uid'
             res_type:
-              type: string
+              type: integer
+              description: '资源类型:2 channel、3 文章、4 文集、6 工作流、7 项目、8 AI 模型'
+            user_id:
+              type: array
+              description: '协作者 uid 列表(用户或群组)'
             user_type:
               type: string
+              description: 协作者类型
+              enum:
+                - user
+                - group
             role:
               type: string
+              description: 协作者角色
               enum:
                 - manager
                 - editor
                 - reader
+          required:
+            - res_id
+            - res_type
+            - user_id
+            - user_type
+            - role
   responses:
     200:
       description: '成功。业务失败时 HTTP 仍可能为 200,以 ok 字段为准。'