fix(mosaic): serialize credential lifecycle mutations
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { timingSafeEqual } from 'node:crypto';
|
||||
import { fstatSync, writeSync } from 'node:fs';
|
||||
import { fstatSync, lstatSync, writeSync } from 'node:fs';
|
||||
import { open, rename } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
CredentialJournalError,
|
||||
listCredentialJournals,
|
||||
} from '../credentials/audit-journal.js';
|
||||
import { readRegularFileSecure } from '../fleet/secure-file.js';
|
||||
import { ensureManagedDirectory, readRegularFileSecure } from '../fleet/secure-file.js';
|
||||
import {
|
||||
runCredentialReadValidation,
|
||||
runCredentialValidation,
|
||||
@@ -542,10 +542,15 @@ export async function executeCredentialRotate(
|
||||
context.provider,
|
||||
context.store,
|
||||
context.teaStore,
|
||||
{ stateRoot: context.stateRoot, actor: options.actor, allowReplace: true },
|
||||
{
|
||||
stateRoot: context.stateRoot,
|
||||
actor: options.actor,
|
||||
allowReplace: true,
|
||||
journal,
|
||||
deferSuccessSeal: true,
|
||||
},
|
||||
);
|
||||
if (provisioned.outcome !== 'ok') {
|
||||
await journal.seal(provisioned.outcome, provisioned.reason.code);
|
||||
old.secret.fill(0);
|
||||
return {
|
||||
...provisioned,
|
||||
@@ -616,7 +621,25 @@ export async function executeCredentialWire(
|
||||
});
|
||||
}
|
||||
const locations = lifecycleLocations(options);
|
||||
const seatEnvironmentRoot = join(defaultMosaicHome(options), 'fleet', 'agents');
|
||||
if (dirname(options.seatEnv) !== seatEnvironmentRoot) {
|
||||
return localLifecycleResult('wire', identity, options, {
|
||||
outcome: 'refused',
|
||||
code: 'insecure-credential-destination',
|
||||
message: 'Seat environment must be directly beneath the governed fleet agent directory.',
|
||||
});
|
||||
}
|
||||
try {
|
||||
ensureManagedDirectory(seatEnvironmentRoot, seatEnvironmentRoot);
|
||||
const parent = lstatSync(seatEnvironmentRoot);
|
||||
if (
|
||||
!parent.isDirectory() ||
|
||||
parent.isSymbolicLink() ||
|
||||
parent.uid !== process.getuid?.() ||
|
||||
(parent.mode & 0o022) !== 0
|
||||
) {
|
||||
throw new Error('seat environment directory is unsafe');
|
||||
}
|
||||
const context = await lifecycleContext(options);
|
||||
if (context.registry.resolve(options.estate, options.host) === undefined) {
|
||||
return localLifecycleResult('wire', identity, options, {
|
||||
@@ -668,6 +691,7 @@ export async function executeCredentialWire(
|
||||
`MOSAIC_CREDENTIAL_ESTATE=${options.estate}`,
|
||||
`GITEA_LOGIN=${identity}--${options.host}`,
|
||||
);
|
||||
const parentBefore = lstatSync(seatEnvironmentRoot);
|
||||
const temp = `${options.seatEnv}.${process.pid.toString()}.tmp`;
|
||||
const handle = await open(temp, 'wx', 0o600);
|
||||
try {
|
||||
@@ -676,6 +700,15 @@ export async function executeCredentialWire(
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
const parentAfter = lstatSync(seatEnvironmentRoot);
|
||||
if (
|
||||
parentAfter.dev !== parentBefore.dev ||
|
||||
parentAfter.ino !== parentBefore.ino ||
|
||||
parentAfter.uid !== process.getuid?.() ||
|
||||
(parentAfter.mode & 0o022) !== 0
|
||||
) {
|
||||
throw new Error('seat environment directory changed during mutation');
|
||||
}
|
||||
await rename(temp, options.seatEnv);
|
||||
await journal.recordMutation('wire-applied');
|
||||
await journal.seal('ok', 'wire-verified');
|
||||
@@ -813,6 +846,15 @@ async function executeAuthorizedInventoryRead(
|
||||
});
|
||||
}
|
||||
const context = await lifecycleContext(options);
|
||||
if (context.registry.inventoryAuthority(options.estate) !== options.actor) {
|
||||
await journal.seal('refused', 'permission-denied');
|
||||
return localLifecycleResult(operation, 'all', options, {
|
||||
outcome: 'refused',
|
||||
code: 'permission-denied',
|
||||
message: 'Explicit actor is not the configured estate inventory authority.',
|
||||
audit: { journalId: journal.journalId(), state: 'sealed' },
|
||||
});
|
||||
}
|
||||
const authority = await lifecycleAuthority(options.actor, options);
|
||||
const providerIdentity = await context.provider.readIdentity(authority);
|
||||
if (providerIdentity.login !== options.actor) {
|
||||
|
||||
@@ -10,5 +10,6 @@ export interface CredentialHostConfigDto {
|
||||
export interface CredentialEstateConfigDto {
|
||||
readonly name: string;
|
||||
readonly readOnlyControlIdentity?: string;
|
||||
readonly inventoryAuthorityIdentity?: string;
|
||||
readonly hosts: readonly CredentialHostConfigDto[];
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ const estateSchema = z
|
||||
.object({
|
||||
name: z.string().regex(NAME),
|
||||
readOnlyControlIdentity: z.string().regex(IDENTITY).optional(),
|
||||
inventoryAuthorityIdentity: z.string().regex(IDENTITY).optional(),
|
||||
hosts: z.array(hostSchema).min(1),
|
||||
})
|
||||
.strict();
|
||||
@@ -105,6 +106,17 @@ export class ParsedCredentialEstateRegistry implements CredentialEstateRegistry
|
||||
return undefined;
|
||||
}
|
||||
|
||||
inventoryAuthority(estate: string): string {
|
||||
const identity = this.estates.get(estate)?.inventoryAuthorityIdentity;
|
||||
if (identity === undefined) {
|
||||
throw new CredentialEstateRegistryError(
|
||||
'inventory-authority-missing',
|
||||
`estate ${estate} has no delegated inventory authority identity`,
|
||||
);
|
||||
}
|
||||
return identity;
|
||||
}
|
||||
|
||||
readOnlyControl(estate: string): string {
|
||||
const identity = this.estates.get(estate)?.readOnlyControlIdentity;
|
||||
if (identity === undefined) {
|
||||
|
||||
@@ -180,10 +180,17 @@ export class FileCredentialResolver implements CredentialResolver {
|
||||
});
|
||||
const binding = bindingSchema.safeParse(JSON.parse(bindingSnapshot.content.toString('utf8')));
|
||||
const digest = createHash('sha256').update(snapshot.content).digest('hex');
|
||||
if (!binding.success || binding.data.tokenDigest !== digest) {
|
||||
if (
|
||||
!binding.success ||
|
||||
binding.data.tokenDigest !== digest ||
|
||||
binding.data.identity !== identity ||
|
||||
binding.data.estate !== estate ||
|
||||
binding.data.host !== host ||
|
||||
binding.data.providerLogin !== identity
|
||||
) {
|
||||
throw new CredentialStoreError(
|
||||
'credential-generation-mismatch',
|
||||
'token and binding metadata are not one committed generation',
|
||||
'token and binding metadata are not one committed identity-bound generation',
|
||||
);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
@@ -410,17 +417,47 @@ export class FileCredentialStore {
|
||||
.sort();
|
||||
}
|
||||
|
||||
async remove(identity: string, estate: string, host: string): Promise<void> {
|
||||
async remove(
|
||||
identity: string,
|
||||
estate: string,
|
||||
host: string,
|
||||
expectedTokenDigest?: string,
|
||||
): Promise<void> {
|
||||
const paths = this.paths(identity, estate, host);
|
||||
await unlink(paths.token).catch((error: unknown): void => {
|
||||
if (!isMissingFile(error)) throw error;
|
||||
});
|
||||
await unlink(paths.binding).catch((error: unknown): void => {
|
||||
if (!isMissingFile(error)) throw error;
|
||||
});
|
||||
await unlink(paths.envelope).catch((error: unknown): void => {
|
||||
if (!isMissingFile(error)) throw error;
|
||||
});
|
||||
await syncDirectory(this.tokenDirectory);
|
||||
const lockPath = join(this.tokenDirectory, `${paths.prefix}.lock`);
|
||||
let lock;
|
||||
try {
|
||||
lock = await open(lockPath, 'wx', 0o600);
|
||||
} catch {
|
||||
throw new CredentialStoreError(
|
||||
'conflicting-credential-mutation',
|
||||
'another mutation owns the identity lock',
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (expectedTokenDigest !== undefined) {
|
||||
const current = await this.readBinding(identity, estate, host);
|
||||
if (current === undefined || current.tokenDigest !== expectedTokenDigest) {
|
||||
throw new CredentialStoreError(
|
||||
'credential-generation-mismatch',
|
||||
'credential generation changed before removal',
|
||||
);
|
||||
}
|
||||
}
|
||||
await unlink(paths.token).catch((error: unknown): void => {
|
||||
if (!isMissingFile(error)) throw error;
|
||||
});
|
||||
await unlink(paths.binding).catch((error: unknown): void => {
|
||||
if (!isMissingFile(error)) throw error;
|
||||
});
|
||||
await unlink(paths.envelope).catch((error: unknown): void => {
|
||||
if (!isMissingFile(error)) throw error;
|
||||
});
|
||||
await syncDirectory(this.tokenDirectory);
|
||||
} finally {
|
||||
await lock.close();
|
||||
await unlink(lockPath).catch((): void => undefined);
|
||||
await syncDirectory(this.tokenDirectory);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,8 @@ export interface LifecycleOptions {
|
||||
readonly actor: string;
|
||||
readonly now?: () => string;
|
||||
readonly allowReplace?: boolean;
|
||||
readonly journal?: CredentialAuditJournal;
|
||||
readonly deferSuccessSeal?: boolean;
|
||||
}
|
||||
|
||||
function lifecycleResult(
|
||||
@@ -113,7 +115,7 @@ export async function provisionCredential(
|
||||
teaStore: TeaLoginStore,
|
||||
options: LifecycleOptions,
|
||||
): Promise<CredentialLifecycleResultDto> {
|
||||
const journal = await openLifecycleJournal('provision', request, options);
|
||||
const journal = options.journal ?? (await openLifecycleJournal('provision', request, options));
|
||||
let mutation: 'none' | 'unknown' | 'applied' = 'none';
|
||||
let minted: MintedToken | undefined;
|
||||
let failureCode = 'mutation-state-unknown';
|
||||
@@ -192,14 +194,19 @@ export async function provisionCredential(
|
||||
contentType: readBack.contentType,
|
||||
decision: 'scope-verified',
|
||||
});
|
||||
await journal.seal('ok', 'provision-verified');
|
||||
if (options.deferSuccessSeal !== true) {
|
||||
await journal.seal('ok', 'provision-verified');
|
||||
}
|
||||
return lifecycleResult('provision', request, {
|
||||
outcome: 'ok',
|
||||
mutation: 'applied',
|
||||
code: 'provision-verified',
|
||||
message: 'Provider principal and exact token scopes were read back and stored.',
|
||||
code: options.deferSuccessSeal === true ? 'replacement-staged' : 'provision-verified',
|
||||
message:
|
||||
options.deferSuccessSeal === true
|
||||
? 'Replacement was read back and staged under the open rotation transaction.'
|
||||
: 'Provider principal and exact token scopes were read back and stored.',
|
||||
journalId: journal.journalId(),
|
||||
auditState: 'sealed',
|
||||
auditState: options.deferSuccessSeal === true ? 'open' : 'sealed',
|
||||
providerIdentity: identity.login,
|
||||
token: readBack,
|
||||
teaLogin: { ...teaLogin, state: 'registered' },
|
||||
@@ -305,7 +312,7 @@ export async function revokeCredential(
|
||||
throw new Error('Tea login still exists after revocation');
|
||||
}
|
||||
await journal.recordMutation('tea-login-removed');
|
||||
await store.remove(request.identity, request.estate, request.host);
|
||||
await store.remove(request.identity, request.estate, request.host, binding.tokenDigest);
|
||||
await journal.seal('ok', 'revoke-verified');
|
||||
return lifecycleResult('revoke', request, {
|
||||
outcome: 'ok',
|
||||
|
||||
Reference in New Issue
Block a user