Skip to content

Commit f730cc1

Browse files
committed
Harden against denial of service and account takeover
From a security review of the new code: - Render markdown in a worker thread with a 5 s budget, and reject bodies saturated with emphasis markers up front: some inputs make CommonMark parsing quadratic and could freeze the server for tens of seconds - Make excerpt and reading-time helpers linear (truncate first, bounded patterns, line-based code fence stripping); they run on every page view - Only auto-link a GitHub login to an existing account whose e-mail is verified; GitHub-created accounts are verified, changing the e-mail clears the verification - Never write multipart bodies to disk (no upload feature), cap request bodies at 1 MB in Caddy - Rate-limit edits, likes, solutions, pin/lock, settings and the preview - Hide comments of unpublished articles from profiles and the dashboard; only the author can publish their draft - Count replies correctly under concurrent deletes; double-clicking a like no longer returns a 500 - CI deploy job is skipped with a warning when secrets are not configured
1 parent dae3ecf commit f730cc1

21 files changed

Lines changed: 499 additions & 116 deletions

‎.github/workflows/deploy-staging.yml‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,12 +53,25 @@ jobs:
5353
name: staging
5454
url: https://staging.javascript.cm
5555
steps:
56+
- name: Check deploy secrets
57+
id: secrets
58+
env:
59+
HOST: ${{ secrets.STAGING_HOST }}
60+
run: |
61+
if [ -z "$HOST" ]; then
62+
echo "::warning title=Deploy skipped::STAGING_SSH_KEY, STAGING_KNOWN_HOSTS, STAGING_HOST and STAGING_SSH_USER secrets are not configured."
63+
echo "ready=false" >> "$GITHUB_OUTPUT"
64+
else
65+
echo "ready=true" >> "$GITHUB_OUTPUT"
66+
fi
5667
- name: Configure SSH
68+
if: steps.secrets.outputs.ready == 'true'
5769
run: |
5870
install -m 700 -d ~/.ssh
5971
echo "${{ secrets.STAGING_SSH_KEY }}" > ~/.ssh/deploy_key
6072
chmod 600 ~/.ssh/deploy_key
6173
echo "${{ secrets.STAGING_KNOWN_HOSTS }}" > ~/.ssh/known_hosts
6274
# The key is restricted server-side (forced command): it can only run the deploy script.
6375
- name: Deploy
76+
if: steps.secrets.outputs.ready == 'true'
6477
run: ssh -i ~/.ssh/deploy_key ${{ secrets.STAGING_SSH_USER }}@${{ secrets.STAGING_HOST }} deploy

‎app/controllers/article_actions_controller.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ export default class ArticleActionsController {
5757
*/
5858
async publish({ params, auth, response, session }: HttpContext) {
5959
const { article, allowed } = await managedArticle(params.slug, auth.user!)
60-
if (!allowed) {
60+
if (!allowed || article.userId !== auth.user!.id) {
6161
session.flash('error', 'Seul l’auteur de cet article peut le publier.')
6262
return response.redirect().back()
6363
}

‎app/controllers/auth/github_controller.ts‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { DateTime } from 'luxon'
12
import string from '@adonisjs/core/helpers/string'
23
import type { HttpContext } from '@adonisjs/core/http'
34
import User from '#models/user'
@@ -28,12 +29,22 @@ export default class GithubController {
2829

2930
if (!user && profile.email) {
3031
// Link the GitHub account to an existing account with the same e-mail.
31-
user = await User.findBy('email', profile.email.toLowerCase())
32-
if (user) {
33-
user.githubId = profile.id
34-
user.githubUsername = profile.login
35-
user.avatarUrl = user.avatarUrl ?? profile.avatarUrl
36-
await user.save()
32+
const existing = await User.findBy('email', profile.email.toLowerCase())
33+
if (existing && !existing.emailVerifiedAt) {
34+
// Local e-mails are not verified: auto-linking would let anyone who
35+
// registered with someone else's address capture their GitHub login.
36+
session.flash(
37+
'error',
38+
'Un compte existe déjà avec cette adresse e-mail. Connectez-vous avec votre mot de passe.'
39+
)
40+
return response.redirect().toRoute('login')
41+
}
42+
if (existing) {
43+
existing.githubId = profile.id
44+
existing.githubUsername = profile.login
45+
existing.avatarUrl = existing.avatarUrl ?? profile.avatarUrl
46+
await existing.save()
47+
user = existing
3748
}
3849
}
3950

@@ -59,6 +70,8 @@ export default class GithubController {
5970
twitterUsername: profile.twitterUsername,
6071
password: null,
6172
role: 'member',
73+
// GitHub only returns verified addresses.
74+
emailVerifiedAt: DateTime.now(),
6275
})
6376
session.flash('success', `Bienvenue dans la communauté, ${user.displayName} !`)
6477
} else {

‎app/controllers/profile_controller.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,25 @@ export type ReplySummary = ReturnType<typeof replySummary>
5757
* Query modifier: the parents a reply summary needs (only light columns).
5858
*/
5959
export function withReplyParents(query: ModelQueryBuilderContract<typeof Reply>) {
60-
return query
61-
.preload('thread', (q) => q.select('id', 'slug', 'title', 'solution_reply_id'))
62-
.preload('discussion', (q) => q.select('id', 'slug', 'title'))
63-
.preload('article', (q) => q.select('id', 'slug', 'title'))
60+
return (
61+
query
62+
// Comments on articles that went back to draft must not leak their title.
63+
.where((q) =>
64+
q
65+
.whereNull('replies.article_id')
66+
.orWhereIn(
67+
'replies.article_id',
68+
db
69+
.from('articles')
70+
.select('id')
71+
.whereNotNull('published_at')
72+
.where('published_at', '<=', db.raw('now()'))
73+
)
74+
)
75+
.preload('thread', (q) => q.select('id', 'slug', 'title', 'solution_reply_id'))
76+
.preload('discussion', (q) => q.select('id', 'slug', 'title'))
77+
.preload('article', (q) => q.select('id', 'slug', 'title'))
78+
)
6479
}
6580

6681
export default class ProfileController {

‎app/controllers/replies_controller.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,16 @@ export default class RepliesController {
4242
.where('user_id', auth.user!.id)
4343
.where('reply_id', reply.id)
4444
.first()
45-
if (existing) await existing.delete()
46-
else if (reply.userId !== auth.user!.id)
47-
await Like.create({ userId: auth.user!.id, replyId: reply.id })
45+
if (existing) {
46+
await existing.delete()
47+
} else if (reply.userId !== auth.user!.id) {
48+
try {
49+
await Like.create({ userId: auth.user!.id, replyId: reply.id })
50+
} catch (error) {
51+
// Double click: the unique (user_id, reply_id) index already holds it.
52+
if ((error as { code?: string }).code !== '23505') throw error
53+
}
54+
}
4855
return response.redirect().back()
4956
}
5057
}

‎app/controllers/settings_controller.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,11 @@ export default class SettingsController {
4343
)
4444

4545
const usernameChanged = data.username !== user.username
46+
if (data.email !== user.email) {
47+
// A new address is unverified until proven otherwise (GitHub sign-in
48+
// only links accounts whose e-mail is verified).
49+
user.emailVerifiedAt = null
50+
}
4651
user.merge({
4752
name: data.name,
4853
username: data.username,
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { Exception } from '@adonisjs/core/exceptions'
2+
import type { HttpContext } from '@adonisjs/core/http'
3+
4+
/**
5+
* Raised when markdown takes too long to render (pathological input).
6+
* Sends the member back to the form with an explanation instead of a 500.
7+
*/
8+
export default class MarkdownTooComplexException extends Exception {
9+
static status = 422
10+
static code = 'E_MARKDOWN_TOO_COMPLEX'
11+
static message =
12+
'Ce contenu est trop complexe à mettre en forme. Simplifiez la mise en forme (gras, italique, liens imbriqués) puis réessayez.'
13+
14+
async handle(error: this, ctx: HttpContext) {
15+
if (ctx.request.accepts(['html', 'json']) === 'json' && !ctx.request.header('x-inertia')) {
16+
return ctx.response.status(error.status).send({ message: error.message })
17+
}
18+
ctx.session.flashExcept(['password', 'passwordConfirmation'])
19+
ctx.session.flash('error', error.message)
20+
return ctx.response.redirect().back()
21+
}
22+
}

0 commit comments

Comments
 (0)