| 1 | import { Injectable, NestMiddleware } from '@nestjs/common'; |
| 2 | import { AuthService } |
| 3 | import type { NextFunction, |
| 4 | |
| 5 | import type { Auth |
| 6 | import { RepositoryNotFoundError } |
| 7 | import { AuthenticationRequiredError } |
| 8 | import { RepositoryAccessService } |
| 9 | import { type Actor |
| 10 | import { GitAuthenticatedBufferedRequest } |
| 11 | |
| 12 | /** Runs before the body is spooled, so a rejected push never reaches disk. */ |
| 13 | @Injectable() |
| 14 | export class GitBasicAuthMiddleware |
| 15 | constructor( |
| 16 | private readonly auth |
| 17 | private readonly access |
| 18 | ) {} |
| 19 | |
| 20 | async use( |
| 21 | req: GitAuthenticatedBufferedRequest |
| 22 | res: Response |
| 23 | next: NextFunction |
| 24 | ) { |
| 25 | const { username, |
| 26 | if (!username || |
| 27 | |
| 28 | // Git asks for the receive-pack advertisement before it pushes, so a read-only actor is turned away at `info/refs` rather than a round trip later. |
| 29 | const isPush = |
| 30 | req.path.endsWith |
| 31 | req.query.service |
| 32 | |
| 33 | try { |
| 34 | const actor = |
| 35 | req.repository = |
| 36 | username, |
| 37 | repo: repo.replace |
| 38 | actor, |
| 39 | operation: isPush ? |
| 40 | }); |
| 41 | |
| 42 | req.actor = |
| 43 | next(); |
| 44 | } catch (error) |
| 45 | if (!(error |
| 46 | // Git only sends credentials once challenged, so this is not a dead end. |
| 47 | res.setHeader('WWW-Authenticate |
| 48 | res.status(401) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | private async resolveActor |
| 53 | const header = |
| 54 | if (!header?.startsWith |
| 55 | |
| 56 | // Username is ignored; the password is the API key, and may contain ":". |
| 57 | const decoded = |
| 58 | const key = |
| 59 | if (!key) |
| 60 | |
| 61 | const { valid, |
| 62 | body: { key |
| 63 | }); |
| 64 | |
| 65 | // A bad key is treated as no key, so the caller is challenged again. |
| 66 | return valid && |
| 67 | } |
| 68 | } |