セキュリティヘッダー
CoddyのNode.jsジャーニー「認証とセキュリティ」セクションの一部。レッスン 15/17。
ブラウザーは既定で推測し、情報を共有します。テキストの回答をスクリプトとして扱ったり、ページのアドレスをリンク先のすべてのサイトに送信したり、あらゆる場所からスクリプトを実行したりすることがあります。いくつかのレスポンスヘッダーを設定すれば、これらを無効にできます。
X-Content-Type-Options: nosniff:Content-Typeを信頼し、決して推測しません。Referrer-Policy: no-referrer:どのページがリンク元だったかを他のサイトに伝えません。Content-Security-Policy: default-src 'self':スクリプト、スタイル、画像をこのサイトからのみ読み込みます。
ExpressはさらにX-Powered-By: Expressも追加します。これは攻撃者に試すべきことを知らせてしまいます。app.disable('x-powered-by')を使うと削除できます。1つのミドルウェアですべてのレスポンスにヘッダーを設定できます。
app.use((req, res, next) => {
res.set('Strict-Transport-Security', 'max-age=31536000');
res.set('Permissions-Policy', 'camera=(), microphone=()');
next();
});チャレンジ
簡単- すべての応答に
X-Content-Type-Options: nosniffとReferrer-Policy: no-referrerが設定されています。 - ページには
Content-Security-Policy: default-src 'self'も設定されています。すべての応答に設定して問題ありません。 - どの応答にも
X-Powered-Byは含まれていません。
GET /notes を送信し、Headers を開きます。ログインして、GET / でも同じ操作をします。
自分で試してみよう
import express from 'express';
import { ObjectId } from 'mongodb';
import { randomBytes } from 'node:crypto';
import { parseCookies } from './cookies.js';
import { notes, sessions, users } from './db.js';
import { hashPassword, verifyPassword } from './passwords.js';
const app = express();
app.use(express.json());
// 唯一の管理者アカウント。パスワードは環境変数から取得する。
await users.insertOne({ username: 'admin', role: 'admin', passwordHash: await hashPassword(process.env.ADMIN_PASSWORD) });
app.post('/signup', async (req, res) => {
const username = String(req.body.username ?? '').trim().toLowerCase();
const password = String(req.body.password ?? '');
if (!username || password.length < 8) {
return res.status(400).json({ error: 'Pick a username and a password of at least 8 characters' });
}
if (await users.findOne({ username })) {
return res.status(409).json({ error: 'That username is taken' });
}
await users.insertOne({ username, role: 'member', passwordHash: await hashPassword(password) });
res.status(201).json({ username });
});
app.post('/login', async (req, res) => {
const username = String(req.body.username ?? '').trim().toLowerCase();
const user = await users.findOne({ username });
if (!user || !(await verifyPassword(String(req.body.password ?? ''), user.passwordHash))) {
return res.status(401).json({ error: 'Wrong username or password' });
}
const sid = randomBytes(24).toString('base64url');
await sessions.insertOne({ _id: sid, userId: user._id, createdAt: new Date() });
res.cookie('sid', sid, {
httpOnly: true,
sameSite: 'lax',
secure: true,
maxAge: 24 * 60 * 60 * 1000,
});
res.json({ username: user.username });
});
// セッションCookieに対応するユーザーを検索し、見つからなければ401を返す。
async function requireUser(req, res, next) {
const { sid } = parseCookies(req.get('cookie'));
const session = sid && (await sessions.findOne({ _id: sid }));
const user = session && (await users.findOne({ _id: session.userId }));
if (!user) {
return res.status(401).json({ error: 'Log in first' });
}
req.user = { id: user._id.toHexString(), username: user.username, role: user.role };
next();
}
// ログイン中のユーザーがこのロールを持っていなければ403を返す。
function requireRole(role) {
return (req, res, next) => {
if (req.user.role !== role) {
return res.status(403).json({ error: 'Not allowed' });
}
next();
};
}
app.get('/me', requireUser, (req, res) => {
res.json({ username: req.user.username });
});
app.post('/logout', async (req, res) => {
const { sid } = parseCookies(req.get('cookie'));
if (sid) {
await sessions.deleteOne({ _id: sid });
}
res.clearCookie('sid');
res.status(204).end();
});
// 自分のノートをページとして表示する。
app.get('/', requireUser, async (req, res) => {
const list = await notes.find({ owner: req.user.id }).toArray();
const items = list.map((note) => `<li>${note.text}</li>`).join('');
res.send(`<!doctype html><title>Vault</title><h1>${req.user.username}'s notes</h1><ul>${items}</ul>`);
});
// ノート:各ユーザーは自分のノートだけを読み書きする。
app.get('/notes', requireUser, async (req, res) => {
res.json(await notes.find({ owner: req.user.id }).toArray());
});
app.post('/notes', requireUser, async (req, res) => {
const note = { owner: req.user.id, text: String(req.body.text ?? '') };
await notes.insertOne(note);
res.status(201).json(note);
});
app.get('/notes/:id', requireUser, async (req, res) => {
if (!ObjectId.isValid(req.params.id)) {
return res.status(404).json({ error: 'Note not found' });
}
const note = await notes.findOne({ _id: new ObjectId(req.params.id), owner: req.user.id });
if (!note) {
return res.status(404).json({ error: 'Note not found' });
}
res.json(note);
});
app.delete('/notes/:id', requireUser, async (req, res) => {
if (!ObjectId.isValid(req.params.id)) {
return res.status(404).json({ error: 'Note not found' });
}
const { deletedCount } = await notes.deleteOne({ _id: new ObjectId(req.params.id), owner: req.user.id });
if (!deletedCount) {
return res.status(404).json({ error: 'Note not found' });
}
res.status(204).end();
});
// 管理者向け:アカウントの総数を示す。
app.get('/admin', requireUser, requireRole('admin'), async (req, res) => {
res.json({ users: await users.countDocuments() });
});
app.listen(3000, () => {
console.log('Vault is running on port 3000');
});
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。