MeWrite Docs

PermissionDenied: Requires read/write/net permission

Denoで権限が不足している場合のエラー

概要

Denoはセキュリティファーストのランタイムで、ファイル、ネットワーク、環境変数などへのアクセスには明示的な権限が必要です。権限なしでアクセスしようとするとこのエラーが発生します。

エラーメッセージ

error: PermissionDenied: Requires read access to "/path/to/file", run again with the --allow-read flag
error: PermissionDenied: Requires net access to "api.example.com:443", run again with the --allow-net flag
error: PermissionDenied: Requires env access to "API_KEY", run again with the --allow-env flag

権限の種類

フラグ説明
--allow-readファイル読み取り
--allow-writeファイル書き込み
--allow-netネットワークアクセス
--allow-env環境変数アクセス
--allow-runサブプロセス実行
--allow-ffiFFI(外部関数)呼び出し
--allow-all / -Aすべての権限

解決策

1. 必要な権限を指定して実行

1
2
3
4
5
6
7
8
# 読み取り権限
deno run --allow-read script.ts

# ネットワーク権限
deno run --allow-net script.ts

# 複数の権限
deno run --allow-read --allow-net --allow-env script.ts

2. 特定のパス/ホストのみ許可

1
2
3
4
5
6
7
8
# 特定のディレクトリのみ読み取り許可
deno run --allow-read=/tmp,./data script.ts

# 特定のホストのみネットワーク許可
deno run --allow-net=api.example.com,localhost:3000 script.ts

# 特定の環境変数のみ許可
deno run --allow-env=API_KEY,DATABASE_URL script.ts

3. deno.jsonで設定

1
2
3
4
5
6
7
// deno.json
{
  "tasks": {
    "dev": "deno run --allow-read --allow-net --allow-env src/main.ts",
    "start": "deno run --allow-read=./data --allow-net=api.example.com src/main.ts"
  }
}
1
deno task dev

4. すべての権限を許可(開発時のみ)

1
2
# 開発時のみ使用(本番では推奨しない)
deno run -A script.ts

5. 権限をプロンプトで確認

1
2
# 権限が必要な時にプロンプトで確認
deno run --prompt script.ts

6. コード内で権限を確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// 権限を確認してから処理
const status = await Deno.permissions.query({ name: "read", path: "/tmp" });

if (status.state === "granted") {
  const data = await Deno.readTextFile("/tmp/file.txt");
} else if (status.state === "prompt") {
  // ユーザーに権限を要求
  const request = await Deno.permissions.request({ name: "read", path: "/tmp" });
  if (request.state === "granted") {
    const data = await Deno.readTextFile("/tmp/file.txt");
  }
} else {
  console.error("Read permission denied");
}

7. サブプロセス実行の権限

1
2
3
4
5
# サブプロセスを実行する場合
deno run --allow-run script.ts

# 特定のコマンドのみ許可
deno run --allow-run=git,npm script.ts
1
2
3
4
5
// script.ts
const command = new Deno.Command("git", {
  args: ["status"],
});
const output = await command.output();

本番環境でのベストプラクティス

1
2
3
4
5
6
7
# 最小権限の原則
deno run \
  --allow-read=./public,./config \
  --allow-write=./logs \
  --allow-net=0.0.0.0:8000,api.example.com \
  --allow-env=NODE_ENV,PORT,API_KEY \
  server.ts

Deno Deployでの権限

Deno Deployでは以下の権限が自動的に付与されます:

  • --allow-net(すべてのネットワーク)
  • --allow-read(デプロイされたファイルのみ)
  • --allow-env(設定された環境変数のみ)

関連エラー

関連エラー

最終更新: 2025-12-18