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:
9 files changed
+141
-34
No files matched your search
@@ -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'),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.');
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user