Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(pki): let reviewers stop enforcing scope parameters on a pending signing request

Carlos Monastyrskida1b51763718
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index d5b453f046..f6ad01fd16 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -813,6 +813,7 @@ export enum EventType {
PKI_SIGNER_REQUEST_TO_SIGN = "pki-signer-request-to-sign",
PKI_SIGNER_PRE_APPROVE_SIGNING = "pki-signer-pre-approve-signing",
PKI_SIGNER_REVOKE_REQUEST = "pki-signer-revoke-request",
+ PKI_SIGNER_REMOVE_REQUEST_SCOPE_FIELDS = "pki-signer-remove-request-scope-fields",
ADD_PKI_SIGNER_MEMBER = "add-pki-signer-member",
UPDATE_PKI_SIGNER_MEMBER = "update-pki-signer-member",
REMOVE_PKI_SIGNER_MEMBER = "remove-pki-signer-member",
@@ -4812,6 +4813,15 @@ interface PkiSignerRevokeRequestEvent {
};
}
+interface PkiSignerRemoveRequestScopeFieldsEvent {
+ type: EventType.PKI_SIGNER_REMOVE_REQUEST_SCOPE_FIELDS;
+ metadata: {
+ signerId: string;
+ requestId: string;
+ removedFields: string[];
+ };
+}
+
interface AddPkiSignerMemberEvent {
type: EventType.ADD_PKI_SIGNER_MEMBER;
metadata: {
@@ -7399,6 +7409,7 @@ export type Event =
| PkiSignerRequestToSignEvent
| PkiSignerPreApproveSigningEvent
| PkiSignerRevokeRequestEvent
+ | PkiSignerRemoveRequestScopeFieldsEvent
| AddPkiSignerMemberEvent
| UpdatePkiSignerMemberEvent
| RemovePkiSignerMemberEvent
diff --git a/backend/src/server/routes/v1/signer-routers/requests-router.ts b/backend/src/server/routes/v1/signer-routers/requests-router.ts
index 4b247aabcf..35db704166 100644
--- a/backend/src/server/routes/v1/signer-routers/requests-router.ts
+++ b/backend/src/server/routes/v1/signer-routers/requests-router.ts
@@ -4,13 +4,17 @@ import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags } from "@app/lib/api-docs";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { CodeSigningScopeField } from "@app/services/approval-policy/code-signing/code-signing-policy-enums";
import {
CODE_SIGNING_SCOPE_API_DESCRIPTION,
- CodeSigningScopeInputSchema
+ CodeSigningRequestSchema,
+ CodeSigningScopeInputSchema,
+ RemoveCodeSigningScopeFieldsSchema,
+ SigningWindowDurationSchema
} from "@app/services/approval-policy/code-signing/code-signing-policy-schemas";
import { AuthMode } from "@app/services/auth/auth-type";
-import { SignerIdParamsSchema } from "./schemas";
+import { SignerIdParamsSchema, SignerRequestParamsSchema } from "./schemas";
export const registerSignerRequestsRouter = async (server: FastifyZodProvider) => {
server.route({
@@ -69,8 +73,9 @@ export const registerSignerRequestsRouter = async (server: FastifyZodProvider) =
body: z.object({
justification: z.string().trim().min(1).max(2048),
requestedSignings: z.number().int().min(1).optional(),
- requestedWindowStart: z.string().datetime().optional(),
- requestedWindowEnd: z.string().datetime().optional(),
+ requestedWindowDuration: SigningWindowDurationSchema.optional().describe(
+ "How long the approval stays usable once it is granted, for example '4h'. The window starts when the request is approved."
+ ),
scope: CodeSigningScopeInputSchema.optional().describe(CODE_SIGNING_SCOPE_API_DESCRIPTION)
})
},
@@ -113,8 +118,9 @@ export const registerSignerRequestsRouter = async (server: FastifyZodProvider) =
granteeIdentityId: z.string().uuid().optional(),
justification: z.string().trim().min(1).max(2048),
requestedSignings: z.number().int().min(1).optional(),
- requestedWindowStart: z.string().datetime().optional(),
- requestedWindowEnd: z.string().datetime().optional(),
+ requestedWindowDuration: SigningWindowDurationSchema.optional().describe(
+ "How long the approval stays usable once it is granted, for example '4h'. The window starts when the request is approved."
+ ),
scope: CodeSigningScopeInputSchema.optional().describe(CODE_SIGNING_SCOPE_API_DESCRIPTION)
})
},
@@ -147,6 +153,54 @@ export const registerSignerRequestsRouter = async (server: FastifyZodProvider) =
}
});
+ server.route({
+ method: "PATCH",
+ url: "/:signerId/requests/:requestId/scope",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "removeSignerRequestScopeFields",
+ tags: [ApiDocsTags.PkiSigners],
+ description:
+ "Stop enforcing scope parameters on a pending signing request. Open to the requester and to the request's approvers.",
+ params: SignerRequestParamsSchema,
+ body: RemoveCodeSigningScopeFieldsSchema,
+ response: {
+ 200: z.object({
+ request: CodeSigningRequestSchema,
+ removedFields: z.array(z.nativeEnum(CodeSigningScopeField))
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { request, removedFields } = await server.services.signerPolicy.removeRequestScopeFields({
+ signerId: req.params.signerId,
+ requestId: req.params.requestId,
+ removeFields: req.body.removeFields,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: await server.services.pkiSigner.getProjectIdForSigner(req.params.signerId),
+ event: {
+ type: EventType.PKI_SIGNER_REMOVE_REQUEST_SCOPE_FIELDS,
+ metadata: {
+ signerId: req.params.signerId,
+ requestId: req.params.requestId,
+ removedFields
+ }
+ }
+ });
+
+ return { request, removedFields };
+ }
+ });
+
server.route({
method: "POST",
url: "/:signerId/requests/:requestId/revoke",
@@ -156,7 +210,7 @@ export const registerSignerRequestsRouter = async (server: FastifyZodProvider) =
operationId: "revokeSignerRequest",
tags: [ApiDocsTags.PkiSigners],
description: "Revoke a pending or active signing request",
- params: z.object({ signerId: z.string().uuid(), requestId: z.string().uuid() })
+ params: SignerRequestParamsSchema
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
diff --git a/backend/src/server/routes/v1/signer-routers/schemas.ts b/backend/src/server/routes/v1/signer-routers/schemas.ts
index 4d71bf0352..93f74b8e81 100644
--- a/backend/src/server/routes/v1/signer-routers/schemas.ts
+++ b/backend/src/server/routes/v1/signer-routers/schemas.ts
@@ -8,6 +8,8 @@ const RE_NO_NEWLINES = new RE2("^[^\\r\\n]+$");
export const SignerIdParamsSchema = z.object({ signerId: z.string().uuid() });
+export const SignerRequestParamsSchema = SignerIdParamsSchema.extend({ requestId: z.string().uuid() });
+
export const SignerExternalConfigurationSchema = z.discriminatedUnion("caType", [
z.object({
caType: z.literal(CaType.DIGICERT),
diff --git a/backend/src/server/routes/v1/signer-routers/signing-router.ts b/backend/src/server/routes/v1/signer-routers/signing-router.ts
index 420d7eae11..ab94ce4965 100644
--- a/backend/src/server/routes/v1/signer-routers/signing-router.ts
+++ b/backend/src/server/routes/v1/signer-routers/signing-router.ts
@@ -6,6 +6,7 @@ import { SigningAlgorithm } from "@app/lib/crypto/sign/types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { MAX_SIGNING_COMMAND_LENGTH } from "@app/services/approval-policy/code-signing/code-signing-policy-schemas";
import { AuthMode } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
@@ -33,13 +34,17 @@ export const registerSignerSigningRouter = async (server: FastifyZodProvider) =>
.max(128)
.optional()
.describe("The signing application. Compared against a 'signingApplication' scope on the approval."),
+ signingApplication: z
+ .string()
+ .max(128)
+ .optional()
+ .describe("Alias of 'tool', matching the name this parameter has in an approval's scope."),
hostname: z.string().max(256).optional().describe("The machine the sign call is made from."),
- reportedIp: z
+ command: z
.string()
- .max(64)
+ .max(MAX_SIGNING_COMMAND_LENGTH)
.optional()
- .describe("Recorded for audit only. Approvals are matched against the address the call arrives from."),
- command: z.string().max(2048).optional().describe("The command line that issued the sign call."),
+ .describe("The command line that issued the sign call."),
osUsername: z
.string()
.max(256)
@@ -49,12 +54,7 @@ export const registerSignerSigningRouter = async (server: FastifyZodProvider) =>
.string()
.max(64)
.optional()
- .describe("SHA-256 checksum of the signing application binary."),
- moduleVersion: z
- .string()
- .max(64)
- .optional()
- .describe("Version of the Infisical client that made the sign call. Recorded for audit only.")
+ .describe("SHA-256 checksum of the signing application binary.")
})
.optional()
.describe(
diff --git a/backend/src/services/approval-policy/approval-request-dal.ts b/backend/src/services/approval-policy/approval-request-dal.ts
index d37205b5ab..3267f41705 100644
--- a/backend/src/services/approval-policy/approval-request-dal.ts
+++ b/backend/src/services/approval-policy/approval-request-dal.ts
@@ -74,7 +74,9 @@ export const approvalRequestDALFactory = (db: TDbClient) => {
) => {
try {
const dbInstance = db.replicaNode();
- const baseQuery = dbInstance(TableName.ApprovalRequests).where({ type: policyType, projectId });
+ const baseQuery = dbInstance(TableName.ApprovalRequests)
+ .where({ type: policyType, projectId })
+ .orderBy("createdAt", "desc");
if (options?.scopeType === null) {
void baseQuery.whereNull("scopeType");
diff --git a/backend/src/services/approval-policy/code-signing/code-signing-policy-factory.ts b/backend/src/services/approval-policy/code-signing/code-signing-policy-factory.ts
index 5d9602f818..99f4b91fb6 100644
--- a/backend/src/services/approval-policy/code-signing/code-signing-policy-factory.ts
+++ b/backend/src/services/approval-policy/code-signing/code-signing-policy-factory.ts
@@ -83,39 +83,16 @@ export const codeSigningPolicyFactory: TApprovalResourceFactory<
const errors: string[] = [];
const { maxWindowDuration, maxSignings } = policy.constraints.constraints;
- const hasTimeConstraint = Boolean(maxWindowDuration);
- const hasCountConstraint = Boolean(maxSignings);
-
- if (hasTimeConstraint) {
- if (!inputs.requestedWindowStart || !inputs.requestedWindowEnd) {
- errors.push("Both requestedWindowStart and requestedWindowEnd are required for this policy");
- } else {
- const startTime = new Date(inputs.requestedWindowStart).getTime();
- const endTime = new Date(inputs.requestedWindowEnd).getTime();
- const requestedDuration = endTime - startTime;
-
- if (requestedDuration <= 0) {
- errors.push("Requested window end must be after window start");
- }
- if (endTime <= Date.now()) {
- errors.push("Requested window end must be in the future");
- }
- if (maxWindowDuration && requestedDuration > ms(maxWindowDuration)) {
- errors.push(`Requested window duration exceeds maximum of ${maxWindowDuration}`);
- }
- }
- } else if (inputs.requestedWindowStart || inputs.requestedWindowEnd) {
- errors.push("This policy does not allow time-window parameters");
+ if (
+ maxWindowDuration &&
+ inputs.requestedWindowDuration &&
+ ms(inputs.requestedWindowDuration) > ms(maxWindowDuration)
+ ) {
+ errors.push(`Requested window duration exceeds maximum of ${maxWindowDuration}`);
}
- if (hasCountConstraint) {
- if (!inputs.requestedSignings) {
- errors.push("requestedSignings is required for this policy");
- } else if (maxSignings && inputs.requestedSignings > maxSignings) {
- errors.push(`Requested signings (${inputs.requestedSignings}) exceeds maximum of ${maxSignings}`);
- }
- } else if (inputs.requestedSignings) {
- errors.push("This policy does not allow requestedSignings");
+ if (maxSignings && inputs.requestedSignings && inputs.requestedSignings > maxSignings) {
+ errors.push(`Requested signings (${inputs.requestedSignings}) exceeds maximum of ${maxSignings}`);
}
return {
@@ -138,11 +115,10 @@ export const codeSigningPolicyFactory: TApprovalResourceFactory<
grantAttributes.maxSignings = requestData.requestedSignings;
}
- if (requestData.requestedWindowStart) {
- grantAttributes.windowStart = requestData.requestedWindowStart;
- }
- if (requestData.requestedWindowEnd) {
- expiresAt = new Date(requestData.requestedWindowEnd);
+ if (requestData.requestedWindowDuration) {
+ const windowStart = new Date();
+ grantAttributes.windowStart = windowStart.toISOString();
+ expiresAt = new Date(windowStart.getTime() + ms(requestData.requestedWindowDuration));
}
const scope = normalizeCodeSigningScope(requestData.scope);
if (scope) {
diff --git a/backend/src/services/approval-policy/code-signing/code-signing-policy-fns.test.ts b/backend/src/services/approval-policy/code-signing/code-signing-policy-fns.test.ts
index da43a6cdc5..ef228b8b60 100644
--- a/backend/src/services/approval-policy/code-signing/code-signing-policy-fns.test.ts
+++ b/backend/src/services/approval-policy/code-signing/code-signing-policy-fns.test.ts
@@ -3,9 +3,9 @@ import {
buildObservedSigningContext,
commandsMatch,
getCodeSigningScopeMismatches,
- isSameRequestedSigningWindow,
normalizeCodeSigningScope,
- redactCommandCredentials
+ redactCommandCredentials,
+ removeCodeSigningScopeFields
} from "./code-signing-policy-fns";
const DIGEST = "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9";
@@ -207,68 +207,6 @@ describe("commandsMatch", () => {
});
});
-describe("isSameRequestedSigningWindow", () => {
- const MACHINE = false;
- const HUMAN = true;
-
- // The case that made the pending-request lookup useless for signing clients: a retry asks for
- // the same duration, but every call anchors the window at its own "now".
- test("a client retry asking for the same duration later is the same ask", () => {
- const first = { start: "2026-08-04T10:00:00.000Z", end: "2026-08-04T18:00:00.000Z" };
- const retriedSecondsLater = { start: "2026-08-04T10:00:07.000Z", end: "2026-08-04T18:00:07.000Z" };
- const retriedHoursLater = { start: "2026-08-04T15:30:00.000Z", end: "2026-08-04T23:30:00.000Z" };
-
- expect(isSameRequestedSigningWindow(MACHINE, first, retriedSecondsLater)).toBe(true);
- expect(isSameRequestedSigningWindow(MACHINE, first, retriedHoursLater)).toBe(true);
- });
-
- test("a client asking for a different duration is a new ask", () => {
- const eightHours = { start: "2026-08-04T10:00:00.000Z", end: "2026-08-04T18:00:00.000Z" };
- const oneHour = { start: "2026-08-04T10:00:00.000Z", end: "2026-08-04T11:00:00.000Z" };
-
- expect(isSameRequestedSigningWindow(MACHINE, eightHours, oneHour)).toBe(false);
- });
-
- // A person picks absolute times, so two windows of equal length at different times are two
- // different asks and must not collapse into one.
- test("equal-length windows at different times stay distinct for a person", () => {
- const morning = { start: "2026-08-04T10:00:00.000Z", end: "2026-08-04T11:00:00.000Z" };
- const midday = { start: "2026-08-04T11:00:00.000Z", end: "2026-08-04T12:00:00.000Z" };
-
- expect(isSameRequestedSigningWindow(HUMAN, morning, midday)).toBe(false);
- expect(isSameRequestedSigningWindow(HUMAN, morning, { ...morning })).toBe(true);
- });
-
- test("a count-only request with no window at all is the same ask", () => {
- expect(isSameRequestedSigningWindow(MACHINE, {}, {})).toBe(true);
- expect(isSameRequestedSigningWindow(HUMAN, {}, {})).toBe(true);
- });
-
- // With no start there is no duration, so falling back to the instant keeps two different
- // absolute ends apart instead of treating both unknowns as equal.
- test("an end with no start falls back to comparing the instant", () => {
- const a = { end: "2026-08-04T18:00:00.000Z" };
- const b = { end: "2026-08-04T19:00:00.000Z" };
-
- expect(isSameRequestedSigningWindow(MACHINE, a, b)).toBe(false);
- expect(isSameRequestedSigningWindow(MACHINE, a, { ...a })).toBe(true);
- });
-
- test("an unparseable timestamp does not read as a match", () => {
- const good = { start: "2026-08-04T10:00:00.000Z", end: "2026-08-04T18:00:00.000Z" };
- const broken = { start: "not a date", end: "2026-08-04T18:00:00.000Z" };
-
- expect(isSameRequestedSigningWindow(MACHINE, good, broken)).toBe(false);
- });
-
- test("a window is never the same ask as no window", () => {
- const windowed = { start: "2026-08-04T10:00:00.000Z", end: "2026-08-04T18:00:00.000Z" };
-
- expect(isSameRequestedSigningWindow(MACHINE, windowed, {})).toBe(false);
- expect(isSameRequestedSigningWindow(HUMAN, windowed, {})).toBe(false);
- });
-});
-
describe("redactCommandCredentials", () => {
test.each([
["custom-signer --api-token hunter2 --in app.exe", "custom-signer --api-token hunter2 --in app.exe"],
@@ -307,3 +245,36 @@ describe("redactCommandCredentials", () => {
expect(bound?.command).not.toContain("hunter2");
});
});
+
+describe("removeCodeSigningScopeFields", () => {
+ const scope = {
+ [CodeSigningScopeField.Command]: "signtool sign app.exe",
+ [CodeSigningScopeField.Hostname]: "build-01",
+ [CodeSigningScopeField.DataHash]: DIGEST
+ };
+
+ test("takes out the named parameters and keeps the rest", () => {
+ const result = removeCodeSigningScopeFields(scope, [CodeSigningScopeField.DataHash]);
+
+ expect(result.removed).toEqual([CodeSigningScopeField.DataHash]);
+ expect(result.scope).toEqual({
+ [CodeSigningScopeField.Command]: "signtool sign app.exe",
+ [CodeSigningScopeField.Hostname]: "build-01"
+ });
+ });
+
+ // Removing twice must land in the same place, so a retried call is not an error.
+ test("a parameter the scope does not declare is not reported as removed", () => {
+ const result = removeCodeSigningScopeFields(scope, [CodeSigningScopeField.IpAddress]);
+
+ expect(result.removed).toEqual([]);
+ expect(result.scope).toEqual(scope);
+ });
+
+ test("removing every parameter leaves no scope at all", () => {
+ const result = removeCodeSigningScopeFields(scope, Object.values(CodeSigningScopeField));
+
+ expect(result.scope).toBeUndefined();
+ expect(result.removed).toHaveLength(3);
+ });
+});
diff --git a/backend/src/services/approval-policy/code-signing/code-signing-policy-fns.ts b/backend/src/services/approval-policy/code-signing/code-signing-policy-fns.ts
index befa03f50b..f8ff495ce0 100644
--- a/backend/src/services/approval-policy/code-signing/code-signing-policy-fns.ts
+++ b/backend/src/services/approval-policy/code-signing/code-signing-policy-fns.ts
@@ -46,6 +46,26 @@ export const normalizeCodeSigningScope = (scope: TCodeSigningScope | undefined):
return hasAny ? declared : undefined;
};
+/**
+ * The scope with the named parameters taken out. Removing a parameter widens what the approval will
+ * cover, so this only ever runs on a pending request and never on an issued grant.
+ */
+export const removeCodeSigningScopeFields = (
+ scope: TCodeSigningScope,
+ fields: readonly CodeSigningScopeField[]
+): { scope: TCodeSigningScope | undefined; removed: CodeSigningScopeField[] } => {
+ const removed = Object.values(CodeSigningScopeField).filter(
+ (field) => fields.includes(field) && Boolean(scope[field])
+ );
+
+ const remaining: TCodeSigningScope = {};
+ Object.values(CodeSigningScopeField).forEach((field) => {
+ if (scope[field] && !removed.includes(field)) remaining[field] = scope[field];
+ });
+
+ return { scope: Object.keys(remaining).length ? remaining : undefined, removed };
+};
+
export type TObservedSigningContext = {
[CodeSigningScopeField.Command]?: string;
[CodeSigningScopeField.SigningApplication]?: string;
@@ -123,32 +143,3 @@ export const getCodeSigningScopeMismatches = (
return boundValue !== observedValue;
});
};
-
-type TRequestedSigningWindow = { start?: string; end?: string };
-
-/**
- * Whether two requested signing windows are the same ask, which depends on who is asking.
- *
- * A signing client re-derives its window from a configured duration on every call, so a retry asks
- * for identical terms at a later absolute window. Comparing instants would never match and every
- * retry would open a duplicate request. A person picks absolute times, so both ends of the window
- * are compared: 10:00-18:00 and 12:00-18:00 are different asks even though they end together.
- */
-export const isSameRequestedSigningWindow = (
- isHumanRequester: boolean,
- pending: TRequestedSigningWindow,
- incoming: TRequestedSigningWindow
-): boolean => {
- const sameEnd = (pending.end ?? null) === (incoming.end ?? null);
- if (isHumanRequester) return sameEnd && (pending.start ?? null) === (incoming.start ?? null);
-
- if (!pending.start || !pending.end || !incoming.start || !incoming.end) return sameEnd;
-
- const durationOf = (start: string, end: string) => new Date(end).getTime() - new Date(start).getTime();
-
- const pendingDuration = durationOf(pending.start, pending.end);
- const incomingDuration = durationOf(incoming.start, incoming.end);
- // A stored window whose timestamps will not parse is a malformed record, not a match.
- if (Number.isNaN(pendingDuration) || Number.isNaN(incomingDuration)) return false;
- return pendingDuration === incomingDuration;
-};
diff --git a/backend/src/services/approval-policy/code-signing/code-signing-policy-schemas.ts b/backend/src/services/approval-policy/code-signing/code-signing-policy-schemas.ts
index e7c2226aa9..5f619cb89a 100644
--- a/backend/src/services/approval-policy/code-signing/code-signing-policy-schemas.ts
+++ b/backend/src/services/approval-policy/code-signing/code-signing-policy-schemas.ts
@@ -20,17 +20,16 @@ export const CodeSigningPolicyInputsSchema = z.object({
export const CodeSigningPolicyConditionsSchema = z.object({}).array();
-const WindowDurationSchema = z
- .string()
- .refine(
- (val) => {
- const duration = ms(val) / 1000;
- // 1 minute to 30 days
- return duration >= 60 && duration <= 2592000;
- },
- { message: "Window duration must be between 1 minute and 30 days" }
- )
- .optional();
+export const SigningWindowDurationSchema = z.string().refine(
+ (val) => {
+ const duration = ms(val) / 1000;
+ // 1 minute to 30 days
+ return duration >= 60 && duration <= 2592000;
+ },
+ { message: "Window duration must be between 1 minute and 30 days" }
+);
+
+export const MAX_SIGNING_COMMAND_LENGTH = 32767;
const SHA256_HEX_RE = new RE2("^[a-fA-F0-9]{64}$");
@@ -52,7 +51,7 @@ const scopeSha256 = (message: string) =>
.refine((value) => value === undefined || SHA256_HEX_RE.test(value), message);
export const CodeSigningScopeSchema = z.object({
- [CodeSigningScopeField.Command]: scopeText(2048),
+ [CodeSigningScopeField.Command]: scopeText(MAX_SIGNING_COMMAND_LENGTH),
[CodeSigningScopeField.SigningApplication]: scopeText(256),
[CodeSigningScopeField.SigningApplicationHash]: scopeSha256(
"Signing application checksum must be a 64-character SHA-256 hex string"
@@ -74,9 +73,19 @@ export const CodeSigningScopeInputSchema = CodeSigningScopeSchema.strict();
export const CODE_SIGNING_SCOPE_API_DESCRIPTION =
"Optional parameters to scope this approval to (command, signingApplication, signingApplicationHash, hostname, osUsername, ipAddress, dataHash). Every value declared here must match at signing time or the sign call is denied; parameters left out are not restricted. A command must match exactly, apart from whitespace, so a different order of options is a different command. ipAddress is compared against the address the sign call arrives from and dataHash against the digest of the submitted payload, so those two hold even if a caller reports something else.";
+export const RemoveCodeSigningScopeFieldsSchema = z.object({
+ removeFields: z
+ .array(z.nativeEnum(CodeSigningScopeField))
+ .min(1)
+ .max(Object.keys(CodeSigningScopeField).length)
+ .describe(
+ "Scope parameters to stop enforcing on this request, for example ['dataHash'] so the approval covers the same command and machine for any payload. Parameters left in place still have to match at signing time, and naming one the request does not declare has no effect."
+ )
+});
+
export const CodeSigningPolicyConstraintsSchema = z
.object({
- maxWindowDuration: WindowDurationSchema,
+ maxWindowDuration: SigningWindowDurationSchema.optional(),
maxSignings: z.number().int().positive().optional()
})
.refine((data) => data.maxWindowDuration || data.maxSignings, {
@@ -88,8 +97,7 @@ export const CodeSigningPolicyRequestDataSchema = z.object({
approvalPolicyId: z.string().uuid(),
signerName: z.string(),
justification: z.string().max(512).optional(),
- requestedWindowStart: z.string().datetime().optional(),
- requestedWindowEnd: z.string().datetime().optional(),
+ requestedWindowDuration: SigningWindowDurationSchema.optional(),
requestedSignings: z.number().int().positive().optional(),
scope: CodeSigningScopeSchema.optional()
});
diff --git a/backend/src/services/signer/signer-policy-service.ts b/backend/src/services/signer/signer-policy-service.ts
index 94497f3b9c..9e19fbdc50 100644
--- a/backend/src/services/signer/signer-policy-service.ts
+++ b/backend/src/services/signer/signer-policy-service.ts
@@ -8,7 +8,7 @@ import {
ResourcePermissionSignerActions,
ResourcePermissionSub
} from "@app/ee/services/permission/resource-permission";
-import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
import {
@@ -20,7 +20,8 @@ import {
ApprovalPolicyScope,
ApprovalPolicyType,
ApprovalRequestGrantStatus,
- ApprovalRequestStatus
+ ApprovalRequestStatus,
+ ApproverType
} from "../approval-policy/approval-policy-enums";
import {
TApprovalRequestDALFactory,
@@ -31,8 +32,8 @@ import {
import { createApprovalRequestWithSteps, notifyStepApprovers } from "../approval-policy/approval-request-fns";
import { CodeSigningScopeField } from "../approval-policy/code-signing/code-signing-policy-enums";
import {
- isSameRequestedSigningWindow,
- normalizeCodeSigningScope
+ normalizeCodeSigningScope,
+ removeCodeSigningScopeFields
} from "../approval-policy/code-signing/code-signing-policy-fns";
import { TCodeSigningRequestData, TCodeSigningScope } from "../approval-policy/code-signing/code-signing-policy-types";
import { ActorType } from "../auth/auth-type";
@@ -48,6 +49,7 @@ import {
TGetSignerPolicyDTO,
TListSignerRequestsDTO,
TPreApproveSigningDTO,
+ TRemoveSignerRequestScopeFieldsDTO,
TRequestToSignDTO,
TRevokeSignerRequestDTO,
TSignerRequestStatusFilter,
@@ -59,14 +61,17 @@ type TSignerPolicyServiceFactoryDep = {
approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findById" | "updateById" | "findStepsByPolicyId">;
approvalPolicyStepsDAL: Pick<TApprovalPolicyStepsDALFactory, "create" | "delete" | "find">;
approvalPolicyStepApproversDAL: Pick<TApprovalPolicyStepApproversDALFactory, "create" | "delete">;
- approvalRequestDAL: Pick<TApprovalRequestDALFactory, "create" | "find" | "findById" | "updateById" | "transaction">;
+ approvalRequestDAL: Pick<
+ TApprovalRequestDALFactory,
+ "create" | "find" | "findById" | "findByIdForUpdate" | "findStepsByRequestId" | "updateById" | "transaction"
+ >;
signerRequestDAL: TSignerRequestDALFactory;
approvalRequestStepsDAL: Pick<TApprovalRequestStepsDALFactory, "create">;
approvalRequestStepEligibleApproversDAL: Pick<TApprovalRequestStepEligibleApproversDALFactory, "create">;
approvalRequestGrantsDAL: Pick<TApprovalRequestGrantsDALFactory, "create" | "find" | "updateById">;
membershipDAL: Pick<TMembershipDALFactory, "find" | "transaction">;
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;
- userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find" | "findGroupMembershipsByUserIdInOrg">;
identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;
userDAL: Pick<TUserDALFactory, "findById" | "find">;
identityDAL: Pick<TIdentityDALFactory, "findById">;
@@ -84,6 +89,15 @@ type TConstraintsBlob = {
};
};
+const $parseDurationMs = (duration: string): number | null => {
+ try {
+ const parsed = ms(duration);
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
+ } catch {
+ return null;
+ }
+};
+
const $loadSignerOrThrow = async (signerDAL: TSignerPolicyServiceFactoryDep["signerDAL"], signerId: string) => {
const signer = await signerDAL.findById(signerId);
if (!signer) {
@@ -165,8 +179,8 @@ export const signerPolicyServiceFactory = ({
const $resolveRequestEffectiveLimits = (
policyConstraints: unknown,
- dto: { requestedSignings?: number; requestedWindowStart?: string; requestedWindowEnd?: string }
- ): { effectiveSignings?: number; effectiveWindowStart?: string; effectiveWindowEnd?: string } => {
+ dto: { requestedSignings?: number; requestedWindowDuration?: string }
+ ): { effectiveSignings?: number; effectiveWindowDuration?: string } => {
const blob = (policyConstraints as TConstraintsBlob) ?? {};
const maxSignings = blob.constraints?.maxSignings ?? null;
const maxWindowDuration = blob.constraints?.maxWindowDuration ?? null;
@@ -180,50 +194,23 @@ export const signerPolicyServiceFactory = ({
});
}
- let effectiveWindowStart: string | undefined;
- let effectiveWindowEnd: string | undefined;
- if (dto.requestedWindowEnd) {
- const end = new Date(dto.requestedWindowEnd).getTime();
- if (Number.isNaN(end)) {
- throw new BadRequestError({ message: "Invalid requestedWindowEnd date." });
- }
- const rawStart = dto.requestedWindowStart ? new Date(dto.requestedWindowStart).getTime() : Date.now();
- if (Number.isNaN(rawStart)) {
- throw new BadRequestError({ message: "Invalid requestedWindowStart date." });
- }
- const startTime = Math.max(rawStart, Date.now());
- if (end <= startTime) {
+ let effectiveWindowDuration: string | undefined;
+ if (dto.requestedWindowDuration) {
+ const requestedMs = $parseDurationMs(dto.requestedWindowDuration);
+ if (requestedMs === null) {
throw new BadRequestError({
- message: "requestedWindowEnd must be in the future and after requestedWindowStart."
+ message: `Invalid signing window duration '${dto.requestedWindowDuration}'. Use a duration such as '4h' or '30m'.`
});
}
- if (maxWindowDuration) {
- let allowedMs: number;
- try {
- allowedMs = ms(maxWindowDuration);
- } catch {
- allowedMs = Number.POSITIVE_INFINITY;
- }
- if (Number.isFinite(allowedMs) && end - startTime > allowedMs) {
- throw new BadRequestError({
- message: `Requested signing window exceeds the policy maximum of ${maxWindowDuration}.`
- });
- }
+ const allowedMs = maxWindowDuration ? $parseDurationMs(maxWindowDuration) : null;
+ if (allowedMs !== null && requestedMs > allowedMs) {
+ throw new BadRequestError({
+ message: `Requested signing window exceeds the policy maximum of ${maxWindowDuration}.`
+ });
}
- effectiveWindowStart = dto.requestedWindowStart;
- effectiveWindowEnd = dto.requestedWindowEnd;
+ effectiveWindowDuration = dto.requestedWindowDuration;
} else if (maxWindowDuration) {
- let allowedMs: number;
- try {
- allowedMs = ms(maxWindowDuration);
- } catch {
- allowedMs = 0;
- }
- if (allowedMs > 0) {
- const start = new Date();
- effectiveWindowStart = dto.requestedWindowStart ?? start.toISOString();
- effectiveWindowEnd = new Date(start.getTime() + allowedMs).toISOString();
- }
+ effectiveWindowDuration = maxWindowDuration;
}
let effectiveSignings = dto.requestedSignings;
@@ -231,7 +218,7 @@ export const signerPolicyServiceFactory = ({
effectiveSignings = maxSignings;
}
- return { effectiveSignings, effectiveWindowStart, effectiveWindowEnd };
+ return { effectiveSignings, effectiveWindowDuration };
};
const $findDuplicatePendingRequest = async ({
@@ -241,8 +228,7 @@ export const signerPolicyServiceFactory = ({
actorId,
scope,
effectiveSignings,
- effectiveWindowStart,
- effectiveWindowEnd
+ effectiveWindowDuration
}: {
policyId: string;
signerId: string;
@@ -250,8 +236,7 @@ export const signerPolicyServiceFactory = ({
actorId: string;
scope: TCodeSigningScope;
effectiveSignings?: number;
- effectiveWindowStart?: string;
- effectiveWindowEnd?: string;
+ effectiveWindowDuration?: string;
}) => {
const isHumanRequester = actor === ActorType.USER;
const pendingRequests = await approvalRequestDAL.find({
@@ -268,12 +253,7 @@ export const signerPolicyServiceFactory = ({
if (!pendingScope) return false;
if ((requestData?.requestedSignings ?? null) !== (effectiveSignings ?? null)) return false;
- const sameWindow = isSameRequestedSigningWindow(
- isHumanRequester,
- { start: requestData?.requestedWindowStart, end: requestData?.requestedWindowEnd },
- { start: effectiveWindowStart, end: effectiveWindowEnd }
- );
- if (!sameWindow) return false;
+ if ((requestData?.requestedWindowDuration ?? null) !== (effectiveWindowDuration ?? null)) return false;
return Object.values(CodeSigningScopeField).every(
(field) => (pendingScope[field] ?? null) === (scope[field] ?? null)
@@ -605,8 +585,8 @@ export const signerPolicyServiceFactory = ({
});
}
- if (!dto.requestedSignings && !dto.requestedWindowEnd) {
- throw new BadRequestError({ message: "Provide at least one of requestedSignings or requestedWindowEnd." });
+ if (!dto.requestedSignings && !dto.requestedWindowDuration) {
+ throw new BadRequestError({ message: "Provide at least one of requestedSignings or requestedWindowDuration." });
}
const policy = await approvalPolicyDAL.findById(signer.approvalPolicyId);
@@ -614,14 +594,10 @@ export const signerPolicyServiceFactory = ({
throw new NotFoundError({ message: `Policy for signer '${signer.name}' has been removed.` });
}
- const { effectiveSignings, effectiveWindowStart, effectiveWindowEnd } = $resolveRequestEffectiveLimits(
- policy.constraints,
- {
- requestedSignings: dto.requestedSignings,
- requestedWindowStart: dto.requestedWindowStart,
- requestedWindowEnd: dto.requestedWindowEnd
- }
- );
+ const { effectiveSignings, effectiveWindowDuration } = $resolveRequestEffectiveLimits(policy.constraints, {
+ requestedSignings: dto.requestedSignings,
+ requestedWindowDuration: dto.requestedWindowDuration
+ });
const scope = normalizeCodeSigningScope(dto.scope);
if (scope) {
@@ -632,10 +608,11 @@ export const signerPolicyServiceFactory = ({
actorId: dto.actorId,
scope,
effectiveSignings,
- effectiveWindowStart,
- effectiveWindowEnd
+ effectiveWindowDuration
});
- if (duplicate) return duplicate;
+ if (duplicate) {
+ return { ...duplicate, steps: await approvalRequestDAL.findStepsByRequestId(duplicate.id) };
+ }
}
const requester = await $resolveActorDisplay({
@@ -658,8 +635,7 @@ export const signerPolicyServiceFactory = ({
approvalPolicyId: policy.id,
justification: dto.justification,
requestedSignings: effectiveSignings,
- requestedWindowStart: effectiveWindowStart,
- requestedWindowEnd: effectiveWindowEnd,
+ requestedWindowDuration: effectiveWindowDuration,
scope
},
justification: dto.justification,
@@ -704,8 +680,8 @@ export const signerPolicyServiceFactory = ({
if (!dto.granteeUserId && !dto.granteeIdentityId) {
throw new BadRequestError({ message: "granteeUserId or granteeIdentityId is required." });
}
- if (!dto.requestedSignings && !dto.requestedWindowEnd) {
- throw new BadRequestError({ message: "Provide at least one of requestedSignings or requestedWindowEnd." });
+ if (!dto.requestedSignings && !dto.requestedWindowDuration) {
+ throw new BadRequestError({ message: "Provide at least one of requestedSignings or requestedWindowDuration." });
}
if (!signer.approvalPolicyId) {
@@ -717,14 +693,10 @@ export const signerPolicyServiceFactory = ({
if (!policy) {
throw new NotFoundError({ message: `Policy for signer '${signer.name}' has been removed.` });
}
- const { effectiveSignings, effectiveWindowStart, effectiveWindowEnd } = $resolveRequestEffectiveLimits(
- policy.constraints,
- {
- requestedSignings: dto.requestedSignings,
- requestedWindowStart: dto.requestedWindowStart,
- requestedWindowEnd: dto.requestedWindowEnd
- }
- );
+ const { effectiveSignings, effectiveWindowDuration } = $resolveRequestEffectiveLimits(policy.constraints, {
+ requestedSignings: dto.requestedSignings,
+ requestedWindowDuration: dto.requestedWindowDuration
+ });
const scope = normalizeCodeSigningScope(dto.scope);
const granteeRoles = await $resolveGranteeEffectiveRoles({
@@ -747,6 +719,8 @@ export const signerPolicyServiceFactory = ({
});
const orgId = dto.actorOrgId;
+ const windowStart = new Date();
+ const windowDurationMs = effectiveWindowDuration ? $parseDurationMs(effectiveWindowDuration) : null;
const result = await membershipDAL.transaction(async (tx) => {
const request = await approvalRequestDAL.create(
{
@@ -771,8 +745,7 @@ export const signerPolicyServiceFactory = ({
approvalPolicyId: signer.approvalPolicyId,
justification: dto.justification,
requestedSignings: effectiveSignings,
- requestedWindowStart: effectiveWindowStart,
- requestedWindowEnd: effectiveWindowEnd,
+ requestedWindowDuration: effectiveWindowDuration,
scope
}
}
@@ -792,10 +765,10 @@ export const signerPolicyServiceFactory = ({
signerId: signer.id,
signerName: signer.name,
maxSignings: effectiveSignings,
- windowStart: effectiveWindowStart,
+ windowStart: windowDurationMs ? windowStart.toISOString() : undefined,
scope
},
- expiresAt: effectiveWindowEnd ? new Date(effectiveWindowEnd) : null
+ expiresAt: windowDurationMs ? new Date(windowStart.getTime() + windowDurationMs) : null
},
tx
);
@@ -806,6 +779,100 @@ export const signerPolicyServiceFactory = ({
return result;
};
+ const removeRequestScopeFields = async (dto: TRemoveSignerRequestScopeFieldsDTO) => {
+ const signer = await $loadSignerOrThrow(signerDAL, dto.signerId);
+ await $assertResourcePermission(
+ signer.id,
+ signer.projectId,
+ dto.actor,
+ dto.actorId,
+ dto.actorAuthMethod,
+ dto.actorOrgId,
+ ResourcePermissionSignerActions.Read
+ );
+
+ const request = await approvalRequestDAL.findById(dto.requestId);
+ if (!request || request.scopeId !== signer.id || request.type !== ApprovalPolicyType.CertCodeSigning) {
+ throw new NotFoundError({ message: `Request with ID '${dto.requestId}' not found on this signer.` });
+ }
+ if (request.status !== ApprovalRequestStatus.Pending) {
+ throw new BadRequestError({
+ message: `This request is ${request.status}. Scope parameters can only be removed while a request is pending review.`
+ });
+ }
+
+ const requestData = (request.requestData as { requestData?: TCodeSigningRequestData } | null)?.requestData;
+ const scope = requestData?.scope;
+ if (!scope || !Object.values(scope).some(Boolean)) {
+ throw new BadRequestError({ message: "This request has no scope parameters to remove." });
+ }
+
+ const steps = await approvalRequestDAL.findStepsByRequestId(dto.requestId);
+ const currentStep = steps.find((step) => step.stepNumber === request.currentStep);
+
+ if (currentStep?.approvals.length) {
+ throw new BadRequestError({
+ message:
+ "This request already has an approval on its current step. Reject it and open a new request to sign with different parameters."
+ });
+ }
+
+ const isRequester =
+ dto.actor === ActorType.USER ? request.requesterId === dto.actorId : request.machineIdentityId === dto.actorId;
+
+ if (!isRequester) {
+ const groupIds = new Set(
+ dto.actor === ActorType.USER && dto.actorOrgId
+ ? (await userGroupMembershipDAL.findGroupMembershipsByUserIdInOrg(dto.actorId, dto.actorOrgId)).map(
+ (membership) => membership.groupId
+ )
+ : []
+ );
+ const isApprover = Boolean(
+ currentStep?.approvers.some(
+ (approver) =>
+ (approver.type === ApproverType.User && approver.id === dto.actorId) ||
+ (approver.type === ApproverType.Group && groupIds.has(approver.id))
+ )
+ );
+ if (!isApprover) {
+ throw new ForbiddenRequestError({
+ message: "Only the requester or an approver on this request can remove its scope parameters."
+ });
+ }
+ }
+
+ const { request: updatedRow, removedFields } = await approvalRequestDAL.transaction(async (tx) => {
+ const locked = await approvalRequestDAL.findByIdForUpdate(dto.requestId, tx);
+ if (!locked || locked.status !== ApprovalRequestStatus.Pending) {
+ throw new BadRequestError({ message: "This request is no longer pending review." });
+ }
+
+ const lockedBlob = locked.requestData as { version: number; requestData: TCodeSigningRequestData };
+ const lockedScope = lockedBlob.requestData.scope;
+ const { scope: remainingScope, removed } = lockedScope
+ ? removeCodeSigningScopeFields(lockedScope, dto.removeFields)
+ : { scope: undefined, removed: [] };
+
+ const updatedRequest = await approvalRequestDAL.updateById(
+ dto.requestId,
+ {
+ requestData: {
+ ...lockedBlob,
+ requestData: { ...lockedBlob.requestData, scope: remainingScope }
+ }
+ },
+ tx
+ );
+
+ return { request: updatedRequest, removedFields: removed };
+ });
+
+ const updatedBlob = updatedRow.requestData as { version: 1; requestData: TCodeSigningRequestData };
+
+ return { request: { ...updatedRow, requestData: updatedBlob, steps }, removedFields };
+ };
+
const revokeRequest = async (dto: TRevokeSignerRequestDTO) => {
const signer = await $loadSignerOrThrow(signerDAL, dto.signerId);
await $assertResourcePermission(
@@ -852,6 +919,7 @@ export const signerPolicyServiceFactory = ({
listRequests,
requestToSign,
preApproveSigning,
+ removeRequestScopeFields,
revokeRequest
};
};
diff --git a/backend/src/services/signer/signer-service.ts b/backend/src/services/signer/signer-service.ts
index b6855e6837..4de4c51349 100644
--- a/backend/src/services/signer/signer-service.ts
+++ b/backend/src/services/signer/signer-service.ts
@@ -42,7 +42,8 @@ import {
import {
ApprovalPolicyScope,
ApprovalPolicyType,
- ApprovalRequestGrantStatus
+ ApprovalRequestGrantStatus,
+ ApprovalRequestStatus
} from "../approval-policy/approval-policy-enums";
import { TApprovalRequestDALFactory, TApprovalRequestGrantsDALFactory } from "../approval-policy/approval-request-dal";
import {
@@ -55,7 +56,10 @@ import {
redactCommandCredentials,
TObservedSigningContext
} from "../approval-policy/code-signing/code-signing-policy-fns";
-import { TCodeSigningGrantAttributes } from "../approval-policy/code-signing/code-signing-policy-types";
+import {
+ TCodeSigningGrantAttributes,
+ TCodeSigningRequestData
+} from "../approval-policy/code-signing/code-signing-policy-types";
import { ActorType } from "../auth/auth-type";
import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";
import { TCertificateDALFactory } from "../certificate/certificate-dal";
@@ -164,7 +168,7 @@ type TSignerServiceFactoryDep = {
approvalPolicyDAL: TApprovalPolicyDALFactory;
approvalPolicyStepsDAL: Pick<TApprovalPolicyStepsDALFactory, "create">;
approvalPolicyStepApproversDAL: Pick<TApprovalPolicyStepApproversDALFactory, "create">;
- approvalRequestDAL: Pick<TApprovalRequestDALFactory, "delete">;
+ approvalRequestDAL: Pick<TApprovalRequestDALFactory, "delete" | "find">;
approvalRequestGrantsDAL: TApprovalRequestGrantsDALFactory;
membershipDAL: Pick<
TMembershipDALFactory,
@@ -1678,16 +1682,24 @@ export const signerServiceFactory = ({
const requiresApproval = signer.approvalPolicyId ? (await $countPolicySteps(signer.approvalPolicyId)) > 0 : false;
+ const clientMetadata = dto.clientMetadata
+ ? {
+ ...dto.clientMetadata,
+ tool: dto.clientMetadata.tool ?? dto.clientMetadata.signingApplication,
+ signingApplication: undefined
+ }
+ : undefined;
+
const observedContext = buildObservedSigningContext({
- clientMetadata: dto.clientMetadata,
+ clientMetadata,
ipAddress: dto.ipAddress,
dataHash
});
const operationClientMetadata =
- dto.clientMetadata || dto.ipAddress
+ clientMetadata || dto.ipAddress
? {
- ...dto.clientMetadata,
- ...(dto.clientMetadata?.command ? { command: redactCommandCredentials(dto.clientMetadata.command) } : {}),
+ ...clientMetadata,
+ ...(clientMetadata?.command ? { command: redactCommandCredentials(clientMetadata.command) } : {}),
sourceIp: dto.ipAddress
}
: null;
@@ -1707,9 +1719,22 @@ export const signerServiceFactory = ({
});
if (access.deniedReason) {
+ const pendingRequests = await approvalRequestDAL.find({
+ scopeType: ApprovalPolicyScope.Signer,
+ scopeId: signer.id,
+ status: ApprovalRequestStatus.Pending,
+ ...(dto.actor === ActorType.USER ? { requesterId: dto.actorId } : { machineIdentityId: dto.actorId })
+ });
+ const hasPendingRequest = pendingRequests.some((request) => {
+ const pendingScope = (request.requestData as { requestData?: TCodeSigningRequestData } | null)?.requestData
+ ?.scope;
+ return getCodeSigningScopeMismatches(pendingScope, observedContext).length === 0;
+ });
+
throw new ForbiddenRequestError({
message: access.deniedReason,
- name: SIGNER_APPROVAL_REQUIRED_ERROR_NAME
+ name: SIGNER_APPROVAL_REQUIRED_ERROR_NAME,
+ details: { hasPendingRequest }
});
}
diff --git a/backend/src/services/signer/signer-types.ts b/backend/src/services/signer/signer-types.ts
index 22d7a2ea33..fe1d4d410f 100644
--- a/backend/src/services/signer/signer-types.ts
+++ b/backend/src/services/signer/signer-types.ts
@@ -4,6 +4,7 @@ import { z } from "zod";
import { SigningAlgorithm } from "@app/lib/crypto/sign/types";
import { TProjectPermission } from "@app/lib/types";
+import { CodeSigningScopeField } from "../approval-policy/code-signing/code-signing-policy-enums";
import { TCodeSigningScope } from "../approval-policy/code-signing/code-signing-policy-types";
import { CertKeyAlgorithm } from "../certificate/certificate-types";
import { CaType } from "../certificate-authority/certificate-authority-enums";
@@ -98,8 +99,8 @@ export type TSignDataDTO = {
actorName?: string;
clientMetadata?: {
tool?: string;
+ signingApplication?: string;
hostname?: string;
- reportedIp?: string;
command?: string;
osUsername?: string;
signingApplicationHash?: string;
@@ -181,8 +182,7 @@ export type TRequestToSignDTO = {
signerId: string;
justification: string;
requestedSignings?: number;
- requestedWindowStart?: string;
- requestedWindowEnd?: string;
+ requestedWindowDuration?: string;
scope?: TCodeSigningScope;
} & TActorPermission;
@@ -192,11 +192,16 @@ export type TPreApproveSigningDTO = {
granteeIdentityId?: string;
justification: string;
requestedSignings?: number;
- requestedWindowStart?: string;
- requestedWindowEnd?: string;
+ requestedWindowDuration?: string;
scope?: TCodeSigningScope;
} & TActorPermission;
+export type TRemoveSignerRequestScopeFieldsDTO = {
+ signerId: string;
+ requestId: string;
+ removeFields: CodeSigningScopeField[];
+} & TActorPermission;
+
export type TRevokeSignerRequestDTO = {
signerId: string;
requestId: string;
diff --git a/docs/documentation/platform/pki/code-signing/approvals.mdx b/docs/documentation/platform/pki/code-signing/approvals.mdx
index fd9b79e1f2..232cd9c29a 100644
--- a/docs/documentation/platform/pki/code-signing/approvals.mdx
+++ b/docs/documentation/platform/pki/code-signing/approvals.mdx
@@ -78,7 +78,7 @@ Open the Signer's **Approvals** tab and click the pencil icon on the **Approval
| Field | Description |
|-------|-------------|
| **Signatures per approval** | How many signing operations one approval is good for. Leave empty for unlimited. Set to **1** for "approve once per artifact". |
- | **Signing window** | How long the access record is valid after approval. Options: No limit, 1h, 8h, 24h, 7d, 30d. |
+ | **Signing window** | The longest an access record can stay valid, counted from approval. Options: No limit, 1h, 8h, 24h, 7d, 30d. |
You can combine both. For example: `maxSignings=10` with `signing window=1h` issues access good for at most 10 sign calls within one hour of approval, whichever comes first.
@@ -88,10 +88,6 @@ Open the Signer's **Approvals** tab and click the pencil icon on the **Approval
Press **Save policy**. The new policy applies to **new** requests; existing active access keeps its original terms until it expires or is revoked.
-<Warning>
- **The signing window runs from when the request is opened, not from when it is approved**, because the requester picks the start and end times and approval activates that window. Time spent waiting for an approver comes out of it, so set the window wide enough to cover how long approvals usually take.
-</Warning>
-
## Scoping an approval
By default an approval means "this member may sign N times before it expires". Expanding **Scope this request** on a request or pre-approval lets you narrow that to a specific signing situation. Every parameter is optional, and the ones you fill in are the only ones that get restricted.
@@ -136,6 +132,16 @@ The [PKCS#11 module](/documentation/platform/pki/code-signing/pkcs11-module) and
Filling in a digest by hand is fiddly, because a sign call carries a digest rather than the file, so the value to declare is the hash of the bytes the call submits and not `sha256sum yourfile`. If you are calling the API directly, see the [Sign API reference](/api-reference/endpoints/code-signing/signers/sign).
</Note>
+### Removing a parameter from a request
+
+A scoped request is not fixed once it is open. While it is still pending review, both the requester and the request's approvers can stop enforcing any parameter on it, from the **Request Scope** panel on the request. The parameters left in place still have to match at signing time.
+
+This is what makes a digest-scoped request usable for a pipeline that signs on every build. A client opens its request pinned to the artifact it was denied on, someone drops **Data Digest**, and the approval that follows covers that command on that machine for any artifact until the window or the signature count runs out.
+
+<Warning>
+ Removing a parameter widens what the approval will cover, so it is recorded in the audit log against whoever did it. Once a request is approved its scope is fixed: the access record enforces exactly the parameters that were left in place, and loosening it further means a new request.
+</Warning>
+
## Access lifecycle
Every approved request becomes an **active access record**. On the Approvals tab it's a row in the Requests table with its own status, expiry, and signature counter.
@@ -170,8 +176,7 @@ There are two ways someone gets active access on a Signer: Administrators **pre-
|-------|-------------|
| **Justification** | Short note recorded on the access record for audit. Required. |
| **Signatures allowed** | How many sign operations the access permits. Capped at the policy's **Signatures per approval**. Leave empty to fall back to the policy ceiling. |
- | **When access begins** | Defaults to "now". |
- | **When access expires** | Capped at the policy's **Signing window**. Leave empty to fall back to the policy ceiling. |
+ | **How long the approval lasts** | How long the access stays usable, counted from the moment the access is granted. Capped at the policy's **Signing window**. |
| **Scope this request** | Optional. Expand it to [scope](#scoping-an-approval) the access to a specific command, signing tool, checksum, machine, OS account, IP address, or payload digest. Useful for pre-approving a known build agent: set its address and the access only works from there. |
<Note>
@@ -200,8 +205,7 @@ There are two ways someone gets active access on a Signer: Administrators **pre-
| Field | Description |
|-------|-------------|
| **Signatures requested** | How many sign operations you need. Capped at the policy's **Signatures per approval**. Leave empty to fall back to the policy ceiling. |
- | **When access begins** | When the access window should start once approvals complete. Defaults to "now". |
- | **When access expires** | When the access window should end. Capped at the policy's **Signing window**. Leave empty to fall back to the policy ceiling. |
+ | **How long the approval lasts** | How long you need the access for, counted from the moment approvals complete. Capped at the policy's **Signing window**. Waiting for an approver does not eat into it. |
| **Scope this request** | Optional. Expand it to [scope](#scoping-an-approval) your access to the command, signing tool, checksum, machine, OS account, IP address, or payload digest you will sign with. Approvers see whatever you declare, and the access only covers matching sign calls. |
<Note>
@@ -227,7 +231,7 @@ If you're an eligible approver for the **current** step of a pending request, an
<Steps>
<Step title="Open the request">
- Click the row on the Signer's **Approvals** tab. Full details: requester, recipient, justification, requested signings, requested window, and which step is currently pending.
+ Click the row on the Signer's **Approvals** tab. Full details: requester, recipient, justification, requested signings, requested duration, and which step is currently pending.
</Step>
<Step title="Review">
Verify who's asking, for how many signings, for how long, and why. If the requester scoped the request, the detail page lists every parameter the access will be limited to, so you can see exactly which signing situation you are approving.
diff --git a/docs/documentation/platform/pki/code-signing/windows-ksp.mdx b/docs/documentation/platform/pki/code-signing/windows-ksp.mdx
index 2e53014181..bf1fdb2825 100644
--- a/docs/documentation/platform/pki/code-signing/windows-ksp.mdx
+++ b/docs/documentation/platform/pki/code-signing/windows-ksp.mdx
@@ -123,7 +123,7 @@ $env:INFISICAL_TOKEN = "<your-access-token>"
| `cache.token_ttl_seconds` | No | `300` | How long to reuse a login token before logging in again. |
| `cache.cert_ttl_seconds` | No | `3600` | How long to reuse a downloaded certificate. |
| `cache.signer_ttl_seconds` | No | `300` | How long to reuse the list of Signers. |
-| `approval.signing_duration` | No | None | Ask for an access window of this length when signing is denied for want of approved access (`30m`, `8h`, `2d`). The provider accepts 1m to 30d as a sanity check; the real limit is the Signer's approval policy. The window starts when the request is opened, not when it is approved, so allow for review time. |
+| `approval.signing_duration` | No | None | Ask for an access window of this length when signing is denied for want of approved access (`30m`, `8h`, `2d`). The provider accepts 1m to 30d as a sanity check; the real limit is the Signer's approval policy. The window starts when the request is approved, so time spent waiting for an approver does not eat into it. |
| `approval.signing_count` | No | None | Ask for access good for this many signing operations. |
| `log_level` | No | `info` | How much detail to log: `trace`, `debug`, `info`, `warn`, or `error`. |
| `log_file` | No | `%ProgramData%\Infisical\ksp.log` | Where to write the log. `signtool` has no window to print to, so the plug-in writes here by default. |
diff --git a/frontend/src/helpers/datetime.ts b/frontend/src/helpers/datetime.ts
index aadf0a7a10..f758daf50b 100644
--- a/frontend/src/helpers/datetime.ts
+++ b/frontend/src/helpers/datetime.ts
@@ -24,12 +24,6 @@ export const formatDateTime = ({
return format(date, dateFormat);
};
-export const toDateTimeLocalInputValue = (epochMs: number) => {
- const date = new Date(epochMs);
- const pad = (part: number) => String(part).padStart(2, "0");
- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
-};
-
export const parseDurationMs = (duration?: string | null): number | null => {
if (!duration) return null;
try {
diff --git a/frontend/src/hooks/api/approvalRequests/types.ts b/frontend/src/hooks/api/approvalRequests/types.ts
index 9ff15522fc..7392c0d8f2 100644
--- a/frontend/src/hooks/api/approvalRequests/types.ts
+++ b/frontend/src/hooks/api/approvalRequests/types.ts
@@ -89,8 +89,7 @@ export type CodeSigningRequestData = {
approvalPolicyId: string;
signerName: string;
justification?: string;
- requestedWindowStart?: string;
- requestedWindowEnd?: string;
+ requestedWindowDuration?: string;
requestedSignings?: number;
scope?: TCodeSigningScope;
};
diff --git a/frontend/src/hooks/api/signers/index.tsx b/frontend/src/hooks/api/signers/index.tsx
index c2da06ccfb..b2f48beeb2 100644
--- a/frontend/src/hooks/api/signers/index.tsx
+++ b/frontend/src/hooks/api/signers/index.tsx
@@ -12,6 +12,7 @@ export {
useReissueSignerCertificate,
useRemoveSignerGroupMember,
useRemoveSignerIdentityMember,
+ useRemoveSignerRequestScopeFields,
useRemoveSignerUserMember,
useRequestToSign,
useRevokeSignerRequest,
diff --git a/frontend/src/hooks/api/signers/mutations.tsx b/frontend/src/hooks/api/signers/mutations.tsx
index 7d3f21b006..884f815141 100644
--- a/frontend/src/hooks/api/signers/mutations.tsx
+++ b/frontend/src/hooks/api/signers/mutations.tsx
@@ -3,9 +3,11 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { createNotification } from "@app/components/notifications";
import { apiRequest } from "@app/config/request";
import { approvalRequestQuery } from "@app/hooks/api/approvalRequests/queries";
+import { TApprovalRequest } from "@app/hooks/api/approvalRequests/types";
import { signerKeys } from "./queries";
import {
+ CodeSigningScopeField,
SignerStatus,
TAddSignerGroupMemberDTO,
TAddSignerIdentityMemberDTO,
@@ -18,6 +20,7 @@ import {
TReissueSignerCertificateDTO,
TRemoveSignerGroupDTO,
TRemoveSignerIdentityDTO,
+ TRemoveSignerRequestScopeFieldsDTO,
TRemoveSignerUserDTO,
TRequestToSignDTO,
TRevokeSignerRequestDTO,
@@ -416,3 +419,26 @@ export const useRevokeSignerRequest = () => {
}
});
};
+
+export const useRemoveSignerRequestScopeFields = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation<
+ { removedFields: CodeSigningScopeField[]; request: TApprovalRequest },
+ object,
+ TRemoveSignerRequestScopeFieldsDTO
+ >({
+ mutationFn: async ({ signerId, requestId, removeFields }) => {
+ const { data } = await apiRequest.patch<{
+ removedFields: CodeSigningScopeField[];
+ request: TApprovalRequest;
+ }>(`/api/v1/cert-manager/signers/${signerId}/requests/${requestId}/scope`, { removeFields });
+ return data;
+ },
+ onSuccess: (_, { signerId }) => {
+ queryClient.invalidateQueries({ queryKey: signerKeys.requests(signerId) });
+ queryClient.invalidateQueries({ queryKey: approvalRequestQuery.allKey() });
+ createNotification({ text: "Scope parameter removed from the request", type: "success" });
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/signers/types.ts b/frontend/src/hooks/api/signers/types.ts
index 522a94dd50..27bee98dae 100644
--- a/frontend/src/hooks/api/signers/types.ts
+++ b/frontend/src/hooks/api/signers/types.ts
@@ -106,7 +106,7 @@ export const codeSigningScopeFieldDescriptions: Record<CodeSigningScopeField, st
[CodeSigningScopeField.Hostname]: "The machine the signing requests come from.",
[CodeSigningScopeField.OsUsername]: "The operating system account running the signing tool.",
[CodeSigningScopeField.IpAddress]: "The address sign calls must come from.",
- [CodeSigningScopeField.DataHash]: "SHA-256 hash of the payload being signed."
+ [CodeSigningScopeField.DataHash]: "SHA-256 digest of the payload being signed."
};
/** How each value is compared at signing time, mirroring the API's matching rules. */
@@ -223,7 +223,6 @@ export type TSigningOperation = {
clientMetadata?: {
tool?: string;
hostname?: string;
- reportedIp?: string;
command?: string;
sourceIp?: string;
osUsername?: string;
@@ -510,8 +509,7 @@ export type TRequestToSignDTO = {
signerId: string;
justification: string;
requestedSignings?: number;
- requestedWindowStart?: string;
- requestedWindowEnd?: string;
+ requestedWindowDuration?: string;
scope?: TCodeSigningScope;
};
export type TPreApproveSigningDTO = {
@@ -520,8 +518,12 @@ export type TPreApproveSigningDTO = {
granteeIdentityId?: string;
justification: string;
requestedSignings?: number;
- requestedWindowStart?: string;
- requestedWindowEnd?: string;
+ requestedWindowDuration?: string;
scope?: TCodeSigningScope;
};
+export type TRemoveSignerRequestScopeFieldsDTO = {
+ signerId: string;
+ requestId: string;
+ removeFields: CodeSigningScopeField[];
+};
export type TRevokeSignerRequestDTO = { signerId: string; requestId: string };
diff --git a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx
index a896fb6bff..72dfb2175f 100644
--- a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx
+++ b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/ApprovalRequestDetailPage.tsx
@@ -1,20 +1,37 @@
+import { useState } from "react";
import { Helmet } from "react-helmet";
import { faBan, faChevronLeft } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useQuery } from "@tanstack/react-query";
import { Link, useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { format } from "date-fns";
+import { XIcon } from "lucide-react";
import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications";
-import { Button, ConfirmActionModal, ContentLoader, EmptyState } from "@app/components/v2";
-import { Badge } from "@app/components/v3";
-import { useOrganization, useProject, useUser } from "@app/context";
+import { ConfirmActionModal, ContentLoader, EmptyState } from "@app/components/v2";
+import {
+ Badge,
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ IconButton
+} from "@app/components/v3";
+import { useOrganization, useProject, useProjectPermission, useUser } from "@app/context";
import { usePopUp } from "@app/hooks";
-import { ApprovalPolicyScope, ApprovalPolicyType } from "@app/hooks/api/approvalPolicies";
+import {
+ ApprovalPolicyScope,
+ ApprovalPolicyType,
+ ApproverType
+} from "@app/hooks/api/approvalPolicies";
import {
approvalRequestQuery,
ApprovalRequestStatus,
+ ApprovalRequestStepStatus,
CertRequestRequestData,
CodeSigningRequestData,
useCancelApprovalRequest
@@ -23,7 +40,8 @@ import { useGetPkiApplicationById } from "@app/hooks/api/pkiApplications";
import {
CodeSigningScopeField,
codeSigningScopeFieldLabels,
- MONOSPACED_SCOPE_FIELDS
+ MONOSPACED_SCOPE_FIELDS,
+ useRemoveSignerRequestScopeFields
} from "@app/hooks/api/signers";
import {
@@ -38,12 +56,33 @@ const ROUTE_ID =
const CodeSigningDetailsSection = ({
requestData,
requesterName,
- requesterEmail
+ requesterEmail,
+ requestId,
+ canEditScope
}: {
requestData: CodeSigningRequestData;
requesterName?: string;
requesterEmail?: string;
+ requestId: string;
+ canEditScope: boolean;
}) => {
+ const removeScopeFields = useRemoveSignerRequestScopeFields();
+ const [fieldToRemove, setFieldToRemove] = useState<CodeSigningScopeField | null>(null);
+
+ const handleRemove = async () => {
+ if (!fieldToRemove) return;
+ try {
+ await removeScopeFields.mutateAsync({
+ signerId: requestData.signerId,
+ requestId,
+ removeFields: [fieldToRemove]
+ });
+ setFieldToRemove(null);
+ } catch {
+ // The mutation cache reports the failure
+ }
+ };
+
return (
<div className="flex flex-col gap-4">
<div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
@@ -72,21 +111,13 @@ const CodeSigningDetailsSection = ({
<span className="text-xs text-mineshaft-400">Signer</span>
<p className="text-sm text-mineshaft-100">{requestData.signerName}</p>
</div>
- {requestData.requestedWindowStart && requestData.requestedWindowEnd && (
- <>
- <div>
- <span className="text-xs text-mineshaft-400">Valid From</span>
- <p className="text-sm text-mineshaft-100">
- {format(new Date(requestData.requestedWindowStart), "yyyy-MM-dd, hh:mm aaa")}
- </p>
- </div>
- <div>
- <span className="text-xs text-mineshaft-400">Valid Until</span>
- <p className="text-sm text-mineshaft-100">
- {format(new Date(requestData.requestedWindowEnd), "yyyy-MM-dd, hh:mm aaa")}
- </p>
- </div>
- </>
+ {requestData.requestedWindowDuration && (
+ <div>
+ <span className="text-xs text-mineshaft-400">Access Duration</span>
+ <p className="text-sm text-mineshaft-100">
+ {requestData.requestedWindowDuration} from approval
+ </p>
+ </div>
)}
{requestData.requestedSignings && (
<div>
@@ -105,24 +136,71 @@ const CodeSigningDetailsSection = ({
{Object.values(CodeSigningScopeField)
.filter((field) => requestData.scope?.[field])
.map((field) => (
- <div key={field}>
- <span className="text-xs text-mineshaft-400">
- {codeSigningScopeFieldLabels[field]}
- </span>
- <p
- className={twMerge(
- "text-sm break-all text-mineshaft-100",
- MONOSPACED_SCOPE_FIELDS.includes(field) && "font-mono text-xs"
- )}
- >
- {requestData.scope?.[field]}
- </p>
+ <div key={field} className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <span className="text-xs text-mineshaft-400">
+ {codeSigningScopeFieldLabels[field]}
+ </span>
+ <p
+ className={twMerge(
+ "text-sm break-all text-mineshaft-100",
+ MONOSPACED_SCOPE_FIELDS.includes(field) && "font-mono text-xs"
+ )}
+ >
+ {requestData.scope?.[field]}
+ </p>
+ </div>
+ {canEditScope && (
+ <IconButton
+ variant="ghost"
+ size="sm"
+ className="shrink-0"
+ aria-label={`Stop enforcing ${codeSigningScopeFieldLabels[field]}`}
+ onClick={() => setFieldToRemove(field)}
+ >
+ <XIcon className="size-4" />
+ </IconButton>
+ )}
</div>
))}
</div>
</div>
)}
</div>
+
+ <Dialog
+ open={Boolean(fieldToRemove)}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setFieldToRemove(null);
+ }}
+ >
+ <DialogContent className="max-w-lg">
+ <DialogHeader>
+ <DialogTitle>
+ {fieldToRemove
+ ? `Stop enforcing ${codeSigningScopeFieldLabels[fieldToRemove]}?`
+ : "Stop enforcing this parameter?"}
+ </DialogTitle>
+ <DialogDescription>
+ Signing will be allowed whatever value this parameter takes. The other parameters
+ still have to match.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setFieldToRemove(null)} className="flex-1">
+ Cancel
+ </Button>
+ <Button
+ variant="danger"
+ onClick={handleRemove}
+ isPending={removeScopeFields.isPending}
+ className="flex-1"
+ >
+ Stop enforcing
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
</div>
);
};
@@ -133,6 +211,8 @@ const PageContent = () => {
const { currentOrg } = useOrganization();
const { currentProject } = useProject();
const { user: currentUser } = useUser();
+ const { memberships } = useProjectPermission();
+ const userGroupIds = memberships.map((membership) => membership.actorGroupId).filter(Boolean);
const cancelApprovalRequest = useCancelApprovalRequest();
const navigate = useNavigate();
const { handlePopUpOpen, handlePopUpToggle, popUp } = usePopUp(["cancelRequest"]);
@@ -315,11 +395,27 @@ const PageContent = () => {
const renderDetailsSection = () => {
if (isCodeSigning) {
const reqData = request.requestData.requestData as CodeSigningRequestData;
+ const isRequester = Boolean(currentUser?.id) && request.requesterId === currentUser?.id;
+ const currentStep = request.steps.find(
+ (step) => step.status === ApprovalRequestStepStatus.InProgress
+ );
+ const isCurrentStepApprover = Boolean(
+ currentStep?.approvers.some((approver) =>
+ approver.type === ApproverType.User
+ ? approver.id === currentUser?.id
+ : userGroupIds.includes(approver.id)
+ )
+ );
return (
<CodeSigningDetailsSection
requestData={reqData}
requesterName={request.requesterName}
requesterEmail={request.requesterEmail}
+ requestId={request.id}
+ canEditScope={
+ request.status === ApprovalRequestStatus.Pending &&
+ (isRequester || isCurrentStepApprover)
+ }
/>
);
}
@@ -411,9 +507,9 @@ const PageContent = () => {
request.status === ApprovalRequestStatus.Pending && (
<Button
onClick={() => handlePopUpOpen("cancelRequest")}
- variant="outline_bg"
+ variant="outline"
size="xs"
- isLoading={cancelApprovalRequest.isPending}
+ isPending={cancelApprovalRequest.isPending}
>
Cancel Request
</Button>
diff --git a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/ApprovalStepsSection.tsx b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/ApprovalStepsSection.tsx
index f37d7b6ac2..c55cb45b0f 100644
--- a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/ApprovalStepsSection.tsx
+++ b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/ApprovalStepsSection.tsx
@@ -1,8 +1,17 @@
import { useMemo } from "react";
import { CheckCircle2, Eye, User } from "lucide-react";
-import { Tooltip } from "@app/components/v2";
-import { Badge } from "@app/components/v3";
+import {
+ Badge,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger
+} from "@app/components/v3";
import { useProject } from "@app/context";
import { useGetWorkspaceUsers, useListWorkspaceGroups } from "@app/hooks/api";
import { ApproverType } from "@app/hooks/api/approvalPolicies";
@@ -27,14 +36,10 @@ const getMemberLabel = (member: {
return user.username || user.email;
};
-const getStepCircleClasses = (isCurrentStep: boolean, isCompleted: boolean) => {
- if (isCurrentStep) {
- return "bg-primary/20 text-primary ring-2 ring-primary/50";
- }
- if (isCompleted) {
- return "bg-primary text-black";
- }
- return "bg-mineshaft-600 text-mineshaft-300";
+const getStepMarkerClasses = (isCurrentStep: boolean, isCompleted: boolean) => {
+ if (isCurrentStep) return "border-project/25 bg-project/10 text-project";
+ if (isCompleted) return "border-success/25 bg-success/10 text-success";
+ return "border-border bg-foreground/5 text-muted";
};
export const ApprovalStepsSection = ({ request }: Props) => {
@@ -59,96 +64,106 @@ export const ApprovalStepsSection = ({ request }: Props) => {
);
return (
- <div className="flex w-full flex-col rounded-lg border border-mineshaft-600 bg-mineshaft-900 px-4 py-4">
- <h3 className="mb-4 text-base font-medium text-mineshaft-100">Approval Workflow</h3>
-
- {request.steps.length === 0 && request.status === ApprovalRequestStatus.Approved ? (
- <div className="flex items-start gap-3 rounded-md border border-mineshaft-600 bg-mineshaft-800 px-3 py-3">
- <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary/15 text-primary">
- <CheckCircle2 className="h-4 w-4" />
- </div>
- <div className="min-w-0">
- <p className="text-sm font-medium text-mineshaft-100">Pre-approved</p>
- <p className="mt-0.5 text-xs text-mineshaft-400">
- An Administrator pre-approved this request.
- </p>
- </div>
- </div>
- ) : (
- <div className="relative space-y-0">
- {request.steps.map((step, index) => {
- const isCurrentStep = step.status === ApprovalRequestStepStatus.InProgress;
- const isCompleted = step.status === ApprovalRequestStepStatus.Completed;
- const isLast = index === request.steps.length - 1;
-
- return (
- <div key={step.id} className="relative flex gap-3">
- {!isLast && (
- <div
- className={`absolute top-6 left-[11px] h-[calc(100%-26px)] w-0.5 ${
- isCompleted ? "bg-primary" : "bg-mineshaft-600"
- }`}
- />
- )}
+ <Card>
+ <CardHeader>
+ <CardTitle>Approval Workflow</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <TooltipProvider>
+ {request.steps.length === 0 && request.status === ApprovalRequestStatus.Approved ? (
+ <div className="flex items-start gap-3 rounded-md border border-border bg-foreground/5 px-3 py-3">
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-success/10 text-success">
+ <CheckCircle2 className="h-4 w-4" />
+ </div>
+ <div className="min-w-0">
+ <p className="text-sm font-medium text-foreground">Pre-approved</p>
+ <p className="mt-0.5 text-xs text-muted">
+ An Administrator pre-approved this request.
+ </p>
+ </div>
+ </div>
+ ) : (
+ <div className="relative space-y-0">
+ {request.steps.map((step, index) => {
+ const isCurrentStep = step.status === ApprovalRequestStepStatus.InProgress;
+ const isCompleted = step.status === ApprovalRequestStepStatus.Completed;
+ const isLast = index === request.steps.length - 1;
- <div
- className={`relative z-10 flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-xs text-xs font-medium ${getStepCircleClasses(isCurrentStep, isCompleted)}`}
- >
- {index + 1}
- </div>
+ return (
+ <div key={step.id} className="relative flex gap-3">
+ {!isLast && (
+ <div
+ className={`absolute top-6 left-[11px] h-[calc(100%-26px)] w-0.5 ${
+ isCompleted ? "bg-success/40" : "bg-border"
+ }`}
+ />
+ )}
- <div className={`flex-1 pb-4 ${isLast ? "pb-0" : ""}`}>
- <div className="flex items-center gap-2">
- <span
- className={`text-sm font-medium ${isCurrentStep || isCompleted ? "text-mineshaft-100" : "text-mineshaft-400"}`}
+ <div
+ className={`relative z-10 flex size-6 shrink-0 items-center justify-center rounded-xs border text-xs font-medium ${getStepMarkerClasses(isCurrentStep, isCompleted)}`}
>
- {step.name || `Step ${index + 1}`}
- </span>
- {isCurrentStep && (
- <Badge variant="project" className="text-xs">
- Current
- </Badge>
- )}
- </div>
- <p className="mt-0.5 text-xs text-mineshaft-400">
- {step.requiredApprovals} approval{step.requiredApprovals > 1 ? "s" : ""}{" "}
- required
- </p>
+ {index + 1}
+ </div>
- <div className="mt-2 space-y-1">
- {step.approvers.map((approver) => {
- const approval = step.approvals.find((a) => a.approverUserId === approver.id);
- const isApproved =
- approval?.decision === ApprovalRequestApprovalDecision.Approved;
- const isRejected =
- approval?.decision === ApprovalRequestApprovalDecision.Rejected;
- const hasComment = approval?.comment;
- return (
- <div
- key={approver.id}
- className="flex items-center gap-2 rounded-md bg-mineshaft-700 px-3 py-1.5 text-sm text-mineshaft-300"
+ <div className={`flex-1 pb-4 ${isLast ? "pb-0" : ""}`}>
+ <div className="flex items-center gap-2">
+ <span
+ className={`text-sm font-medium ${isCurrentStep || isCompleted ? "text-foreground" : "text-muted"}`}
>
- <User className="h-3.5 w-3.5" />
- <span className="flex-1">
- {getApproverLabel(approver.id, approver.type)}
- </span>
- {isApproved && <span className="text-xs text-green-500">Approved</span>}
- {isRejected && <span className="text-xs text-red-500">Rejected</span>}
- {hasComment && (
- <Tooltip content={approval.comment}>
- <Eye className="h-3.5 w-3.5 cursor-pointer text-mineshaft-400 hover:text-mineshaft-200" />
- </Tooltip>
- )}
- </div>
- );
- })}
+ {step.name || `Step ${index + 1}`}
+ </span>
+ {isCurrentStep && (
+ <Badge variant="project" className="text-xs">
+ Current
+ </Badge>
+ )}
+ </div>
+ <p className="mt-0.5 text-xs text-muted">
+ {step.requiredApprovals} approval{step.requiredApprovals > 1 ? "s" : ""}{" "}
+ required
+ </p>
+
+ <div className="mt-2 space-y-1">
+ {step.approvers.map((approver) => {
+ const approval = step.approvals.find(
+ (a) => a.approverUserId === approver.id
+ );
+ const isApproved =
+ approval?.decision === ApprovalRequestApprovalDecision.Approved;
+ const isRejected =
+ approval?.decision === ApprovalRequestApprovalDecision.Rejected;
+ const hasComment = approval?.comment;
+ return (
+ <div
+ key={approver.id}
+ className="flex items-center gap-2 rounded-md border border-border bg-foreground/5 px-3 py-1.5 text-sm text-foreground"
+ >
+ <User className="size-3.5 text-muted" />
+ <span className="flex-1">
+ {getApproverLabel(approver.id, approver.type)}
+ </span>
+ {isApproved && <Badge variant="success">Approved</Badge>}
+ {isRejected && <Badge variant="danger">Rejected</Badge>}
+ {hasComment && (
+ <Tooltip>
+ <TooltipTrigger>
+ <Eye className="size-3.5 cursor-pointer text-muted hover:text-foreground" />
+ </TooltipTrigger>
+ <TooltipContent>{approval.comment}</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
</div>
- </div>
- </div>
- );
- })}
- </div>
- )}
- </div>
+ );
+ })}
+ </div>
+ )}
+ </TooltipProvider>
+ </CardContent>
+ </Card>
);
};
diff --git a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/RequestActionsSection.tsx b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/RequestActionsSection.tsx
index c8aeee28e4..f35b58797b 100644
--- a/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/RequestActionsSection.tsx
+++ b/frontend/src/pages/cert-manager/ApprovalRequestDetailPage/components/RequestActionsSection.tsx
@@ -1,10 +1,22 @@
import { useState } from "react";
-import { faCheck, faXmark } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { TriangleAlertIcon } from "lucide-react";
+import { CheckIcon, TriangleAlertIcon, XIcon } from "lucide-react";
import { createNotification } from "@app/components/notifications";
-import { Button, FormLabel, Modal, ModalContent, TextArea } from "@app/components/v2";
+import {
+ Button,
+ Card,
+ CardContent,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldLabel,
+ TextArea
+} from "@app/components/v3";
import { useProjectPermission, useUser } from "@app/context";
import { usePopUp } from "@app/hooks";
import { ApprovalPolicyType, ApproverType } from "@app/hooks/api/approvalPolicies";
@@ -62,11 +74,13 @@ export const RequestActionsSection = ({ request }: Props) => {
if (hasAlreadyActed) {
return (
- <div className="flex w-full flex-col gap-3 rounded-lg border border-mineshaft-600 bg-mineshaft-900 px-4 py-3">
- <p className="text-sm text-mineshaft-300">
- You have already provided your approval for this request.
- </p>
- </div>
+ <Card>
+ <CardContent>
+ <p className="text-sm text-muted">
+ You have already provided your approval for this request.
+ </p>
+ </CardContent>
+ </Card>
);
}
@@ -106,105 +120,124 @@ export const RequestActionsSection = ({ request }: Props) => {
return (
<>
- <div className="flex w-full flex-col gap-3 rounded-lg border border-mineshaft-600 bg-mineshaft-900 px-4 py-4">
- <div className="flex items-center gap-2">
- <TriangleAlertIcon />
- <h3 className="font-medium text-mineshaft-100">Action Required</h3>
- </div>
- <p className="text-sm text-mineshaft-300">
- You are an approver for this request. Please review the details carefully before making
- your decision.
- </p>
- <div className="flex flex-col gap-2">
- <Button
- colorSchema="primary"
- leftIcon={<FontAwesomeIcon icon={faCheck} />}
- onClick={() => handlePopUpOpen("approveModal")}
- isDisabled={isRejecting}
- className="w-full"
- >
- Approve Request
- </Button>
- <Button
- colorSchema="danger"
- variant="outline_bg"
- leftIcon={<FontAwesomeIcon icon={faXmark} />}
- onClick={() => handlePopUpOpen("rejectModal")}
- isDisabled={isApproving}
- className="w-full"
- >
- Reject Request
- </Button>
- </div>
- </div>
-
- <Modal
- isOpen={popUp.approveModal.isOpen}
+ <Card>
+ <CardContent className="flex flex-col gap-3">
+ <div className="flex items-center gap-2">
+ <TriangleAlertIcon className="size-4 text-warning" />
+ <h3 className="font-medium text-foreground">Action Required</h3>
+ </div>
+ <p className="text-sm text-muted">
+ You are an approver for this request. Please review the details carefully before making
+ your decision.
+ </p>
+ <div className="flex flex-col gap-2">
+ <Button
+ variant="project"
+ onClick={() => handlePopUpOpen("approveModal")}
+ isDisabled={isRejecting}
+ className="w-full"
+ >
+ <CheckIcon className="mr-1.5 size-4" />
+ Approve Request
+ </Button>
+ <Button
+ variant="danger"
+ onClick={() => handlePopUpOpen("rejectModal")}
+ isDisabled={isApproving}
+ className="w-full"
+ >
+ <XIcon className="mr-1.5 size-4" />
+ Reject Request
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+
+ <Dialog
+ open={popUp.approveModal.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("approveModal", isOpen)}
>
- <ModalContent title="Approve Request">
- <FormLabel label="Comment (optional)" />
- <TextArea
- value={comment}
- onChange={(e) => setComment(e.target.value)}
- placeholder="Add a comment about your approval..."
- rows={3}
- reSize="vertical"
- className="mb-4"
- />
- <div className="flex gap-3">
+ <DialogContent className="max-w-lg">
+ <DialogHeader>
+ <DialogTitle>Approve request</DialogTitle>
+ <DialogDescription>
+ The requester gets the access described on this request as soon as you approve.
+ </DialogDescription>
+ </DialogHeader>
+ <Field>
+ <FieldLabel>Comment (optional)</FieldLabel>
+ <FieldContent>
+ <TextArea
+ value={comment}
+ onChange={(e) => setComment(e.target.value)}
+ placeholder="Add a comment about your approval..."
+ rows={3}
+ className="resize-y"
+ />
+ </FieldContent>
+ </Field>
+ <DialogFooter>
<Button
- colorSchema="primary"
- onClick={handleApprove}
- isLoading={isApproving}
+ variant="outline"
+ onClick={() => handlePopUpToggle("approveModal", false)}
className="flex-1"
>
- Confirm Approval
+ Cancel
</Button>
<Button
- variant="outline_bg"
- onClick={() => handlePopUpToggle("approveModal", false)}
+ variant="project"
+ onClick={handleApprove}
+ isPending={isApproving}
className="flex-1"
>
- Cancel
+ Confirm approval
</Button>
- </div>
- </ModalContent>
- </Modal>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
- <Modal
- isOpen={popUp.rejectModal.isOpen}
+ <Dialog
+ open={popUp.rejectModal.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("rejectModal", isOpen)}
>
- <ModalContent title="Reject Request">
- <FormLabel label="Reason for rejection (optional)" />
- <TextArea
- value={comment}
- onChange={(e) => setComment(e.target.value)}
- placeholder="Explain why you're rejecting this request..."
- rows={3}
- reSize="vertical"
- className="mb-4"
- />
- <div className="flex gap-3">
+ <DialogContent className="max-w-lg">
+ <DialogHeader>
+ <DialogTitle>Reject request</DialogTitle>
+ <DialogDescription>
+ The request is closed and the requester gets no access. They can open a new one.
+ </DialogDescription>
+ </DialogHeader>
+ <Field>
+ <FieldLabel>Reason for rejection (optional)</FieldLabel>
+ <FieldContent>
+ <TextArea
+ value={comment}
+ onChange={(e) => setComment(e.target.value)}
+ placeholder="Explain why you're rejecting this request..."
+ rows={3}
+ className="resize-y"
+ />
+ </FieldContent>
+ </Field>
+ <DialogFooter>
<Button
- colorSchema="danger"
- onClick={handleReject}
- isLoading={isRejecting}
+ variant="outline"
+ onClick={() => handlePopUpToggle("rejectModal", false)}
className="flex-1"
>
- Confirm Rejection
+ Cancel
</Button>
<Button
- variant="outline_bg"
- onClick={() => handlePopUpToggle("rejectModal", false)}
+ variant="danger"
+ onClick={handleReject}
+ isPending={isRejecting}
className="flex-1"
>
- Cancel
+ Confirm rejection
</Button>
- </div>
- </ModalContent>
- </Modal>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
</>
);
};
diff --git a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/ApprovalPolicyStep.tsx b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/ApprovalPolicyStep.tsx
index 8f098dd5e4..dc1608f877 100644
--- a/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/ApprovalPolicyStep.tsx
+++ b/frontend/src/pages/cert-manager/CodeSigningPage/components/CreateSignerWizard/ApprovalPolicyStep.tsx
@@ -234,8 +234,8 @@ export const ApprovalPolicyStep = ({
<div className="min-w-0">
<div className="text-sm font-medium text-mineshaft-100">Signing window</div>
<p className="text-xs text-mineshaft-400">
- The longest signing window a request can ask for. The window runs from the time the
- request is opened.
+ The longest signing window a request can ask for. The window runs from the moment
+ the request is approved.
</p>
</div>
</div>
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/LimitsStep.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/LimitsStep.tsx
index 513d4b928b..6ede1f27ec 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/LimitsStep.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/EditSignerPolicyModal/LimitsStep.tsx
@@ -78,8 +78,8 @@ export const LimitsStep = ({
</SelectContent>
</Select>
<FieldDescription>
- The longest signing window a request can ask for. The window runs from the time the
- request is opened.
+ The longest signing window a request can ask for. The window runs from the moment the
+ request is approved.
</FieldDescription>
{showError && (
<FieldError
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/PreApproveSigningSheet.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/PreApproveSigningSheet.tsx
index 7d33ceb6f7..65bd44bafc 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/PreApproveSigningSheet.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/PreApproveSigningSheet.tsx
@@ -22,7 +22,6 @@ import {
SheetTitle,
TextArea
} from "@app/components/v3";
-import { parseDurationMs, toDateTimeLocalInputValue } from "@app/helpers/datetime";
import {
SignerMemberRole,
TEffectiveSignerMember,
@@ -37,6 +36,8 @@ import {
} from "@app/pages/cert-manager/components/ScopeFieldsFormSection";
import { PkiDocsUrls } from "@app/pages/cert-manager/pki-docs-urls";
+import { getDefaultSigningWindow, SigningWindowField } from "../../components/SigningWindowField";
+
type Props = {
isOpen: boolean;
onOpenChange: (open: boolean) => void;
@@ -58,20 +59,17 @@ const schema = z
.union([z.number().int("Must be a whole number").min(1, "Must be at least 1"), z.null()])
.optional()
),
- requestedWindowStart: z.string().optional(),
- requestedWindowEnd: z.string().optional(),
+ requestedWindowDuration: z.string().optional(),
justification: z.string().trim().min(1, "Reason is required").max(2048),
scope: SigningScopeSchema
})
- .refine((d) => d.requestedSignings || d.requestedWindowEnd, {
- message: "Provide a signature count or a window end",
+ .refine((d) => d.requestedSignings || d.requestedWindowDuration, {
+ message: "Provide a signature count or an approval duration",
path: ["requestedSignings"]
});
type FormData = z.infer<typeof schema>;
-const DEFAULT_SIGNING_WINDOW_MS = 24 * 60 * 60 * 1000;
-
export const PreApproveSigningSheet = ({ isOpen, onOpenChange, signerId }: Props) => {
const users = useListEffectiveSignerMembers({ signerId, kind: "user" });
const identities = useListEffectiveSignerMembers({ signerId, kind: "identity" });
@@ -104,18 +102,13 @@ export const PreApproveSigningSheet = ({ isOpen, onOpenChange, signerId }: Props
return opts;
}, [users.data, identities.data]);
- const buildDefaults = (): FormData => {
- const now = Date.now();
- const allowedMs = parseDurationMs(maxWindowDuration);
- return {
- granteeKey: "",
- requestedSignings: maxSignings ?? null,
- requestedWindowStart: toDateTimeLocalInputValue(now),
- requestedWindowEnd: toDateTimeLocalInputValue(now + (allowedMs ?? DEFAULT_SIGNING_WINDOW_MS)),
- justification: "",
- scope: []
- };
- };
+ const buildDefaults = (): FormData => ({
+ granteeKey: "",
+ requestedSignings: maxSignings ?? null,
+ requestedWindowDuration: getDefaultSigningWindow(maxWindowDuration),
+ justification: "",
+ scope: []
+ });
const { control, handleSubmit, reset } = useForm<FormData>({
resolver: zodResolver(schema),
@@ -142,12 +135,7 @@ export const PreApproveSigningSheet = ({ isOpen, onOpenChange, signerId }: Props
granteeIdentityId: kind === "identity" ? id : undefined,
justification: data.justification,
requestedSignings: data.requestedSignings ?? undefined,
- requestedWindowStart: data.requestedWindowStart
- ? new Date(data.requestedWindowStart).toISOString()
- : undefined,
- requestedWindowEnd: data.requestedWindowEnd
- ? new Date(data.requestedWindowEnd).toISOString()
- : undefined,
+ requestedWindowDuration: data.requestedWindowDuration,
scope: pickDeclaredScope(data.scope)
});
handleClose(false);
@@ -241,46 +229,11 @@ export const PreApproveSigningSheet = ({ isOpen, onOpenChange, signerId }: Props
)}
/>
- <div className="grid grid-cols-2 gap-3">
- <Controller
- name="requestedWindowStart"
- control={control}
- render={({ field, fieldState: { error } }) => (
- <Field>
- <FieldLabel>Starts</FieldLabel>
- <FieldContent>
- <Input
- type="datetime-local"
- value={field.value ?? ""}
- onChange={(e) => field.onChange(e.target.value || undefined)}
- isError={Boolean(error)}
- />
- <FieldDescription>When access begins.</FieldDescription>
- <FieldError errors={[error]} />
- </FieldContent>
- </Field>
- )}
- />
- <Controller
- name="requestedWindowEnd"
- control={control}
- render={({ field, fieldState: { error } }) => (
- <Field>
- <FieldLabel>Ends</FieldLabel>
- <FieldContent>
- <Input
- type="datetime-local"
- value={field.value ?? ""}
- onChange={(e) => field.onChange(e.target.value || undefined)}
- isError={Boolean(error)}
- />
- <FieldDescription>When access expires.</FieldDescription>
- <FieldError errors={[error]} />
- </FieldContent>
- </Field>
- )}
- />
- </div>
+ <SigningWindowField
+ control={control}
+ name="requestedWindowDuration"
+ maxWindowDuration={maxWindowDuration}
+ />
<ScopeFieldsFormSection control={control} />
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/RequestToSignSheet.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/RequestToSignSheet.tsx
index 88773a70d8..eccc6c6da4 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/RequestToSignSheet.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/RequestToSignSheet.tsx
@@ -21,7 +21,6 @@ import {
SheetTitle,
TextArea
} from "@app/components/v3";
-import { parseDurationMs, toDateTimeLocalInputValue } from "@app/helpers/datetime";
import { useGetSignerPolicy, useRequestToSign } from "@app/hooks/api/signers";
import {
pickDeclaredScope,
@@ -30,6 +29,8 @@ import {
} from "@app/pages/cert-manager/components/ScopeFieldsFormSection";
import { PkiDocsUrls } from "@app/pages/cert-manager/pki-docs-urls";
+import { getDefaultSigningWindow, SigningWindowField } from "../../components/SigningWindowField";
+
type Props = {
isOpen: boolean;
onOpenChange: (open: boolean) => void;
@@ -48,20 +49,17 @@ const schema = z
.union([z.number().int("Must be a whole number").min(1, "Must be at least 1"), z.null()])
.optional()
),
- requestedWindowStart: z.string().optional(),
- requestedWindowEnd: z.string().optional(),
+ requestedWindowDuration: z.string().optional(),
justification: z.string().trim().min(1, "Reason is required").max(2048),
scope: SigningScopeSchema
})
- .refine((d) => d.requestedSignings || d.requestedWindowEnd, {
- message: "Provide a signature count or a window end",
+ .refine((d) => d.requestedSignings || d.requestedWindowDuration, {
+ message: "Provide a signature count or an approval duration",
path: ["requestedSignings"]
});
type FormData = z.infer<typeof schema>;
-const DEFAULT_SIGNING_WINDOW_MS = 24 * 60 * 60 * 1000;
-
export const RequestToSignSheet = ({ isOpen, onOpenChange, signerId }: Props) => {
const requestToSign = useRequestToSign();
const { data: policy } = useGetSignerPolicy(signerId);
@@ -70,17 +68,12 @@ export const RequestToSignSheet = ({ isOpen, onOpenChange, signerId }: Props) =>
const maxSignings = policy?.constraints?.maxSignings ?? null;
const maxWindowDuration = policy?.constraints?.maxWindowDuration ?? null;
- const buildDefaults = (): FormData => {
- const now = Date.now();
- const allowedMs = parseDurationMs(maxWindowDuration);
- return {
- requestedSignings: maxSignings ?? null,
- requestedWindowStart: toDateTimeLocalInputValue(now),
- requestedWindowEnd: toDateTimeLocalInputValue(now + (allowedMs ?? DEFAULT_SIGNING_WINDOW_MS)),
- justification: "",
- scope: []
- };
- };
+ const buildDefaults = (): FormData => ({
+ requestedSignings: maxSignings ?? null,
+ requestedWindowDuration: getDefaultSigningWindow(maxWindowDuration),
+ justification: "",
+ scope: []
+ });
const { control, handleSubmit, reset } = useForm<FormData>({
resolver: zodResolver(schema),
@@ -104,12 +97,7 @@ export const RequestToSignSheet = ({ isOpen, onOpenChange, signerId }: Props) =>
signerId,
justification: data.justification,
requestedSignings: data.requestedSignings ?? undefined,
- requestedWindowStart: data.requestedWindowStart
- ? new Date(data.requestedWindowStart).toISOString()
- : undefined,
- requestedWindowEnd: data.requestedWindowEnd
- ? new Date(data.requestedWindowEnd).toISOString()
- : undefined,
+ requestedWindowDuration: data.requestedWindowDuration,
scope: pickDeclaredScope(data.scope)
});
handleClose(false);
@@ -178,46 +166,11 @@ export const RequestToSignSheet = ({ isOpen, onOpenChange, signerId }: Props) =>
)}
/>
- <div className="grid grid-cols-2 gap-3">
- <Controller
- name="requestedWindowStart"
- control={control}
- render={({ field, fieldState: { error } }) => (
- <Field>
- <FieldLabel>Starts</FieldLabel>
- <FieldContent>
- <Input
- type="datetime-local"
- value={field.value ?? ""}
- onChange={(e) => field.onChange(e.target.value || undefined)}
- isError={Boolean(error)}
- />
- <FieldDescription>When access starts.</FieldDescription>
- <FieldError errors={[error]} />
- </FieldContent>
- </Field>
- )}
- />
- <Controller
- name="requestedWindowEnd"
- control={control}
- render={({ field, fieldState: { error } }) => (
- <Field>
- <FieldLabel>Ends</FieldLabel>
- <FieldContent>
- <Input
- type="datetime-local"
- value={field.value ?? ""}
- onChange={(e) => field.onChange(e.target.value || undefined)}
- isError={Boolean(error)}
- />
- <FieldDescription>When access ends.</FieldDescription>
- <FieldError errors={[error]} />
- </FieldContent>
- </Field>
- )}
- />
- </div>
+ <SigningWindowField
+ control={control}
+ name="requestedWindowDuration"
+ maxWindowDuration={maxWindowDuration}
+ />
<ScopeFieldsFormSection control={control} />
@@ -254,8 +207,8 @@ export const RequestToSignSheet = ({ isOpen, onOpenChange, signerId }: Props) =>
<p className="mt-2 text-sm leading-relaxed text-muted">
Your request goes to this signer&apos;s approvers, and you cannot sign until one
of them approves it. On approval it becomes an access record with the signatures
- and window you asked for. The window is measured from when you send the request,
- not from when it is approved, so allow for review time.
+ and window you asked for. The window starts on approval, so waiting for a review
+ does not eat into it.
</p>
</div>
</aside>
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerApprovalPolicyTab.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerApprovalPolicyTab.tsx
index 672590e30d..40bede52c8 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerApprovalPolicyTab.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SignerApprovalPolicyTab.tsx
@@ -214,7 +214,7 @@ export const SignerApprovalPolicyTab = ({ signerId }: Props) => {
</TooltipTrigger>
<TooltipContent className="max-w-xs">
The longest signing window a request can ask for. The window runs from the
- time the request is opened.
+ moment the request is approved.
</TooltipContent>
</Tooltip>
<p className="mt-0.5 text-xs text-foreground">
diff --git a/frontend/src/pages/cert-manager/SignerDetailPage/components/SigningOperationsTable.tsx b/frontend/src/pages/cert-manager/SignerDetailPage/components/SigningOperationsTable.tsx
index e61c6902af..b2ccc43844 100644
--- a/frontend/src/pages/cert-manager/SignerDetailPage/components/SigningOperationsTable.tsx
+++ b/frontend/src/pages/cert-manager/SignerDetailPage/components/SigningOperationsTable.tsx
@@ -138,7 +138,7 @@ export const SigningOperationsTable = ({ signer, signerId, projectId }: Props) =
<TableHead>Timestamp</TableHead>
<TableHead>Status</TableHead>
<TableHead>Algorithm</TableHead>
- <TableHead>Data Hash</TableHead>
+ <TableHead>Data Digest</TableHead>
<TableHead>Actor</TableHead>
</TableRow>
</TableHeader>
diff --git a/frontend/src/pages/cert-manager/SigningOperationDetailPage/SigningOperationDetailPage.tsx b/frontend/src/pages/cert-manager/SigningOperationDetailPage/SigningOperationDetailPage.tsx
index 595de938e3..7c6d225748 100644
--- a/frontend/src/pages/cert-manager/SigningOperationDetailPage/SigningOperationDetailPage.tsx
+++ b/frontend/src/pages/cert-manager/SigningOperationDetailPage/SigningOperationDetailPage.tsx
@@ -117,7 +117,7 @@ export const SigningOperationDetailPage = () => {
</Detail>
</div>
<Detail>
- <DetailLabel>Data Digest (SHA-256)</DetailLabel>
+ <DetailLabel>Data Digest</DetailLabel>
<MonoValue value={operation.dataHash} />
</Detail>
{operation.errorMessage && (
@@ -163,12 +163,6 @@ export const SigningOperationDetailPage = () => {
<DetailValue>{metadata.sourceIp}</DetailValue>
</Detail>
)}
- {metadata.reportedIp && (
- <Detail>
- <DetailLabel>Reported IP</DetailLabel>
- <DetailValue>{metadata.reportedIp}</DetailValue>
- </Detail>
- )}
</div>
{metadata.signingApplicationHash && (
<Detail>
diff --git a/frontend/src/pages/cert-manager/components/ScopeFieldsFormSection.tsx b/frontend/src/pages/cert-manager/components/ScopeFieldsFormSection.tsx
index 459254c11f..5ba636e376 100644
--- a/frontend/src/pages/cert-manager/components/ScopeFieldsFormSection.tsx
+++ b/frontend/src/pages/cert-manager/components/ScopeFieldsFormSection.tsx
@@ -40,7 +40,7 @@ import {
TCodeSigningScope
} from "@app/hooks/api/signers";
-const MAX_COMMAND_LENGTH = 2048;
+const MAX_COMMAND_LENGTH = 32767;
const MAX_SCOPE_TEXT_LENGTH = 256;
const SHA256_HEX = /^[a-fA-F0-9]{64}$/;
diff --git a/frontend/src/pages/cert-manager/components/SigningWindowField.tsx b/frontend/src/pages/cert-manager/components/SigningWindowField.tsx
new file mode 100644
index 0000000000..09096c9dc6
--- /dev/null
+++ b/frontend/src/pages/cert-manager/components/SigningWindowField.tsx
@@ -0,0 +1,89 @@
+import { Control, Controller, FieldValues, Path } from "react-hook-form";
+
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldLabel,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import { parseDurationMs } from "@app/helpers/datetime";
+
+const DURATION_PRESETS = [
+ { value: "15m", label: "15 minutes" },
+ { value: "1h", label: "1 hour" },
+ { value: "4h", label: "4 hours" },
+ { value: "8h", label: "8 hours" },
+ { value: "1d", label: "1 day" },
+ { value: "3d", label: "3 days" },
+ { value: "7d", label: "1 week" }
+];
+
+const DEFAULT_UNCAPPED_WINDOW = "1d";
+
+const getSigningWindowOptions = (maxWindowDuration?: string | null) => {
+ const maxMs = parseDurationMs(maxWindowDuration);
+ if (maxMs === null || !maxWindowDuration) return DURATION_PRESETS;
+
+ const withinPolicy = DURATION_PRESETS.filter((option) => {
+ const optionMs = parseDurationMs(option.value);
+ return optionMs !== null && optionMs <= maxMs;
+ });
+
+ if (withinPolicy.some((option) => parseDurationMs(option.value) === maxMs)) return withinPolicy;
+ return [...withinPolicy, { value: maxWindowDuration, label: maxWindowDuration }];
+};
+
+export const getDefaultSigningWindow = (maxWindowDuration?: string | null) =>
+ maxWindowDuration && parseDurationMs(maxWindowDuration) !== null
+ ? maxWindowDuration
+ : DEFAULT_UNCAPPED_WINDOW;
+
+type Props<T extends FieldValues> = {
+ control: Control<T>;
+ name: Path<T>;
+ maxWindowDuration?: string | null;
+};
+
+export const SigningWindowField = <T extends FieldValues>({
+ control,
+ name,
+ maxWindowDuration
+}: Props<T>) => {
+ const options = getSigningWindowOptions(maxWindowDuration);
+
+ return (
+ <Controller
+ control={control}
+ name={name}
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>How long the approval lasts</FieldLabel>
+ <FieldContent>
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldDescription>
+ {maxWindowDuration
+ ? `Counts down from when the access is granted. Policy caps it at ${maxWindowDuration}.`
+ : "Counts down from when the access is granted."}
+ </FieldDescription>
+ </FieldContent>
+ </Field>
+ )}
+ />
+ );
+};