feat(gitea): use a dedicated admin token for recruitment
CI / quality (push) Failing after 45s

Recruitment needs `write:admin` and `write:organization`, which the everyday
token must not carry. A second token keeps the repository and issue scopes
least privileged, falls back to `GITEA_TOKEN` so existing installs keep
working, and a 403 now names the missing scope instead of pretending Gitea
did not answer.
This commit is contained in:
BlackAngelTV committed 2026-12-06 18:01:43 +01:00
1 parent 9b45c9bf89
commit adc96e4d75
9 files changed
+132 -25

No files matched your search

+3
View File
@@ -59,6 +59,9 @@ BOT_STATUS_INTERVAL_SECONDS=60
GITEA_URL=https://gitea.nocode-var.tech GITEA_URL=https://gitea.nocode-var.tech
# Token with least privilege (read:repository, write:issue). Never log it. # Token with least privilege (read:repository, write:issue). Never log it.
GITEA_TOKEN= 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_OWNER=FWS
GITEA_REPO=FWS-Arch GITEA_REPO=FWS-Arch
# Organisation qui accueille les personnes recrutées (défaut : GITEA_OWNER) # Organisation qui accueille les personnes recrutées (défaut : GITEA_OWNER)
+2 -1
View File
@@ -143,9 +143,10 @@ Full template: [`.env.example`](.env.example). Default values in brackets.
### Gitea ### Gitea
| Variable | Default | Description | | Variable | Default | Description |
| ------------------- | ------------- | ---------------------------------------------------------------------- | | ------------------------- | ------------- | ---------------------------------------------------------------------------------- |
| `GITEA_URL` | — | Instance URL (without a trailing `/`) | | `GITEA_URL` | — | Instance URL (without a trailing `/`) |
| `GITEA_TOKEN` | — | Least privilege token (`read:repository`, `write:issue`). Never logged | | `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_OWNER` | — | Repository owner (e.g. `FWS`) |
| `GITEA_ORG` | `GITEA_OWNER` | Organization that hosts recruited people | | `GITEA_ORG` | `GITEA_OWNER` | Organization that hosts recruited people |
| `GITEA_DEV_TEAM` | `Dev` | Gitea team they join on acceptance | | `GITEA_DEV_TEAM` | `Dev` | Gitea team they join on acceptance |
+1
View File
@@ -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_URL` | — | URL de l'instance (sans `/` final) |
| `GITEA_TOKEN` | — | Token à moindre privilège (`read:repository`, `write:issue`). Jamais loggé | | `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_OWNER` | — | Propriétaire du dépôt (ex. `FWS`) |
| `GITEA_ORG` | `GITEA_OWNER` | Organisation qui accueille les personnes recrutées | | `GITEA_ORG` | `GITEA_OWNER` | Organisation qui accueille les personnes recrutées |
| `GITEA_DEV_TEAM` | `Dev` | Équipe Gitea où elles sont ajoutées à l'acceptation | | `GITEA_DEV_TEAM` | `Dev` | Équipe Gitea où elles sont ajoutées à l'acceptation |
+3
View File
@@ -65,6 +65,9 @@ export const env = Object.freeze({
gitea: { gitea: {
url: read('GITEA_URL').replace(/\/+$/, ''), url: read('GITEA_URL').replace(/\/+$/, ''),
token: read('GITEA_TOKEN'), 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'), owner: read('GITEA_OWNER'),
repo: read('GITEA_REPO'), repo: read('GITEA_REPO'),
org: read('GITEA_ORG') || read('GITEA_OWNER'), org: read('GITEA_ORG') || read('GITEA_OWNER'),
+38 -9
View File
@@ -4,9 +4,12 @@ import { withRetry } from '../../utils/retry.js';
const isTransient = (error) => error.name === 'TimeoutError' || error.status === 429 || error.status >= 500; 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). */ /** Minimal Gitea REST API client (M5-T01). */
export async function giteaRequest(endpoint, { method = 'GET', body } = {}) { export async function giteaRequest(endpoint, { method = 'GET', body, token = env.gitea.token } = {}) {
if (!env.gitea.url || !env.gitea.token) { if (!env.gitea.url || !token) {
throw new ExternalApiError('gitea', 'Gitea is not configured'); 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}`, { const response = await fetch(`${env.gitea.url}/api/v1${endpoint}`, {
method, method,
headers: { headers: {
Authorization: `token ${env.gitea.token}`, Authorization: `token ${token}`,
Accept: 'application/json', Accept: 'application/json',
...(body && { 'Content-Type': 'application/json' }), ...(body && { 'Content-Type': 'application/json' }),
}, },
@@ -39,6 +42,11 @@ export function isGiteaConfigured() {
return Boolean(env.gitea.url && env.gitea.token); 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. */ /** Gitea returns either a bare array or a `{ data: [...] }` wrapper depending on the version. */
export function asList(payload) { export function asList(payload) {
if (Array.isArray(payload)) return payload; if (Array.isArray(payload)) return payload;
@@ -66,10 +74,20 @@ export const gitea = {
getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`), getLatestRelease: () => giteaRequest(`${repoPath()}/releases/latest`),
getReleaseByTag: (tag) => giteaRequest(`${repoPath()}/releases/tags/${encodeURIComponent(tag)}`), getReleaseByTag: (tag) => giteaRequest(`${repoPath()}/releases/tags/${encodeURIComponent(tag)}`),
listBranches: (limit = 20) => giteaRequest(`${repoPath()}/branches?limit=${limit}`), 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 }) => createUser: ({ username, email, password, mustChangePassword = true }) =>
giteaRequest('/admin/users', { giteaRequest('/admin/users', {
method: 'POST', method: 'POST',
token: recruitmentToken(),
body: { body: {
username, username,
email, email,
@@ -82,18 +100,29 @@ export const gitea = {
}, },
}), }),
deleteUser: (username) => 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) => updateUser: (username, body) =>
giteaRequest(`/admin/users/${encodeURIComponent(username)}`, { method: 'PATCH', body }), giteaRequest(`/admin/users/${encodeURIComponent(username)}`, {
listTeams: (org) => giteaRequest(`/orgs/${encodeURIComponent(org)}/teams`), method: 'PATCH',
body,
token: recruitmentToken(),
}),
listTeams: (org) =>
giteaRequest(`/orgs/${encodeURIComponent(org)}/teams`, { token: recruitmentToken() }),
addTeamMember: (teamId, username) => 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. */ /** Returns the Gitea user, or null when the name is still free. */
export async function findGiteaUser(username) { export async function findGiteaUser(username) {
try { try {
return await gitea.getUser(username); return await giteaRecruitment.getUser(username);
} catch (error) { } catch (error) {
if (error.status === 404) return null; if (error.status === 404) return null;
throw error; throw error;
+19 -13
View File
@@ -30,7 +30,7 @@ import {
setRecruitmentPanel, setRecruitmentPanel,
} from '../../database/repositories/gitea-recruitment-repository.js'; } from '../../database/repositories/gitea-recruitment-repository.js';
import { baseEmbed, bullets, errorEmbed, successEmbed, warningEmbed } from '../../ui/embeds.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'; import { replyGiteaFailure } from './gitea-modals.js';
/** /**
@@ -399,9 +399,9 @@ async function submitApplication(interaction) {
const emailError = validateEmail(email); const emailError = validateEmail(email);
if (emailError) throw new UserFacingError(emailError); if (emailError) throw new UserFacingError(emailError);
if (!isGiteaConfigured()) { if (!isGiteaRecruitmentConfigured()) {
throw new UserFacingError( 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) { export async function lockGiteaAccount(username) {
try { try {
await gitea.updateUser(username, { await giteaRecruitment.updateUser(username, {
restricted: true, restricted: true,
max_repo_creation: 0, max_repo_creation: 0,
allow_create_organization: false, allow_create_organization: false,
@@ -497,11 +497,11 @@ export async function addToDeveloperTeam(username) {
const teamName = env.gitea.devTeam; const teamName = env.gitea.devTeam;
if (!org || !teamName) return { added: false, reason: 'organisation ou équipe non configurée' }; 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()); const team = teams.find((entry) => String(entry.name).toLowerCase() === teamName.toLowerCase());
if (!team) return { added: false, reason: `équipe « ${teamName} » introuvable dans ${org}` }; 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 }; return { added: true, team: team.name };
} }
@@ -540,9 +540,9 @@ function credentialsEmbed(username, password) {
} }
async function acceptApplication(interaction, application) { async function acceptApplication(interaction, application) {
if (!isGiteaConfigured()) { if (!isGiteaRecruitmentConfigured()) {
throw new UserFacingError( 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; let created;
try { try {
created = await gitea.createUser({ created = await giteaRecruitment.createUser({
username: application.gitea_username, username: application.gitea_username,
email: application.email, email: application.email,
password, password,
@@ -564,10 +564,16 @@ async function acceptApplication(interaction, application) {
} catch (error) { } catch (error) {
releaseApplication(application.id); releaseApplication(application.id);
log.error('Gitea refused a team account creation', error); log.error('Gitea refused a team account creation', error);
const reason = let reason = 'Gitea n’a pas répondu. La candidature reste en attente : réessaie plus tard.';
error.status === 422 if (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.' reason =
: 'Gitea n’a pas répondu. La candidature reste en attente : réessaie plus tard.'; '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({ await interaction.followUp({
embeds: [errorEmbed(reason)], embeds: [errorEmbed(reason)],
flags: MessageFlags.Ephemeral, flags: MessageFlags.Ephemeral,
+39
View File
@@ -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.'); throw notFound('Service inconnu.');
}, },
WIZARD, WIZARD,
+11 -2
View File
@@ -73,6 +73,7 @@ export const SECTIONS = Object.freeze([
'Connecte-toi à ton instance Gitea avec le compte technique de l’organisation.', 'Connecte-toi à ton instance Gitea avec le compte technique de l’organisation.',
'Va dans **Paramètres → Applications → Générer un nouveau jeton**.', '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.', '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.', 'Copie le jeton immédiatement : Gitea ne le réaffiche jamais.',
], ],
}, },
@@ -332,10 +333,18 @@ export const VARIABLES = Object.freeze([
key: 'GITEA_TOKEN', key: 'GITEA_TOKEN',
section: 'gitea', section: 'gitea',
label: 'Jeton d’accès', 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', type: 'secret',
testable: 'gitea', 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', key: 'GITEA_OWNER',
section: 'gitea', 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.'); 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.'); warnings.push('Un jeton Gitea est renseigné sans `GITEA_URL` : les appels API resteront désactivés.');
} }
+16
View File
@@ -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', () => { it('covers the variables the bot refuses to start without', () => {
assert.deepEqual(requiredKeys().sort(), ['DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID', 'DISCORD_TOKEN']); assert.deepEqual(requiredKeys().sort(), ['DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID', 'DISCORD_TOKEN']);
}); });