mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-10-06 09:26:47 +00:00
Switch access token tracking to be persistent, add num uses, draft token renewal, update docs
This commit is contained in:
@@ -27,8 +27,9 @@ declare module "jsonwebtoken" {
|
||||
}
|
||||
export interface MachineAccessTokenJwtPayload extends jwt.JwtPayload {
|
||||
_id: string;
|
||||
clientSecretId: string;
|
||||
machineAccessTokenId: string;
|
||||
authTokenType: string;
|
||||
tokenVersion: number;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import jwt from "jsonwebtoken";
|
||||
import bcrypt from "bcrypt";
|
||||
import crypto from "crypto";
|
||||
import { Request, Response } from "express";
|
||||
@@ -6,6 +7,7 @@ import {
|
||||
IMachineIdentity,
|
||||
IMachineIdentityClientSecret,
|
||||
IMachineIdentityTrustedIp,
|
||||
IdentityAccessToken,
|
||||
MachineIdentity,
|
||||
MachineIdentityClientSecret,
|
||||
MachineMembership,
|
||||
@@ -47,12 +49,14 @@ import { getUserAgentType } from "../../../utils/posthog";
|
||||
const packageClientSecretData = (machineIdentityClientSecret: IMachineIdentityClientSecret) => ({
|
||||
_id: machineIdentityClientSecret._id,
|
||||
machineIdentity: machineIdentityClientSecret.machineIdentity,
|
||||
isActive: machineIdentityClientSecret.isActive,
|
||||
isClientSecretRevoked: machineIdentityClientSecret.isClientSecretRevoked,
|
||||
description: machineIdentityClientSecret.description,
|
||||
clientSecretPrefix: machineIdentityClientSecret.clientSecretPrefix,
|
||||
clientSecretNumUses: machineIdentityClientSecret.clientSecretNumUses,
|
||||
clientSecretNumUsesLimit: machineIdentityClientSecret.clientSecretNumUsesLimit,
|
||||
clientSecretTTL: machineIdentityClientSecret.clientSecretTTL
|
||||
clientSecretTTL: machineIdentityClientSecret.clientSecretTTL,
|
||||
createdAt: machineIdentityClientSecret.createdAt,
|
||||
updatedAt: machineIdentityClientSecret.updatedAt
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -65,7 +69,7 @@ export const getMIClientSecrets = async (req: Request, res: Response) => {
|
||||
params: {
|
||||
machineId
|
||||
}
|
||||
} = await validateRequest(reqValidator.GetClientSecretsV3, req);
|
||||
} = await validateRequest(reqValidator.GetClientSecretsV1, req);
|
||||
|
||||
const machineMembershipOrg = await MachineMembershipOrg.findOne({
|
||||
machineIdentity: new Types.ObjectId(machineId)
|
||||
@@ -97,8 +101,7 @@ export const getMIClientSecrets = async (req: Request, res: Response) => {
|
||||
|
||||
const clientSecretData = await MachineIdentityClientSecret
|
||||
.find({
|
||||
machineIdentity: machineMembershipOrg.machineIdentity,
|
||||
isActive: true
|
||||
machineIdentity: machineMembershipOrg.machineIdentity
|
||||
})
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(5);
|
||||
@@ -108,8 +111,7 @@ export const getMIClientSecrets = async (req: Request, res: Response) => {
|
||||
{
|
||||
type: EventType.GET_MACHINE_IDENTITY_CLIENT_SECRETS,
|
||||
metadata: {
|
||||
machineId: machineMembershipOrg.machineIdentity._id.toString(),
|
||||
clientId: machineMembershipOrg.machineIdentity.clientId,
|
||||
machineId: machineMembershipOrg.machineIdentity._id.toString()
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -137,7 +139,7 @@ export const createMIClientSecret = async (req: Request, res: Response) => {
|
||||
ttl,
|
||||
numUsesLimit
|
||||
}
|
||||
} = await validateRequest(reqValidator.CreateClientSecretV3, req);
|
||||
} = await validateRequest(reqValidator.CreateClientSecretV1, req);
|
||||
|
||||
const machineMembershipOrg = await MachineMembershipOrg.findOne({
|
||||
machineIdentity: new Types.ObjectId(machineId)
|
||||
@@ -173,14 +175,13 @@ export const createMIClientSecret = async (req: Request, res: Response) => {
|
||||
|
||||
const machineIdentityClientSecret = await new MachineIdentityClientSecret({
|
||||
machineIdentity: machineMembershipOrg.machineIdentity,
|
||||
isActive: true,
|
||||
description,
|
||||
clientSecretPrefix: clientSecret.slice(0, 4),
|
||||
clientSecretHash,
|
||||
clientSecretNumUses: 0,
|
||||
clientSecretNumUsesLimit: numUsesLimit,
|
||||
clientSecretTTL: ttl,
|
||||
accessTokenVersion: 1,
|
||||
isClientSecretRevoked: false
|
||||
}).save();
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
@@ -189,7 +190,6 @@ export const createMIClientSecret = async (req: Request, res: Response) => {
|
||||
type: EventType.CREATE_MACHINE_IDENTITY_CLIENT_SECRET,
|
||||
metadata: {
|
||||
machineId: machineMembershipOrg.machineIdentity._id.toString(),
|
||||
clientId: machineMembershipOrg.machineIdentity.clientId,
|
||||
clientSecretId: machineIdentityClientSecret._id.toString()
|
||||
}
|
||||
},
|
||||
@@ -215,7 +215,7 @@ export const deleteMIClientSecret = async (req: Request, res: Response) => {
|
||||
machineId,
|
||||
clientSecretId
|
||||
}
|
||||
} = await validateRequest(reqValidator.DeleteClientSecretV3, req);
|
||||
} = await validateRequest(reqValidator.DeleteClientSecretV1, req);
|
||||
|
||||
const machineMembershipOrg = await MachineMembershipOrg
|
||||
.findOne({
|
||||
@@ -250,20 +250,27 @@ export const deleteMIClientSecret = async (req: Request, res: Response) => {
|
||||
message: "Failed to delete client secrets for more privileged MI"
|
||||
});
|
||||
|
||||
const machineIdentityClientSecret = await MachineIdentityClientSecret.findOneAndDelete({
|
||||
_id: clientSecretId,
|
||||
machineIdentity: machineId
|
||||
});
|
||||
const machineIdentityClientSecret = await MachineIdentityClientSecret.findOneAndUpdate(
|
||||
{
|
||||
_id: clientSecretId,
|
||||
machineIdentity: machineId
|
||||
},
|
||||
{
|
||||
isClientSecretRevoked: true
|
||||
},
|
||||
{
|
||||
new: true
|
||||
}
|
||||
);
|
||||
|
||||
if (!machineIdentityClientSecret) throw ResourceNotFoundError();
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
req.authData,
|
||||
{
|
||||
type: EventType.DELETE_MACHINE_IDENTITY_CLIENT_SECRET,
|
||||
type: EventType.REVOKE_MACHINE_IDENTITY_CLIENT_SECRET,
|
||||
metadata: {
|
||||
machineId: machineMembershipOrg.machineIdentity._id.toString(),
|
||||
clientId: machineMembershipOrg.machineIdentity.clientId,
|
||||
clientSecretId: clientSecretId
|
||||
}
|
||||
},
|
||||
@@ -289,11 +296,10 @@ export const loginMI = async (req: Request, res: Response) => {
|
||||
clientId,
|
||||
clientSecret
|
||||
}
|
||||
} = await validateRequest(reqValidator.LoginMachineIdentityV3, req);
|
||||
} = await validateRequest(reqValidator.LoginMachineIdentityV1, req);
|
||||
|
||||
const machineIdentity = await MachineIdentity.findOne({
|
||||
clientId,
|
||||
isActive: true
|
||||
clientId
|
||||
});
|
||||
|
||||
if (!machineIdentity) throw UnauthorizedRequestError();
|
||||
@@ -305,7 +311,7 @@ export const loginMI = async (req: Request, res: Response) => {
|
||||
|
||||
const clientSecretData = await MachineIdentityClientSecret.find({
|
||||
machineIdentity: machineIdentity._id,
|
||||
isActive: true
|
||||
isClientSecretRevoked: false
|
||||
});
|
||||
|
||||
let validatedClientSecretDatum: IMachineIdentityClientSecret | undefined;
|
||||
@@ -340,7 +346,7 @@ export const loginMI = async (req: Request, res: Response) => {
|
||||
await MachineIdentityClientSecret.findByIdAndUpdate(
|
||||
validatedClientSecretDatum._id,
|
||||
{
|
||||
isActive: false
|
||||
isClientSecretRevoked: true
|
||||
}
|
||||
);
|
||||
|
||||
@@ -350,13 +356,13 @@ export const loginMI = async (req: Request, res: Response) => {
|
||||
}
|
||||
}
|
||||
|
||||
if (clientSecretNumUses > 0 && clientSecretNumUses === clientSecretNumUsesLimit) {
|
||||
if (clientSecretNumUsesLimit > 0 && clientSecretNumUses === clientSecretNumUsesLimit) {
|
||||
// number of times client secret can be used for
|
||||
// a login operation reached
|
||||
await MachineIdentityClientSecret.findByIdAndUpdate(
|
||||
validatedClientSecretDatum._id,
|
||||
{
|
||||
isActive: false
|
||||
isClientSecretRevoked: true
|
||||
},
|
||||
{
|
||||
new: true
|
||||
@@ -372,20 +378,31 @@ export const loginMI = async (req: Request, res: Response) => {
|
||||
await MachineIdentityClientSecret.findByIdAndUpdate(
|
||||
validatedClientSecretDatum._id,
|
||||
{
|
||||
clientSecretLastUsedAt: new Date(),
|
||||
$inc: { clientSecretNumUses: 1 }
|
||||
},
|
||||
{
|
||||
new: true
|
||||
}
|
||||
);
|
||||
|
||||
const identityAccessToken = await new IdentityAccessToken({
|
||||
machineIdentity: machineIdentity._id,
|
||||
machineIdentityClientSecret: validatedClientSecretDatum._id,
|
||||
accessTokenNumUses: 0,
|
||||
accessTokenNumUsesLimit: machineIdentity.accessTokenNumUsesLimit,
|
||||
accessTokenTTL: machineIdentity.accessTokenTTL,
|
||||
accessTokenMaxTTL: machineIdentity.accessTokenMaxTTL,
|
||||
isAccessTokenRevoked: false
|
||||
}).save();
|
||||
|
||||
// token version
|
||||
const accessToken = createToken({
|
||||
payload: {
|
||||
machineId: machineIdentity._id.toString(),
|
||||
clientSecretDataId: validatedClientSecretDatum._id.toString(),
|
||||
authTokenType: AuthTokenType.MACHINE_ACCESS_TOKEN,
|
||||
tokenVersion: validatedClientSecretDatum.accessTokenVersion
|
||||
clientSecretId: validatedClientSecretDatum._id.toString(),
|
||||
identityAccessTokenId: identityAccessToken._id.toString(),
|
||||
authTokenType: AuthTokenType.MACHINE_ACCESS_TOKEN
|
||||
},
|
||||
expiresIn: machineIdentity.accessTokenTTL,
|
||||
secret: await getAuthSecret()
|
||||
@@ -411,8 +428,9 @@ export const loginMI = async (req: Request, res: Response) => {
|
||||
type: EventType.LOGIN_MACHINE_IDENTITY,
|
||||
metadata: {
|
||||
machineId: machineIdentity._id.toString(),
|
||||
clientId,
|
||||
clientSecretId: validatedClientSecretDatum._id.toString()
|
||||
machineAccessTokenId: identityAccessToken._id.toString(),
|
||||
clientSecretId: validatedClientSecretDatum._id.toString(),
|
||||
identityAccessTokenId: identityAccessToken._id.toString()
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -427,6 +445,79 @@ export const loginMI = async (req: Request, res: Response) => {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Renews an access token by its TTL
|
||||
* @param req
|
||||
* @param res
|
||||
*/
|
||||
export const renewAccessToken = async (req: Request, res: Response) => {
|
||||
const {
|
||||
body: {
|
||||
accessToken
|
||||
}
|
||||
} = await validateRequest(reqValidator.RenewAccessTokenV1, req);
|
||||
|
||||
const decodedToken = <jwt.MachineAccessTokenJwtPayload>(
|
||||
jwt.verify(accessToken, await getAuthSecret())
|
||||
);
|
||||
|
||||
if (decodedToken.authTokenType !== AuthTokenType.MACHINE_ACCESS_TOKEN) throw UnauthorizedRequestError();
|
||||
|
||||
const machineIdentityAccessToken = await IdentityAccessToken.findOne({
|
||||
_id: decodedToken.identityAccessTokenId,
|
||||
isAccessTokenRevoked: false
|
||||
});
|
||||
|
||||
if (!machineIdentityAccessToken) throw UnauthorizedRequestError();
|
||||
|
||||
const {
|
||||
accessTokenTTL,
|
||||
accessTokenLastRenewedAt,
|
||||
accessTokenMaxTTL,
|
||||
createdAt: accessTokenCreatedAt
|
||||
} = machineIdentityAccessToken;
|
||||
|
||||
if (accessTokenTTL === accessTokenMaxTTL) throw UnauthorizedRequestError({
|
||||
message: "Failed to renew non-renewable access token"
|
||||
});
|
||||
|
||||
if (accessTokenTTL > 0) {
|
||||
const currentDate = new Date();
|
||||
if (accessTokenLastRenewedAt) {
|
||||
// access token has been renewed
|
||||
const accessTokenRenewed = new Date(accessTokenLastRenewedAt);
|
||||
const ttlInMilliseconds = accessTokenTTL * 1000;
|
||||
const expirationTime = new Date(accessTokenRenewed.getTime() + ttlInMilliseconds);
|
||||
|
||||
if (currentDate > expirationTime) throw UnauthorizedRequestError({
|
||||
message: "Failed to renew MI access token due to TTL expiration"
|
||||
});
|
||||
} else {
|
||||
// access token has never been renewed
|
||||
const accessTokenCreated = new Date(accessTokenCreatedAt);
|
||||
const ttlInMilliseconds = accessTokenTTL * 1000;
|
||||
const expirationTime = new Date(accessTokenCreated.getTime() + ttlInMilliseconds);
|
||||
|
||||
if (currentDate > expirationTime) throw UnauthorizedRequestError({
|
||||
message: "Failed to renew MI access token due to TTL expiration"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await IdentityAccessToken.findByIdAndUpdate(
|
||||
machineIdentityAccessToken._id,
|
||||
{
|
||||
accessTokenLastRenewedAt: new Date()
|
||||
}
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
accessToken,
|
||||
expiresIn: machineIdentityAccessToken.accessTokenTTL,
|
||||
tokenType: "Bearer"
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create machine identity
|
||||
* @param req
|
||||
@@ -442,8 +533,10 @@ export const createMachineIdentity = async (req: Request, res: Response) => {
|
||||
clientSecretTrustedIps,
|
||||
accessTokenTrustedIps,
|
||||
accessTokenTTL,
|
||||
accessTokenMaxTTL,
|
||||
accessTokenNumUsesLimit
|
||||
}
|
||||
} = await validateRequest(reqValidator.CreateMachineIdentityV3, req);
|
||||
} = await validateRequest(reqValidator.CreateMachineIdentityV1, req);
|
||||
|
||||
const { permission } = await getAuthDataOrgPermissions({
|
||||
authData: req.authData,
|
||||
@@ -509,14 +602,14 @@ export const createMachineIdentity = async (req: Request, res: Response) => {
|
||||
return extractIPDetails(accessTokenTrustedIp.ipAddress);
|
||||
});
|
||||
|
||||
const isActive = true;
|
||||
const machineIdentity = await new MachineIdentity({
|
||||
clientId: crypto.randomUUID(),
|
||||
name,
|
||||
organization: new Types.ObjectId(organizationId),
|
||||
isActive,
|
||||
accessTokenTTL,
|
||||
accessTokenUsageCount: 0,
|
||||
accessTokenMaxTTL,
|
||||
accessTokenNumUses: 0,
|
||||
accessTokenNumUsesLimit,
|
||||
clientSecretTrustedIps: reformattedClientSecretTrustedIps,
|
||||
accessTokenTrustedIps: reformattedAccessTokenTrustedIps,
|
||||
}).save();
|
||||
@@ -534,7 +627,6 @@ export const createMachineIdentity = async (req: Request, res: Response) => {
|
||||
type: EventType.CREATE_MACHINE_IDENTITY,
|
||||
metadata: {
|
||||
name,
|
||||
isActive,
|
||||
role,
|
||||
clientSecretTrustedIps: reformattedClientSecretTrustedIps as Array<IMachineIdentityTrustedIp>,
|
||||
accessTokenTrustedIps: reformattedAccessTokenTrustedIps as Array<IMachineIdentityTrustedIp>
|
||||
@@ -564,9 +656,10 @@ export const updateMachineIdentity = async (req: Request, res: Response) => {
|
||||
role,
|
||||
clientSecretTrustedIps,
|
||||
accessTokenTrustedIps,
|
||||
accessTokenTTL
|
||||
accessTokenTTL,
|
||||
accessTokenNumUsesLimit
|
||||
}
|
||||
} = await validateRequest(reqValidator.UpdateMachineIdentityV3, req);
|
||||
} = await validateRequest(reqValidator.UpdateMachineIdentityV1, req);
|
||||
|
||||
const machineMembershipOrg = await MachineMembershipOrg
|
||||
.findOne({
|
||||
@@ -666,7 +759,8 @@ export const updateMachineIdentity = async (req: Request, res: Response) => {
|
||||
name,
|
||||
clientSecretTrustedIps: reformattedClientSecretTrustedIps,
|
||||
accessTokenTrustedIps: reformattedAccessTokenTrustedIps,
|
||||
accessTokenTTL
|
||||
accessTokenTTL,
|
||||
accessTokenNumUsesLimit
|
||||
},
|
||||
{
|
||||
new: true
|
||||
@@ -727,7 +821,7 @@ export const updateMachineIdentity = async (req: Request, res: Response) => {
|
||||
export const deleteMachineIdentity = async (req: Request, res: Response) => {
|
||||
const {
|
||||
params: { machineId }
|
||||
} = await validateRequest(reqValidator.DeleteMachineIdentityV3, req);
|
||||
} = await validateRequest(reqValidator.DeleteMachineIdentityV1, req);
|
||||
|
||||
const machineMembershipOrg = await MachineMembershipOrg
|
||||
.findOne({
|
||||
@@ -775,9 +869,19 @@ export const deleteMachineIdentity = async (req: Request, res: Response) => {
|
||||
machineIdentity: machineMembershipOrg.machineIdentity
|
||||
});
|
||||
|
||||
const machineIdentityClientSecretIds = await MachineIdentityClientSecret.distinct("_id", {
|
||||
machineIdentity: machineMembershipOrg.machineIdentity
|
||||
});
|
||||
|
||||
await MachineIdentityClientSecret.deleteMany({
|
||||
machineIdentity: machineMembershipOrg.machineIdentity
|
||||
});
|
||||
|
||||
await IdentityAccessToken.deleteMany({
|
||||
machineIdentityClientSecret: {
|
||||
$in: machineIdentityClientSecretIds
|
||||
}
|
||||
});
|
||||
|
||||
await EEAuditLogService.createAuditLog(
|
||||
req.authData,
|
||||
@@ -785,7 +889,6 @@ export const deleteMachineIdentity = async (req: Request, res: Response) => {
|
||||
type: EventType.DELETE_MACHINE_IDENTITY,
|
||||
metadata: {
|
||||
name: machineIdentity.name,
|
||||
isActive: machineIdentity.isActive,
|
||||
role: machineMembershipOrg.role,
|
||||
clientSecretTrustedIps: machineIdentity.clientSecretTrustedIps as Array<IMachineIdentityTrustedIp>,
|
||||
accessTokenTrustedIps: machineIdentity.accessTokenTrustedIps as Array<IMachineIdentityTrustedIp>,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
export enum ActorType { // would extend to AWS, Azure, ...
|
||||
USER = "user",
|
||||
USER = "user", // userIdentity
|
||||
SERVICE = "service",
|
||||
MACHINE = "machine"
|
||||
MACHINE = "machine" // machineIdentity
|
||||
}
|
||||
|
||||
export enum UserAgentType {
|
||||
@@ -36,7 +36,7 @@ export enum EventType {
|
||||
DELETE_MACHINE_IDENTITY = "delete-machine-identity",
|
||||
LOGIN_MACHINE_IDENTITY = "login-machine-identity",
|
||||
CREATE_MACHINE_IDENTITY_CLIENT_SECRET = "create-machine-identity-secret",
|
||||
DELETE_MACHINE_IDENTITY_CLIENT_SECRET = "delete-machine-identity-secret",
|
||||
REVOKE_MACHINE_IDENTITY_CLIENT_SECRET = "revoke-machine-identity-secret",
|
||||
GET_MACHINE_IDENTITY_CLIENT_SECRETS = "get-machine-identity-secrets",
|
||||
CREATE_ENVIRONMENT = "create-environment",
|
||||
UPDATE_ENVIRONMENT = "update-environment",
|
||||
|
||||
@@ -225,13 +225,10 @@ interface DeleteServiceTokenEvent {
|
||||
};
|
||||
}
|
||||
|
||||
// TODO: review all logging for MIs including params etc.
|
||||
|
||||
interface CreateMachineIdentityEvent {
|
||||
type: EventType.CREATE_MACHINE_IDENTITY;
|
||||
metadata: {
|
||||
name: string;
|
||||
isActive: boolean;
|
||||
role: string;
|
||||
clientSecretTrustedIps: Array<IMachineIdentityTrustedIp>;
|
||||
accessTokenTrustedIps: Array<IMachineIdentityTrustedIp>;
|
||||
@@ -252,7 +249,6 @@ interface DeleteMachineIdentityEvent {
|
||||
type: EventType.DELETE_MACHINE_IDENTITY;
|
||||
metadata: {
|
||||
name: string;
|
||||
isActive: boolean;
|
||||
role: string;
|
||||
clientSecretTrustedIps: Array<IMachineIdentityTrustedIp>;
|
||||
accessTokenTrustedIps: Array<IMachineIdentityTrustedIp>;
|
||||
@@ -263,8 +259,9 @@ interface LoginMachineIdentityEvent {
|
||||
type: EventType.LOGIN_MACHINE_IDENTITY ;
|
||||
metadata: {
|
||||
machineId: string;
|
||||
clientId: string;
|
||||
machineAccessTokenId: string;
|
||||
clientSecretId: string;
|
||||
identityAccessTokenId: string;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -272,16 +269,14 @@ interface CreateMachineIdentitySecretEvent {
|
||||
type: EventType.CREATE_MACHINE_IDENTITY_CLIENT_SECRET ;
|
||||
metadata: {
|
||||
machineId: string;
|
||||
clientId: string;
|
||||
clientSecretId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface DeleteMachineIdentitySecretEvent {
|
||||
type: EventType.DELETE_MACHINE_IDENTITY_CLIENT_SECRET ;
|
||||
type: EventType.REVOKE_MACHINE_IDENTITY_CLIENT_SECRET ;
|
||||
metadata: {
|
||||
machineId: string;
|
||||
clientId: string;
|
||||
clientSecretId: string;
|
||||
};
|
||||
}
|
||||
@@ -290,7 +285,6 @@ interface GetMachineIdentitySecretsEvent {
|
||||
type: EventType.GET_MACHINE_IDENTITY_CLIENT_SECRETS ;
|
||||
metadata: {
|
||||
machineId: string;
|
||||
clientId: string;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,12 @@ router.post(
|
||||
machineIdentitiesController.loginMI
|
||||
);
|
||||
|
||||
// note: currently this is machine-identity specific
|
||||
router.post(
|
||||
"/access-token/renew",
|
||||
machineIdentitiesController.renewAccessToken
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/",
|
||||
requireAuth({
|
||||
|
||||
+30
-27
@@ -1,33 +1,37 @@
|
||||
import { Document, Schema, Types, model } from "mongoose";
|
||||
import { boolean } from "zod";
|
||||
|
||||
export interface IMachineIdentityAccessToken extends Document {
|
||||
export interface IIdentityAccessToken extends Document {
|
||||
_id: Types.ObjectId;
|
||||
machineIdentityClientSecret: Types.ObjectId;
|
||||
isActive: boolean;
|
||||
accessTokenLastUsed?: Date;
|
||||
machineIdentity?: Types.ObjectId;
|
||||
machineIdentityClientSecret?: Types.ObjectId;
|
||||
accessTokenLastUsedAt?: Date;
|
||||
accessTokenLastRenewedAt?: Date;
|
||||
accessTokenNumUses: number;
|
||||
accessTokenNumUsesLimit: number;
|
||||
accessTokenTTL: number;
|
||||
accessTokenVersion: number;
|
||||
renewable: boolean;
|
||||
accessTokenMaxTTL: number;
|
||||
isAccessTokenRevoked: boolean;
|
||||
updatedAt: Date;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
const machineIdentityAccessTokenSchema = new Schema(
|
||||
const identityAccessTokenSchema = new Schema(
|
||||
{
|
||||
machineIdentity: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "MachineIdentity",
|
||||
required: false
|
||||
},
|
||||
machineIdentityClientSecret: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "MachineIdentityClientSecret",
|
||||
required: true
|
||||
required: false
|
||||
},
|
||||
isActive: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
required: true
|
||||
accessTokenLastUsedAt: {
|
||||
type: Date,
|
||||
required: false
|
||||
},
|
||||
accessTokenLastUsed: {
|
||||
accessTokenLastRenewedAt: {
|
||||
type: Date,
|
||||
required: false
|
||||
},
|
||||
@@ -43,18 +47,21 @@ const machineIdentityAccessTokenSchema = new Schema(
|
||||
default: 0, // default: used as many times as needed
|
||||
required: true
|
||||
},
|
||||
accessTokenTTL: {
|
||||
accessTokenTTL: { // seconds
|
||||
// incremental lifetime
|
||||
type: Number,
|
||||
default: 0, // default: does not expire
|
||||
default: 7200,
|
||||
required: true
|
||||
},
|
||||
renewable: {
|
||||
type: boolean,
|
||||
default: false, // no refresh mechanism yet
|
||||
},
|
||||
accessTokenVersion: {
|
||||
accessTokenMaxTTL: { // seconds
|
||||
// max lifetime
|
||||
type: Number,
|
||||
default: 1,
|
||||
default: 7200,
|
||||
required: true
|
||||
},
|
||||
isAccessTokenRevoked: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
required: true
|
||||
},
|
||||
},
|
||||
@@ -63,8 +70,4 @@ const machineIdentityAccessTokenSchema = new Schema(
|
||||
}
|
||||
);
|
||||
|
||||
machineIdentityAccessTokenSchema.index(
|
||||
{ machineIdentityClientSecret: 1, isActive: 1 }
|
||||
)
|
||||
|
||||
export const MachineIdentityClientSecret = model<IMachineIdentityAccessToken>("MachineIdentityAccessToken", machineIdentityAccessTokenSchema);
|
||||
export const IdentityAccessToken = model<IIdentityAccessToken>("IdentityAccessToken", identityAccessTokenSchema);
|
||||
@@ -22,6 +22,7 @@ export * from "./workspace";
|
||||
export * from "./serviceTokenData"; // TODO: deprecate
|
||||
export * from "./machineIdentity";
|
||||
export * from "./machineIdentityClientSecret";
|
||||
export * from "./identityAccessToken";
|
||||
export * from "./machineMembershipOrg";
|
||||
export * from "./machineMembership";
|
||||
export * from "./apiKeyData"; // TODO: deprecate
|
||||
|
||||
@@ -7,17 +7,14 @@ export interface IMachineIdentityTrustedIp {
|
||||
prefix: number;
|
||||
}
|
||||
|
||||
// TODO: rename to AppClient
|
||||
|
||||
export interface IMachineIdentity extends Document {
|
||||
_id: Types.ObjectId;
|
||||
clientId: string;
|
||||
name: string;
|
||||
organization: Types.ObjectId;
|
||||
isActive: boolean;
|
||||
accessTokenTTL: number;
|
||||
accessTokenLastUsed?: Date;
|
||||
accessTokenUsageCount: number;
|
||||
accessTokenMaxTTL: number;
|
||||
accessTokenNumUsesLimit: number;
|
||||
clientSecretTrustedIps: Array<IMachineIdentityTrustedIp>;
|
||||
accessTokenTrustedIps: Array<IMachineIdentityTrustedIp>;
|
||||
}
|
||||
@@ -37,23 +34,22 @@ const machineIdentitySchema = new Schema(
|
||||
ref: "Organization",
|
||||
required: true
|
||||
},
|
||||
isActive: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
required: true
|
||||
},
|
||||
accessTokenTTL: { // seconds
|
||||
// incremental lifetime
|
||||
type: Number,
|
||||
default: 7200,
|
||||
required: true
|
||||
},
|
||||
accessTokenLastUsed: {
|
||||
type: Date,
|
||||
required: false
|
||||
},
|
||||
accessTokenUsageCount: {
|
||||
accessTokenMaxTTL: { // seconds
|
||||
// max lifetime
|
||||
type: Number,
|
||||
default: 0,
|
||||
default: 7200,
|
||||
required: true
|
||||
},
|
||||
accessTokenNumUsesLimit: {
|
||||
// number of times access token can be used for
|
||||
type: Number,
|
||||
default: 0, // default: used as many times as needed
|
||||
required: true
|
||||
},
|
||||
clientSecretTrustedIps: {
|
||||
@@ -118,6 +114,6 @@ const machineIdentitySchema = new Schema(
|
||||
}
|
||||
);
|
||||
|
||||
machineIdentitySchema.index({ clientId: 1, isActive: 1 })
|
||||
machineIdentitySchema.index({ clientId: 1 })
|
||||
|
||||
export const MachineIdentity = model<IMachineIdentity>("MachineIdentity", machineIdentitySchema);
|
||||
@@ -3,17 +3,16 @@ import { Document, Schema, Types, model } from "mongoose";
|
||||
export interface IMachineIdentityClientSecret extends Document {
|
||||
_id: Types.ObjectId;
|
||||
machineIdentity: Types.ObjectId;
|
||||
isActive: boolean;
|
||||
description: string;
|
||||
clientSecretPrefix: string;
|
||||
clientSecretHash: string;
|
||||
clientSecretLastUsed?: Date;
|
||||
clientSecretLastUsedAt?: Date;
|
||||
clientSecretNumUses: number;
|
||||
clientSecretNumUsesLimit: number;
|
||||
clientSecretTTL: number;
|
||||
accessTokenVersion: number;
|
||||
updatedAt: Date;
|
||||
createdAt: Date;
|
||||
isClientSecretRevoked: boolean;
|
||||
}
|
||||
|
||||
const machineIdentityClientSecretSchema = new Schema(
|
||||
@@ -23,11 +22,6 @@ const machineIdentityClientSecretSchema = new Schema(
|
||||
ref: "MachineIdentity",
|
||||
required: true
|
||||
},
|
||||
isActive: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
required: true
|
||||
},
|
||||
description: {
|
||||
type: String,
|
||||
required: true
|
||||
@@ -40,7 +34,7 @@ const machineIdentityClientSecretSchema = new Schema(
|
||||
type: String,
|
||||
required: true
|
||||
},
|
||||
clientSecretLastUsed: {
|
||||
clientSecretLastUsedAt: {
|
||||
type: Date,
|
||||
required: false
|
||||
},
|
||||
@@ -63,11 +57,11 @@ const machineIdentityClientSecretSchema = new Schema(
|
||||
default: 0, // default: does not expire
|
||||
required: true
|
||||
},
|
||||
accessTokenVersion: {
|
||||
type: Number,
|
||||
default: 1,
|
||||
isClientSecretRevoked: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
required: true
|
||||
},
|
||||
}
|
||||
},
|
||||
{
|
||||
timestamps: true
|
||||
@@ -75,7 +69,7 @@ const machineIdentityClientSecretSchema = new Schema(
|
||||
);
|
||||
|
||||
machineIdentityClientSecretSchema.index(
|
||||
{ machineIdentity: 1, isActive: 1 }
|
||||
{ machineIdentity: 1, isClientSecretRevoked: 1 }
|
||||
)
|
||||
|
||||
export const MachineIdentityClientSecret = model<IMachineIdentityClientSecret>("MachineIdentityClientSecret", machineIdentityClientSecretSchema);
|
||||
@@ -1,6 +1,8 @@
|
||||
import jwt from "jsonwebtoken";
|
||||
import { Types } from "mongoose";
|
||||
import { MachineIdentity, MachineIdentityClientSecret } from "../../../models";
|
||||
import {
|
||||
IMachineIdentity,
|
||||
IdentityAccessToken,
|
||||
} from "../../../models";
|
||||
import { getAuthSecret } from "../../../config";
|
||||
import { AuthTokenType } from "../../../variables";
|
||||
import { UnauthorizedRequestError } from "../../errors";
|
||||
@@ -18,34 +20,80 @@ export const validateMachineIdentity = async ({
|
||||
|
||||
if (decodedToken.authTokenType !== AuthTokenType.MACHINE_ACCESS_TOKEN) throw UnauthorizedRequestError();
|
||||
|
||||
const machineIdentityClientSecret = await MachineIdentityClientSecret.findOne({
|
||||
_id: new Types.ObjectId(decodedToken.clientSecretDataId),
|
||||
isActive: true
|
||||
});
|
||||
const machineIdentityAccessToken = await IdentityAccessToken
|
||||
.findOne({
|
||||
_id: decodedToken.identityAccessTokenId,
|
||||
isAccessTokenRevoked: false
|
||||
})
|
||||
.populate<{ machineIdentity: IMachineIdentity }>("machineIdentity");
|
||||
|
||||
if (!machineIdentityClientSecret) throw UnauthorizedRequestError();
|
||||
if (!machineIdentityAccessToken || !machineIdentityAccessToken?.machineIdentity) throw UnauthorizedRequestError();
|
||||
|
||||
if (decodedToken.tokenVersion !== machineIdentityClientSecret.accessTokenVersion) {
|
||||
// TODO: raise alarm
|
||||
const {
|
||||
accessTokenNumUsesLimit,
|
||||
accessTokenNumUses,
|
||||
accessTokenTTL,
|
||||
accessTokenLastRenewedAt,
|
||||
accessTokenMaxTTL,
|
||||
createdAt: accessTokenCreatedAt
|
||||
} = machineIdentityAccessToken;
|
||||
|
||||
// ttl check
|
||||
if (accessTokenTTL > 0) {
|
||||
const currentDate = new Date();
|
||||
if (accessTokenLastRenewedAt) {
|
||||
// access token has been renewed
|
||||
const accessTokenRenewed = new Date(accessTokenLastRenewedAt);
|
||||
const ttlInMilliseconds = accessTokenTTL * 1000;
|
||||
const expirationTime = new Date(accessTokenRenewed.getTime() + ttlInMilliseconds);
|
||||
|
||||
if (currentDate > expirationTime) throw UnauthorizedRequestError({
|
||||
message: "Failed to authenticate MI access token due to TTL expiration"
|
||||
});
|
||||
} else {
|
||||
// access token has never been renewed
|
||||
const accessTokenCreated = new Date(accessTokenCreatedAt);
|
||||
const ttlInMilliseconds = accessTokenTTL * 1000;
|
||||
const expirationTime = new Date(accessTokenCreated.getTime() + ttlInMilliseconds);
|
||||
|
||||
if (currentDate > expirationTime) throw UnauthorizedRequestError({
|
||||
message: "Failed to authenticate MI access token due to TTL expiration"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// max ttl check
|
||||
if (accessTokenMaxTTL > 0) {
|
||||
const accessTokenCreated = new Date(accessTokenCreatedAt);
|
||||
const ttlInMilliseconds = accessTokenMaxTTL * 1000;
|
||||
const currentDate = new Date();
|
||||
const expirationTime = new Date(accessTokenCreated.getTime() + ttlInMilliseconds);
|
||||
|
||||
if (currentDate > expirationTime) throw UnauthorizedRequestError({
|
||||
message: "Failed to authenticate MI access token due to Max TTL expiration"
|
||||
});
|
||||
}
|
||||
|
||||
// num uses check
|
||||
if (
|
||||
accessTokenNumUsesLimit > 0
|
||||
&& accessTokenNumUses === accessTokenNumUsesLimit
|
||||
) {
|
||||
throw UnauthorizedRequestError({
|
||||
message: "Failed to authenticate",
|
||||
message: "Failed to authenticate MI access token due to access token number of uses limit reached"
|
||||
});
|
||||
}
|
||||
|
||||
const machineIdentity = await MachineIdentity.findByIdAndUpdate(
|
||||
machineIdentityClientSecret.machineIdentity,
|
||||
await IdentityAccessToken.findByIdAndUpdate(
|
||||
machineIdentityAccessToken._id,
|
||||
{
|
||||
accessTokenLastUsed: new Date(),
|
||||
$inc: { accessTokenUsageCount: 1 }
|
||||
accessTokenLastUsedAt: new Date(),
|
||||
$inc: { accessTokenNumUses: 1 }
|
||||
},
|
||||
{
|
||||
new: true
|
||||
}
|
||||
);
|
||||
|
||||
if (!machineIdentity) throw UnauthorizedRequestError({
|
||||
message: "Failed to authenticate"
|
||||
});
|
||||
|
||||
return machineIdentity;
|
||||
return machineIdentityAccessToken.machineIdentity;
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
import { z } from "zod";
|
||||
import { NO_ACCESS } from "../variables";
|
||||
|
||||
export const GetClientSecretsV3 = z.object({
|
||||
export const GetClientSecretsV1 = z.object({
|
||||
params: z.object({
|
||||
machineId: z.string()
|
||||
})
|
||||
});
|
||||
|
||||
export const CreateClientSecretV3 = z.object({
|
||||
export const CreateClientSecretV1 = z.object({
|
||||
params: z.object({
|
||||
machineId: z.string()
|
||||
}),
|
||||
@@ -18,21 +18,27 @@ export const CreateClientSecretV3 = z.object({
|
||||
}),
|
||||
});
|
||||
|
||||
export const DeleteClientSecretV3 = z.object({
|
||||
export const DeleteClientSecretV1 = z.object({
|
||||
params: z.object({
|
||||
machineId: z.string(),
|
||||
clientSecretId: z.string()
|
||||
})
|
||||
});
|
||||
|
||||
export const LoginMachineIdentityV3 = z.object({
|
||||
export const LoginMachineIdentityV1 = z.object({
|
||||
body: z.object({
|
||||
clientId: z.string().trim(),
|
||||
clientSecret: z.string().trim()
|
||||
})
|
||||
});
|
||||
|
||||
export const CreateMachineIdentityV3 = z.object({
|
||||
export const RenewAccessTokenV1 = z.object({
|
||||
body: z.object({
|
||||
accessToken: z.string().trim()
|
||||
})
|
||||
});
|
||||
|
||||
export const CreateMachineIdentityV1 = z.object({
|
||||
body: z.object({
|
||||
name: z.string().trim(),
|
||||
organizationId: z.string().trim(),
|
||||
@@ -51,11 +57,17 @@ export const CreateMachineIdentityV3 = z.object({
|
||||
.array()
|
||||
.min(1)
|
||||
.default([{ ipAddress: "0.0.0.0/0" }]),
|
||||
accessTokenTTL: z.number().int().min(1).default(7200)
|
||||
accessTokenTTL: z.number().int().min(0).default(7200),
|
||||
accessTokenMaxTTL: z.number().int().min(0).default(7200),
|
||||
accessTokenNumUsesLimit: z.number().int().min(0).default(0)
|
||||
})
|
||||
.refine(data => data.accessTokenTTL <= data.accessTokenMaxTTL, {
|
||||
message: "accessTokenTTL cannot be greater than accessTokenMaxTTL",
|
||||
path: ["accessTokenTTL"],
|
||||
})
|
||||
});
|
||||
|
||||
export const UpdateMachineIdentityV3 = z.object({
|
||||
export const UpdateMachineIdentityV1 = z.object({
|
||||
params: z.object({
|
||||
machineId: z.string()
|
||||
}),
|
||||
@@ -76,11 +88,12 @@ export const UpdateMachineIdentityV3 = z.object({
|
||||
.array()
|
||||
.min(1)
|
||||
.optional(),
|
||||
accessTokenTTL: z.number().int().min(1).optional()
|
||||
accessTokenTTL: z.number().int().min(0).optional(),
|
||||
accessTokenNumUsesLimit: z.number().int().min(0).optional()
|
||||
}),
|
||||
});
|
||||
|
||||
export const DeleteMachineIdentityV3 = z.object({
|
||||
export const DeleteMachineIdentityV1 = z.object({
|
||||
params: z.object({
|
||||
machineId: z.string()
|
||||
}),
|
||||
|
||||
Reference in New Issue
Block a user