While someone has a workspace open, the gateway asks the API for a 15-minute write token for the project's platform repository on behalf of that person (membership and role checked each time) and delivers it to the workspace backend. The backend writes it to a Git config file outside the repository (a memory volume in Kubernetes) that the clone includes, and on the first delivery clones the target branch into a folder named after the project. The workspace cannot mint credentials itself, so access ends with the last session. - People commit and push to the target branch like with any Git server; the platform only accepts fast-forwards, and the next wish starts from that commit (covered end to end in the local loop test). - Commits are authored by whoever opened the latest session, from the name and email in their sign-in; their own git config overrides it. - Only the gateway can reach the delivery endpoint: it needs Theia's connection token, and the gateway refuses the path for browsers. - The provisioner pins the workspace to its repository and lets the pod reach the Git service; the Kubernetes baseline admits that traffic. External repositories are not cloned. - The local shared Theia clones each project into its own folder. - The Theia image installs Git, and its stage is named theia: the default build target of that Dockerfile is the gateway. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
130 lines
5.5 KiB
JavaScript
130 lines
5.5 KiB
JavaScript
// While someone has a workspace open, the gateway keeps its Git credential fresh: the control
|
|
// plane mints a short-lived repository token for the session's user, and the gateway hands it
|
|
// to the workspace backend, which clones the project on the first delivery. Nothing in the
|
|
// workspace can mint a credential itself, so access ends with the last session.
|
|
const CONNECTION_COOKIE = 'theia-connection-token';
|
|
export const CREDENTIAL_PATH = '/wishforge-internal/git-credential';
|
|
const REFRESH_BEFORE_MS = 5 * 60_000;
|
|
const RETRY_MS = 30_000;
|
|
// A project without a platform repository, or a workspace without the endpoint, keeps
|
|
// answering the same way; ask again rarely.
|
|
const UNSUPPORTED_RETRY_MS = 30 * 60_000;
|
|
|
|
export function createGitCredentials(config) {
|
|
const fetchImpl = config.fetchImpl ?? fetch;
|
|
const now = config.now ?? Date.now;
|
|
const state = new Map();
|
|
const authors = new Map();
|
|
|
|
function connectionToken(response) {
|
|
for (const cookie of response.headers.getSetCookie?.() ?? []) {
|
|
const token = new RegExp(`^${CONNECTION_COOKIE}=([^;\\s]{1,512})(?:;|$)`).exec(cookie)?.[1];
|
|
if (token) return token;
|
|
}
|
|
return undefined;
|
|
}
|
|
/** Theia accepts the delivery only with its connection token, which the gateway alone holds. */
|
|
async function bootstrapToken(upstream) {
|
|
const response = await fetchImpl(upstream.href, { redirect: 'manual', signal: AbortSignal.timeout(5000) });
|
|
await response.body?.cancel();
|
|
const token = connectionToken(response);
|
|
if (token) config.setConnectionToken(upstream.href, token);
|
|
return token;
|
|
}
|
|
async function credentialFor(workspaceId, userId) {
|
|
const response = await fetchImpl(
|
|
`${config.apiOrigin}/internal/workspaces/${encodeURIComponent(workspaceId)}/git-credential`,
|
|
{
|
|
method: 'POST',
|
|
headers: {
|
|
authorization: `Bearer ${config.serviceToken}`,
|
|
'content-type': 'application/json',
|
|
'X-WishForge-Tenant': config.tenantId,
|
|
},
|
|
body: JSON.stringify({ userId }),
|
|
signal: AbortSignal.timeout(5000),
|
|
redirect: 'error',
|
|
},
|
|
);
|
|
if (response.status === 409) return { unsupported: true };
|
|
if (!response.ok) throw new Error('GIT_CREDENTIAL_UNAVAILABLE');
|
|
const payload = await response.json();
|
|
return payload.data ?? payload;
|
|
}
|
|
async function deliver(upstream, body) {
|
|
const target = new URL(upstream);
|
|
target.pathname = `${target.pathname.replace(/\/$/, '')}${CREDENTIAL_PATH}`;
|
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
const token = (attempt === 0 && config.connectionToken(upstream.href)) || (await bootstrapToken(upstream));
|
|
if (!token) throw new Error('WORKSPACE_CONNECTION_TOKEN_UNAVAILABLE');
|
|
const response = await fetchImpl(target, {
|
|
method: 'POST',
|
|
headers: { 'content-type': 'application/json', cookie: `${CONNECTION_COOKIE}=${token}` },
|
|
body: JSON.stringify(body),
|
|
signal: AbortSignal.timeout(10000),
|
|
redirect: 'error',
|
|
});
|
|
await response.body?.cancel();
|
|
// A restarted Theia has a new connection token; fetch it once and try again.
|
|
if (response.status === 403 && attempt === 0) continue;
|
|
// A workspace provisioned without the project's repository has no endpoint to deliver to.
|
|
if (response.status === 404) return { unsupported: true };
|
|
if (!response.ok) throw new Error('WORKSPACE_GIT_DELIVERY_FAILED');
|
|
return {};
|
|
}
|
|
}
|
|
async function refresh(workspaceId, upstream, userId) {
|
|
const current = state.get(workspaceId);
|
|
try {
|
|
const credential = await credentialFor(workspaceId, userId);
|
|
if (credential.unsupported) {
|
|
current.nextAt = now() + UNSUPPORTED_RETRY_MS;
|
|
return;
|
|
}
|
|
const author = authors.get(workspaceId);
|
|
const delivered = await deliver(upstream, {
|
|
projectId: credential.projectId,
|
|
projectName: credential.projectName,
|
|
repositoryUrl: credential.repositoryUrl,
|
|
branch: credential.branch,
|
|
token: credential.token,
|
|
expiresAt: credential.expiresAt,
|
|
...(author ? { author } : {}),
|
|
});
|
|
current.nextAt = delivered.unsupported
|
|
? now() + UNSUPPORTED_RETRY_MS
|
|
: Math.max(now() + 60_000, Date.parse(credential.expiresAt) - REFRESH_BEFORE_MS);
|
|
} catch {
|
|
current.nextAt = now() + RETRY_MS;
|
|
}
|
|
}
|
|
return {
|
|
/** A new session also makes its user the author of the workspace's next commits. */
|
|
opened(session, upstream) {
|
|
if (session.author) authors.set(session.workspaceId, session.author);
|
|
const current = state.get(session.workspaceId);
|
|
if (current) {
|
|
current.nextAt = 0;
|
|
// A delivery already under way may carry the previous author; send another after it.
|
|
if (current.inFlight) current.again = true;
|
|
}
|
|
return this.due(session, upstream);
|
|
},
|
|
/** Called whenever a session is used; refreshes at most one delivery per workspace at a time. */
|
|
due(session, upstream) {
|
|
if (!session.userId) return undefined;
|
|
const current = state.get(session.workspaceId) ?? { nextAt: 0 };
|
|
state.set(session.workspaceId, current);
|
|
if (current.inFlight || now() < current.nextAt) return current.inFlight;
|
|
current.inFlight = refresh(session.workspaceId, upstream, session.userId).finally(() => {
|
|
current.inFlight = undefined;
|
|
if (current.again) {
|
|
current.again = false;
|
|
current.nextAt = 0;
|
|
}
|
|
});
|
|
return current.inFlight;
|
|
},
|
|
};
|
|
}
|