Skip to content

fix: authenticate pusher from push credentials instead of commit metadata - #46

Open
devin-ai-integration[bot] wants to merge 5 commits into
mainfrom
devin/sfind-5b09d88d-authenticated-pusher-identity
Open

devin-ai-integration[bot] wants to merge 5 commits into
mainfrom
devin/sfind-5b09d88d-authenticated-pusher-identity

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Description

Corrige o finding de code scan sfind-5b09d88d24924f329984167c8e40eaea (medium/high): a identidade do pusher era lida da linha committer do último commit dentro do pack enviado pelo cliente. Qualquer pessoa podia colocar o e-mail de outro usuário permitido no commit e assim (a) passar pelo checkUserPushPermission e (b) aprovar/rejeitar o próprio push no dashboard, além de corromper a trilha de auditoria.

O que mudou

  • parsePush não define mais action.user / action.userEmail a partir do committer (apenas registra os metadados do commit no log).
  • Novo src/proxy/processors/pusherIdentity.ts: lê o header Authorization (Basic) do push e resolve a conta SCM autenticada:
    • GitHub: GET https://api.github.com/user com as credenciais do push → login do dono do token;
    • GitLab (hostname contém gitlab): GET <host>/api/v4/user → username;
    • servidores self-hosted listados na nova config basicAuthHosts (que validam usuário/senha Basic por conta própria, ex.: htpasswd/LDAP): o proxy confirma que o servidor rejeita acesso anônimo (GET <repo>/info/refs?service=git-receive-pack sem credenciais → 401/403) e aceita as credenciais do push (mesma requisição → 200) e só então usa o username do Basic auth. Essa regra tem precedência sobre a regra de GitLab por hostname (mas não sobre github.com, que sempre usa a API);
    • outros servidores git: push bloqueado (fail closed), pois o username do Basic auth sozinho não prova quem é o dono do token.
  • As credenciais são verificadas uma vez por push (getVerifiedGitAccount, cache em WeakMap por Action), compartilhado entre resolvePusher e checkUserPushPermission.
  • Novo processor resolvePusher (logo após parsePush, antes dos push plugins): resolve o mesmo pusher autenticado e preenche action.user / action.userEmail para que plugins vejam uma identidade confiável. Nunca bloqueia; quem aplica a regra é o checkUserPushPermission. Plugins agora são inseridos após resolvePusher (splice(2, ...)).
  • checkUserPushPermission mapeia a conta autenticada (case-insensitive) para o usuário GitProxy via User.gitAccount, bloqueia credenciais ausentes/inválidas/rejeitadas e contas duplicadas, verifica isUserPushAllowed com esse usuário e grava action.user / action.userEmail a partir dele.
  • src/service/routes/push.ts: os guards "Cannot approve/reject your own changes" continuam usando push.userEmail, que agora é o pusher autenticado (só renomeados committerEmail → pusherEmail e mensagens de erro).
  • Docs: docs/Processors.md e docs/Architecture.md.

⚠️ Mudança de comportamento / contrato

  • Pushes agora exigem que o usuário GitProxy tenha gitAccount igual à conta SCM das credenciais usadas no push; antes bastava o e-mail do committer coincidir. Usuários sem gitAccount correto passam a ser bloqueados.
  • Pushes para hosts que não são github.com, GitLab nem listados em basicAuthHosts passam a ser bloqueados, pois o proxy não consegue verificar o dono das credenciais.
  • Nova chave de configuração basicAuthHosts (string[], opcional) em config.schema.json / src/config/generated/config.ts; test-e2e.proxy.config.json passa a listar git-server. Não listar servidores que aceitam qualquer username junto com um token.
  • Para GitHub/GitLab, o proxy chama a API /user do provedor (timeout 10s) uma vez por push.
  • Push plugins passam a rodar depois de resolvePusher e recebem action.user / action.userEmail do usuário autenticado, não mais do committer.
  • Mensagens de erro da API de aprovação/rejeição mudam de "committer's email address" para "pusher's email address".

Related Issue

Finding sfind-5b09d88d24924f329984167c8e40eaea (scan scan-70082f73b42b43fda8ae0a7ecbe7fedf). Upstream: finos#1400

Como testar

  1. Crie dois usuários GitProxy: alice (gitAccount: alice-gh, aprovadora canAuthorise) e bob (gitAccount: bob-gh, canPush).
  2. Como alice, configure git config user.email <email do bob>, faça um commit e push via proxy usando o token da alice.
  3. Esperado: o push é atribuído a alice (não ao bob) e, no dashboard, alice recebe "Cannot approve your own changes".
  4. Push com credenciais de uma conta sem usuário GitProxy vinculado (mesmo com e-mail de committer de um usuário permitido) → bloqueado.

Testes automatizados: npx vitest run test/processors/checkUserPushPermission.test.ts test/processors/pusherIdentity.test.ts test/processors/resolvePusher.test.ts test/chain.test.ts test/testParsePush.test.ts test/testCheckUserPushPermission.test.ts test/testPush.test.ts

Checklist

General

Documentation

  • Documentation has been added/updated for any new features

Configuration

  • config.schema.json modificado (basicAuthHosts); src/config/generated/config.ts atualizado manualmente seguindo o formato do quicktype (o build regenera)
    • TypeScript types regenerados (npm run generate-config-types) — editados à mão; o npm run build regenera
    • Schema reference docs regenerados (npm run gen-schema-doc) — json-schema-for-humans indisponível na VM; seção 24 (basicAuthHosts) adicionada à mão em website/docs/configuration/reference.mdx no formato do gerador (propriedade movida para o fim do schema, sem renumerar seções existentes)

Tests

  • Tests have been added/updated for new functionality
  • Unit tests pass (npm test) — rodados localmente apenas test/processors/{checkUserPushPermission,pusherIdentity,resolvePusher}.test.ts e test/testParsePush.test.ts (todos passando); o restante (chain.test, testCheckUserPushPermission com DB, testPush) depende do CI, pois o registry npm estava bloqueado na VM
  • Formatting (prettier aplicado nos arquivos alterados); [ ] npm run lint / [ ] npm run check-types — pendentes no CI pelo mesmo motivo

Devin-Org: engineering

Link to Devin session: https://devin-gtm.devinenterprise.com/sessions/ae2da50eb6fa428191b67f5332333284
Open in Devin Desktop: https://devin-gtm.devinenterprise.com/desktop/session/ae2da50eb6fa428191b67f5332333284?variant=devin


Devin Review

Status Commit
⚪ Not started —

Run Devin Review

Enable auto-review to review your pull requests automatically.

Devin Review (Staging)


Devin Review

@devin-ai-integration

Copy link
Copy Markdown
Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

Scanned Files

None

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 1 new potential issue.

1 flag not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

Comment on lines +72 to +76
if (anonymous.status !== 401 && anonymous.status !== 403) {
step.log(
`${upstream.host} does not require authentication for pushes, cannot verify the pusher`,
);
return null;

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Hidden private repositories reject valid pushes

When a configured server returns 404 for anonymous discovery, verifyBasicAuthCredentials rejects the push without checking valid credentials. Private repositories hidden from anonymous users cannot be pushed.

Learn more

The Basic-auth host check uses an anonymous git-receive-pack discovery request before testing the client's credentials. A server can hide a private repository by returning 404 to unauthenticated callers while authenticating the same request with valid Basic credentials. Here, the 404 exits before the authenticated request, so a valid user's push is blocked. The existing permission check treats the resulting null account as an authentication failure.

Example: A self-hosted server maps anonymous 401 responses to 404 for /team/private.git/info/refs, but returns 200 with alice's Basic credentials. With that server listed in basicAuthHosts, Alice's push stops after the 404 instead of reaching the successful authenticated check.

Recommended fix: Allow an anonymous 404 only when a subsequent authenticated request to the same repository returns a valid receive-pack advertisement. Keep rejecting anonymous success and authenticated failure, and test the hidden-private-repository case.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, this is a valid case. Accepting an anonymous 404 doesn't weaken the check, because the username is still trusted only when the authenticated request returns 200. A server that hides private repos would also return 404 for wrong credentials. The fix is to allow 401/403/404 on the anonymous request, keep rejecting anonymous 2xx and authenticated non-200 responses, and add a test for a hidden private repo. I'm holding further pushes to this PR until the requester replies about CI. This fix will go into the next commit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants