activitypub.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import { ActivityDelete, ActivityPubSignature, HttpStatusCode } from '@peertube/peertube-models'
  2. import { isActorDeleteActivityValid } from '@server/helpers/custom-validators/activitypub/actor.js'
  3. import { getAPId } from '@server/lib/activitypub/activity.js'
  4. import { wrapWithSpanAndContext } from '@server/lib/opentelemetry/tracing.js'
  5. import { NextFunction, Request, Response } from 'express'
  6. import { logger } from '../helpers/logger.js'
  7. import { isHTTPSignatureVerified, parseHTTPSignature } from '../helpers/peertube-crypto.js'
  8. import { ACCEPT_HEADERS, ACTIVITY_PUB, HTTP_SIGNATURE } from '../initializers/constants.js'
  9. import { getOrCreateAPActor, loadActorUrlOrGetFromWebfinger } from '../lib/activitypub/actors/index.js'
  10. export async function checkSignature (req: Request, res: Response, next: NextFunction) {
  11. try {
  12. const httpSignatureChecked = await checkHttpSignature(req, res)
  13. if (httpSignatureChecked !== true) return
  14. const actor = res.locals.signature.actor
  15. // Forwarded activity
  16. const bodyActor = req.body.actor
  17. const bodyActorId = getAPId(bodyActor)
  18. if (bodyActorId && bodyActorId !== actor.url) {
  19. const jsonLDSignatureChecked = await checkJsonLDSignature(req, res)
  20. if (jsonLDSignatureChecked !== true) return
  21. }
  22. return next()
  23. } catch (err) {
  24. const activity: ActivityDelete = req.body
  25. if (isActorDeleteActivityValid(activity) && activity.object === activity.actor) {
  26. logger.debug('Handling signature error on actor delete activity', { err })
  27. return res.status(HttpStatusCode.NO_CONTENT_204).end()
  28. }
  29. logger.warn('Error in ActivityPub signature checker.', { err })
  30. return res.fail({
  31. status: HttpStatusCode.FORBIDDEN_403,
  32. message: 'ActivityPub signature could not be checked'
  33. })
  34. }
  35. }
  36. export function executeIfActivityPub (req: Request, res: Response, next: NextFunction) {
  37. const accepted = req.accepts(ACCEPT_HEADERS)
  38. if (accepted === false || ACTIVITY_PUB.POTENTIAL_ACCEPT_HEADERS.includes(accepted) === false) {
  39. // Bypass this route
  40. return next('route')
  41. }
  42. logger.debug('ActivityPub request for %s.', req.url)
  43. return next()
  44. }
  45. // ---------------------------------------------------------------------------
  46. // Private
  47. // ---------------------------------------------------------------------------
  48. async function checkHttpSignature (req: Request, res: Response) {
  49. return wrapWithSpanAndContext('peertube.activitypub.checkHTTPSignature', async () => {
  50. // FIXME: compatibility with http-signature < v1.3
  51. const sig = req.headers[HTTP_SIGNATURE.HEADER_NAME] as string
  52. if (sig && sig.startsWith('Signature ') === true) req.headers[HTTP_SIGNATURE.HEADER_NAME] = sig.replace(/^Signature /, '')
  53. let parsed: any
  54. try {
  55. parsed = parseHTTPSignature(req, HTTP_SIGNATURE.CLOCK_SKEW_SECONDS)
  56. } catch (err) {
  57. logger.warn('Invalid signature because of exception in signature parser', { reqBody: req.body, err })
  58. res.fail({
  59. status: HttpStatusCode.FORBIDDEN_403,
  60. message: err.message
  61. })
  62. return false
  63. }
  64. const keyId = parsed.keyId
  65. if (!keyId) {
  66. res.fail({
  67. status: HttpStatusCode.FORBIDDEN_403,
  68. message: 'Invalid key ID',
  69. data: {
  70. keyId
  71. }
  72. })
  73. return false
  74. }
  75. logger.debug('Checking HTTP signature of actor %s...', keyId)
  76. let [ actorUrl ] = keyId.split('#')
  77. if (actorUrl.startsWith('acct:')) {
  78. actorUrl = await loadActorUrlOrGetFromWebfinger(actorUrl.replace(/^acct:/, ''))
  79. }
  80. const actor = await getOrCreateAPActor(actorUrl)
  81. const verified = isHTTPSignatureVerified(parsed, actor)
  82. if (verified !== true) {
  83. logger.warn('Signature from %s is invalid', actorUrl, { parsed })
  84. res.fail({
  85. status: HttpStatusCode.FORBIDDEN_403,
  86. message: 'Invalid signature',
  87. data: {
  88. actorUrl
  89. }
  90. })
  91. return false
  92. }
  93. res.locals.signature = { actor }
  94. return true
  95. })
  96. }
  97. async function checkJsonLDSignature (req: Request, res: Response) {
  98. // Lazy load the module as it's quite big with json.ld dependency
  99. const { compactJSONLDAndCheckSignature } = await import('../helpers/peertube-jsonld.js')
  100. return wrapWithSpanAndContext('peertube.activitypub.JSONLDSignature', async () => {
  101. const signatureObject: ActivityPubSignature = req.body.signature
  102. if (!signatureObject?.creator) {
  103. res.fail({
  104. status: HttpStatusCode.FORBIDDEN_403,
  105. message: 'Object and creator signature do not match'
  106. })
  107. return false
  108. }
  109. const [ creator ] = signatureObject.creator.split('#')
  110. logger.debug('Checking JsonLD signature of actor %s...', creator)
  111. const actor = await getOrCreateAPActor(creator)
  112. const verified = await compactJSONLDAndCheckSignature(actor, req)
  113. if (verified !== true) {
  114. logger.warn('Signature not verified.', req.body)
  115. res.fail({
  116. status: HttpStatusCode.FORBIDDEN_403,
  117. message: 'Signature could not be verified'
  118. })
  119. return false
  120. }
  121. res.locals.signature = { actor }
  122. return true
  123. })
  124. }