diff --git a/.env.example b/.env.example index 5c9f6b3..90576ec 100644 --- a/.env.example +++ b/.env.example @@ -59,6 +59,9 @@ BOT_STATUS_INTERVAL_SECONDS=60 GITEA_URL=https://gitea.nocode-var.tech # Token with least privilege (read:repository, write:issue). Never log it. GITEA_TOKEN= +# Admin token for the recruitment flow (write:admin, write:organization, read:user). +# Leave empty to fall back to GITEA_TOKEN. +GITEA_RECRUITMENT_TOKEN= GITEA_OWNER=FWS GITEA_REPO=FWS-Arch # Organisation qui accueille les personnes recrutées (défaut : GITEA_OWNER) diff --git a/README.en.md b/README.en.md index a0c39d6..131b505 100644 --- a/README.en.md +++ b/README.en.md @@ -142,16 +142,17 @@ Full template: [`.env.example`](.env.example). Default values in brackets. ### Gitea -| Variable | Default | Description | -| ------------------- | ------------- | ---------------------------------------------------------------------- | -| `GITEA_URL` | — | Instance URL (without a trailing `/`) | -| `GITEA_TOKEN` | — | Least privilege token (`read:repository`, `write:issue`). Never logged | -| `GITEA_OWNER` | — | Repository owner (e.g. `FWS`) | -| `GITEA_ORG` | `GITEA_OWNER` | Organization that hosts recruited people | -| `GITEA_DEV_TEAM` | `Dev` | Gitea team they join on acceptance | -| `GITEA_REPO` | — | Target repository (e.g. `FWS-Arch`) | -| `GITEA_TIMEOUT_MS` | `10000` | Request timeout | -| `GITEA_MAX_RETRIES` | `2` | Retries on transient errors (429, 5xx, timeout) | +| Variable | Default | Description | +| ------------------------- | ------------- | ---------------------------------------------------------------------------------- | +| `GITEA_URL` | — | Instance URL (without a trailing `/`) | +| `GITEA_TOKEN` | — | Least privilege token (`read:repository`, `write:issue`). Never logged | +| `GITEA_RECRUITMENT_TOKEN` | `GITEA_TOKEN` | Admin token (`write:admin`, `write:organization`, `read:user`) used by recruitment | +| `GITEA_OWNER` | — | Repository owner (e.g. `FWS`) | +| `GITEA_ORG` | `GITEA_OWNER` | Organization that hosts recruited people | +| `GITEA_DEV_TEAM` | `Dev` | Gitea team they join on acceptance | +| `GITEA_REPO` | — | Target repository (e.g. `FWS-Arch`) | +| `GITEA_TIMEOUT_MS` | `10000` | Request timeout | +| `GITEA_MAX_RETRIES` | `2` | Retries on transient errors (429, 5xx, timeout) | ### Gitea webhooks diff --git a/README.md b/README.md index eae73cd..da5d1e9 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,7 @@ Modèle complet : [`.env.example`](.env.example). Valeurs par défaut entre pare | --- | --- | --- | | `GITEA_URL` | — | URL de l'instance (sans `/` final) | | `GITEA_TOKEN` | — | Token à moindre privilège (`read:repository`, `write:issue`). Jamais loggé | +| `GITEA_RECRUITMENT_TOKEN` | `GITEA_TOKEN` | Jeton admin (`write:admin`, `write:organization`, `read:user`) réservé au recrutement | | `GITEA_OWNER` | — | Propriétaire du dépôt (ex. `FWS`) | | `GITEA_ORG` | `GITEA_OWNER` | Organisation qui accueille les personnes recrutées | | `GITEA_DEV_TEAM` | `Dev` | Équipe Gitea où elles sont ajoutées à l'acceptation | diff --git a/src/config/env.js b/src/config/env.js index 70f3f08..d91b19f 100644 --- a/src/config/env.js +++ b/src/config/env.js @@ -65,6 +65,9 @@ export const env = Object.freeze({ gitea: { url: read('GITEA_URL').replace(/\/+$/, ''), token: read('GITEA_TOKEN'), + // Admin calls need `write:admin`: recruitment has its own token so the + // everyday one can stay least privileged. + recruitToken: read('GITEA_RECRUITMENT_TOKEN') || read('GITEA_TOKEN'), owner: read('GITEA_OWNER'), repo: read('GITEA_REPO'), org: read('GITEA_ORG') || read('GITEA_OWNER'), diff --git a/src/services/gitea/gitea-client.js b/src/services/gitea/gitea-client.js index 25e640e..a683834 100644 --- a/src/services/gitea/gitea-client.js +++ b/src/services/gitea/gitea-client.js @@ -4,9 +4,12 @@ import { withRetry } from '../../utils/retry.js'; const isTransient = (error) => error.name === 'TimeoutError' || error.status === 429 || error.status >= 500; +/** Administration calls need `write:admin`, which recruitment keeps on its own token. */ +const recruitmentToken = () => env.gitea.recruitToken || env.gitea.token; + /** Minimal Gitea REST API client (M5-T01). */ -export async function giteaRequest(endpoint, { method = 'GET', body } = {}) { - if (!env.gitea.url || !env.gitea.token) { +export async function giteaRequest(endpoint, { method = 'GET', body, token = env.gitea.token } = {}) { + if (!env.gitea.url || !token) { throw new ExternalApiError('gitea', 'Gitea is not configured'); } @@ -15,7 +18,7 @@ export async function giteaRequest(endpoint, { method = 'GET', body } = {}) { const response = await fetch(`${env.gitea.url}/api/v1${endpoint}`, { method, headers: { - Authorization: `token ${env.gitea.token}`, + Authorization: `token ${token}`, Accept: 'application/json', ...(body && { 'Content-Type': 'application/json' }), }, @@ -39,6 +42,11 @@ export function isGiteaConfigured() { return Boolean(env.gitea.url && env.gitea.token); } +/** True when the recruitment token (or its fallback) is available. */ +export function isGiteaRecruitmentConfigured() { + return Boolean(env.gitea.url && recruitmentToken()); +} + /** Gitea returns either a bare array or a `{ data: [...] }` wrapper depending on the version. */ export function asList(payload) { if (Array.isArray(payload)) return payload; @@ -66,10 +74,20 @@ export const gitea = { getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`), getReleaseByTag: (tag) => giteaRequest(`${repoPath()}/releases/tags/${encodeURIComponent(tag)}`), listBranches: (limit = 20) => giteaRequest(`${repoPath()}/branches?limit=${limit}`), - getUser: (username) => giteaRequest(`/users/${encodeURIComponent(username)}`), +}; + +/** + * Administration calls used by recruitment only: creating an account and + * joining a team require `write:admin` / `write:organization`, which the + * everyday token must not carry. + */ +export const giteaRecruitment = { + getUser: (username) => + giteaRequest(`/users/${encodeURIComponent(username)}`, { token: recruitmentToken() }), createUser: ({ username, email, password, mustChangePassword = true }) => giteaRequest('/admin/users', { method: 'POST', + token: recruitmentToken(), body: { username, email, @@ -82,18 +100,29 @@ export const gitea = { }, }), deleteUser: (username) => - giteaRequest(`/admin/users/${encodeURIComponent(username)}?purge=true`, { method: 'DELETE' }), + giteaRequest(`/admin/users/${encodeURIComponent(username)}?purge=true`, { + method: 'DELETE', + token: recruitmentToken(), + }), updateUser: (username, body) => - giteaRequest(`/admin/users/${encodeURIComponent(username)}`, { method: 'PATCH', body }), - listTeams: (org) => giteaRequest(`/orgs/${encodeURIComponent(org)}/teams`), + giteaRequest(`/admin/users/${encodeURIComponent(username)}`, { + method: 'PATCH', + body, + token: recruitmentToken(), + }), + listTeams: (org) => + giteaRequest(`/orgs/${encodeURIComponent(org)}/teams`, { token: recruitmentToken() }), addTeamMember: (teamId, username) => - giteaRequest(`/teams/${teamId}/members/${encodeURIComponent(username)}`, { method: 'PUT' }), + giteaRequest(`/teams/${teamId}/members/${encodeURIComponent(username)}`, { + method: 'PUT', + token: recruitmentToken(), + }), }; /** Returns the Gitea user, or null when the name is still free. */ export async function findGiteaUser(username) { try { - return await gitea.getUser(username); + return await giteaRecruitment.getUser(username); } catch (error) { if (error.status === 404) return null; throw error; diff --git a/src/services/gitea/team-recruitment.js b/src/services/gitea/team-recruitment.js index 3eae769..6777782 100644 --- a/src/services/gitea/team-recruitment.js +++ b/src/services/gitea/team-recruitment.js @@ -30,7 +30,7 @@ import { setRecruitmentPanel, } from '../../database/repositories/gitea-recruitment-repository.js'; import { baseEmbed, bullets, errorEmbed, successEmbed, warningEmbed } from '../../ui/embeds.js'; -import { asList, findGiteaUser, gitea, isGiteaConfigured } from './gitea-client.js'; +import { asList, findGiteaUser, giteaRecruitment, isGiteaRecruitmentConfigured } from './gitea-client.js'; import { replyGiteaFailure } from './gitea-modals.js'; /** @@ -399,9 +399,9 @@ async function submitApplication(interaction) { const emailError = validateEmail(email); if (emailError) throw new UserFacingError(emailError); - if (!isGiteaConfigured()) { + if (!isGiteaRecruitmentConfigured()) { throw new UserFacingError( - 'Le recrutement Gitea n’est pas encore configuré : l’équipe doit renseigner `GITEA_URL` et `GITEA_TOKEN`. Réessaie plus tard.', + 'Le recrutement Gitea n’est pas encore configuré : l’équipe doit renseigner `GITEA_URL` et `GITEA_RECRUITMENT_TOKEN`. Réessaie plus tard.', ); } @@ -476,7 +476,7 @@ async function submitApplication(interaction) { */ export async function lockGiteaAccount(username) { try { - await gitea.updateUser(username, { + await giteaRecruitment.updateUser(username, { restricted: true, max_repo_creation: 0, allow_create_organization: false, @@ -497,11 +497,11 @@ export async function addToDeveloperTeam(username) { const teamName = env.gitea.devTeam; if (!org || !teamName) return { added: false, reason: 'organisation ou équipe non configurée' }; - const teams = asList(await gitea.listTeams(org)); + const teams = asList(await giteaRecruitment.listTeams(org)); const team = teams.find((entry) => String(entry.name).toLowerCase() === teamName.toLowerCase()); if (!team) return { added: false, reason: `équipe « ${teamName} » introuvable dans ${org}` }; - await gitea.addTeamMember(team.id, username); + await giteaRecruitment.addTeamMember(team.id, username); return { added: true, team: team.name }; } @@ -540,9 +540,9 @@ function credentialsEmbed(username, password) { } async function acceptApplication(interaction, application) { - if (!isGiteaConfigured()) { + if (!isGiteaRecruitmentConfigured()) { throw new UserFacingError( - 'Gitea n’est pas configuré (`GITEA_URL` et `GITEA_TOKEN`) : impossible de créer le compte pour l’instant.', + 'Gitea n’est pas configuré (`GITEA_URL` et `GITEA_RECRUITMENT_TOKEN`) : impossible de créer le compte pour l’instant.', ); } @@ -555,7 +555,7 @@ async function acceptApplication(interaction, application) { let created; try { - created = await gitea.createUser({ + created = await giteaRecruitment.createUser({ username: application.gitea_username, email: application.email, password, @@ -564,10 +564,16 @@ async function acceptApplication(interaction, application) { } catch (error) { releaseApplication(application.id); log.error('Gitea refused a team account creation', error); - const reason = - error.status === 422 - ? 'Gitea a refusé : ce nom ou cette adresse e-mail est déjà utilisé. Demande au membre d’en choisir un autre.' - : 'Gitea n’a pas répondu. La candidature reste en attente : réessaie plus tard.'; + let reason = 'Gitea n’a pas répondu. La candidature reste en attente : réessaie plus tard.'; + if (error.status === 422) { + reason = + 'Gitea a refusé : ce nom ou cette adresse e-mail est déjà utilisé. Demande au membre d’en choisir un autre.'; + } + if (error.status === 403) { + reason = + 'Gitea a refusé l’appel : le jeton de recrutement n’a pas les droits d’administration. ' + + 'Il lui faut la portée `write:admin` (`GITEA_RECRUITMENT_TOKEN`).'; + } await interaction.followUp({ embeds: [errorEmbed(reason)], flags: MessageFlags.Ephemeral, diff --git a/src/web/api/configuration.js b/src/web/api/configuration.js index 45139cc..b6dbaa8 100644 --- a/src/web/api/configuration.js +++ b/src/web/api/configuration.js @@ -217,6 +217,45 @@ export function registerConfigurationRoutes(router) { } } + if (params.service === 'gitea-recruitment') { + const url = String(values.GITEA_URL ?? '').replace(/\/+$/, ''); + const token = + String(values.GITEA_RECRUITMENT_TOKEN ?? '').trim() || String(values.GITEA_TOKEN ?? '').trim(); + if (!url || !token) return { ok: false, detail: 'URL ou jeton de recrutement manquant.' }; + + try { + const identity = await fetch(`${url}/api/v1/user`, { + headers: { Authorization: `token ${token}`, Accept: 'application/json' }, + signal: AbortSignal.timeout(10_000), + }); + if (!identity.ok) { + return { ok: false, detail: `Gitea a répondu ${identity.status} au jeton de recrutement.` }; + } + const user = await identity.json(); + // `/admin/users` is the route recruitment really calls: it proves both the + // account's admin rights and the token's `write:admin` scope. + const admin = await fetch(`${url}/api/v1/admin/users?limit=1`, { + headers: { Authorization: `token ${token}`, Accept: 'application/json' }, + signal: AbortSignal.timeout(10_000), + }); + if (!admin.ok) { + return { + ok: false, + detail: + user.is_admin === true + ? `« ${user.login} » est administrateur, mais le jeton n’a pas la portée \`write:admin\` (Gitea a répondu ${admin.status}).` + : `« ${user.login} » n’est pas administrateur de l’instance : seuls les admins peuvent créer des comptes Gitea.`, + }; + } + return { + ok: true, + detail: `Jeton de recrutement valide : « ${user.login} » peut créer des comptes et gérer les équipes.`, + }; + } catch (error) { + return { ok: false, detail: `Gitea injoignable : ${error.message}` }; + } + } + throw notFound('Service inconnu.'); }, WIZARD, diff --git a/src/web/services/env-schema.js b/src/web/services/env-schema.js index acb1712..e30c8c1 100644 --- a/src/web/services/env-schema.js +++ b/src/web/services/env-schema.js @@ -73,6 +73,7 @@ export const SECTIONS = Object.freeze([ 'Connecte-toi à ton instance Gitea avec le compte technique de l’organisation.', 'Va dans **Paramètres → Applications → Générer un nouveau jeton**.', 'Coche au minimum `read:organization`, `read:repository`, `write:issue` — ajoute `write:repository` pour créer des releases depuis le site.', + 'Pour le recrutement, génère un second jeton depuis un compte **administrateur**, avec `write:admin`, `write:organization`, `read:user` : c’est `GITEA_RECRUITMENT_TOKEN`.', 'Copie le jeton immédiatement : Gitea ne le réaffiche jamais.', ], }, @@ -332,10 +333,18 @@ export const VARIABLES = Object.freeze([ key: 'GITEA_TOKEN', section: 'gitea', label: 'Jeton d’accès', - help: 'Jeton personnel de l’organisation. Portée minimale : lecture des dépôts et écriture des issues.', + help: 'Jeton personnel de l’organisation. Portée minimale : lecture des dépôts et écriture des issues. Sert aussi de repli au recrutement quand `GITEA_RECRUITMENT_TOKEN` est vide.', type: 'secret', testable: 'gitea', }, + { + key: 'GITEA_RECRUITMENT_TOKEN', + section: 'gitea', + label: 'Jeton de recrutement', + help: 'Jeton d’un compte administrateur de l’instance, réservé à la création des comptes recrutés et à leur ajout dans l’équipe. Portées nécessaires : `write:admin`, `write:organization`, `read:user`. Vide : `GITEA_TOKEN` est utilisé.', + type: 'secret', + testable: 'gitea-recruitment', + }, { key: 'GITEA_OWNER', section: 'gitea', @@ -761,7 +770,7 @@ export function crossCheck(values) { warnings.push('Les webhooks sont activés sans secret : tous les événements Gitea seront rejetés.'); } - if (read('GITEA_TOKEN') && !read('GITEA_URL')) { + if ((read('GITEA_TOKEN') || read('GITEA_RECRUITMENT_TOKEN')) && !read('GITEA_URL')) { warnings.push('Un jeton Gitea est renseigné sans `GITEA_URL` : les appels API resteront désactivés.'); } diff --git a/tests/web-configuration.test.js b/tests/web-configuration.test.js index a4953e2..2e35c52 100644 --- a/tests/web-configuration.test.js +++ b/tests/web-configuration.test.js @@ -37,6 +37,22 @@ describe('env schema', () => { } }); + it('keeps the recruitment token separate and admin-scoped', () => { + const token = BY_KEY.GITEA_RECRUITMENT_TOKEN; + + assert.equal(token.type, 'secret'); + assert.equal(token.testable, 'gitea-recruitment'); + assert.match(token.help, /write:admin/); + assert.match(token.help, /write:organization/); + assert.match(token.help, /read:user/); + }); + + it('warns when a Gitea token has no URL to talk to', () => { + const warnings = crossCheck({ GITEA_RECRUITMENT_TOKEN: 'jeton-admin' }); + + assert.ok(warnings.some((warning) => warning.includes('GITEA_URL'))); + }); + it('covers the variables the bot refuses to start without', () => { assert.deepEqual(requiredKeys().sort(), ['DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID', 'DISCORD_TOKEN']); });