0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

S3 Presigned URLでContent-MD5を使った安全なファイルアップロード

0
Posted at

S3 Presigned URLでContent-MD5は本当に必要?安全なファイルアップロードの実装方法

S3 Presigned URLを使ったファイルアップロードを実装していた際、アップロードするファイルの内容まで保証したい場面がありました。

調べてみると、AWS S3では Content-MD5 を利用することで、アップロードするファイルの整合性を検証できることが分かりました。

今回は、その仕組みと実装方法を簡単に紹介します。


Content-MD5とは

Content-MD5は、ファイルの内容から計算されるMD5ハッシュ値です。

S3へアップロードするときにこの値を一緒に送ることで、

  • リクエストで指定したContent-MD5
  • 実際にアップロードされたファイル

が一致しているかをS3側で検証できます。

つまり、

「アップロードできる」だけではなく、「想定した内容のファイルをアップロードしているか」まで確認できるようになります。


実装の流れ

今回の実装では、以下の流れで対応しました。

1. フロントでContent-MD5を計算する

const contentMd5 = await createContentMd5(file);

2. Presigned URL取得APIへ送る

await api.createSignedUrl({
  filename: file.name,
  contentType: file.type,
  contentMd5,
});

今回はTypeSpecでAPIを管理していたため、contentMd5を追加してOpenAPIを再生成しました。


3. Presigned URL生成時にContentMD5を指定する

new PutObjectCommand({
  Bucket,
  Key,
  ContentType,
  ContentMD5: contentMd5,
});

4. PUT時にも同じContent-MD5を付与する

await fetch(signedUrl, {
  method: "PUT",
  headers: {
    "Content-MD5": contentMd5,
  },
  body: file,
});

Presigned URLを生成するときだけでなく、実際のアップロード時にも同じContent-MD5を送る必要があります。


まとめ

Content-MD5を利用することで、

  • アップロードされたファイルの整合性をS3側で検証できる
  • アップロード途中で内容が変わっていないことを確認できる
  • Presigned URLを利用したアップロードの信頼性を高められる

ようになります。

実装自体はContent-MD5を追加するだけですが、安全性を高めたい場合には取り入れる価値があると感じました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?