-
Notifications
You must be signed in to change notification settings - Fork 0
/
intention.service.ts
234 lines (222 loc) · 7.26 KB
/
intention.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { Request } from 'express';
import { v4 as uuidv4 } from 'uuid';
import * as crypto from 'crypto';
import { Cron, CronExpression } from '@nestjs/schedule';
import { plainToInstance } from 'class-transformer';
import ejs from 'ejs';
import { IntentionDto } from './dto/intention.dto';
import {
INTENTION_DEFAULT_TTL_SECONDS,
INTENTION_MAX_TTL_SECONDS,
INTENTION_MIN_TTL_SECONDS,
IS_PRIMARY_NODE,
} from '../constants';
import { AuditService } from '../audit/audit.service';
import { ActionService } from './action.service';
import { ActionError } from './action.error';
import { BrokerJwtDto } from '../auth/broker-jwt.dto';
import { IntentionRepository } from '../persistence/interfaces/intention.repository';
import { ActionDto } from './dto/action.dto';
export interface IntentionOpenResponse {
actions: any;
token: string;
transaction_id: string;
expiry: string;
}
@Injectable()
export class IntentionService {
private readonly AUDIT_URL_TEMPLATE = process.env.AUDIT_URL_TEMPLATE
? process.env.AUDIT_URL_TEMPLATE
: '';
constructor(
private readonly auditService: AuditService,
private readonly actionService: ActionService,
private readonly intentionRepository: IntentionRepository,
) {}
/**
* Opens an intention after validating its details.
* @param req The associated request object
* @param intentionDto The intention dto to validate
* @param ttl The requested time in seconds to live for this intention
* @returns The intention response or throws an error upon validation failure
*/
public async open(
req: Request,
intentionDto: IntentionDto,
ttl: number = INTENTION_DEFAULT_TTL_SECONDS,
): Promise<IntentionOpenResponse> {
const startDate = new Date();
const actions = {};
const actionFailures: ActionError[] = [];
if (ttl < INTENTION_MIN_TTL_SECONDS || ttl > INTENTION_MAX_TTL_SECONDS) {
throw new BadRequestException({
statusCode: 400,
message: 'TTL out of bounds',
error: `TTL must be between ${INTENTION_MIN_TTL_SECONDS} and ${INTENTION_MAX_TTL_SECONDS}`,
});
}
// Annotate intention event
intentionDto.transaction = {
...this.createTokenAndHash(),
start: startDate.toISOString(),
};
intentionDto.jwt = plainToInstance(BrokerJwtDto, req.user);
intentionDto.expiry = startDate.valueOf() + ttl * 1000;
for (const action of intentionDto.actions) {
const validationResult = this.actionService.validate(
intentionDto,
action,
);
action.valid = validationResult === null;
if (!action.valid) {
actionFailures.push(validationResult);
}
action.transaction = intentionDto.transaction;
action.user = intentionDto.user;
action.trace = this.createTokenAndHash();
actions[action.id] = {
token: action.trace.token,
trace_id: action.trace.hash,
outcome: validationResult === null ? 'success' : 'failure',
};
}
const isSuccessfulOpen = actionFailures.length === 0;
this.auditService.recordIntentionOpen(req, intentionDto, isSuccessfulOpen);
this.auditService.recordActionAuthorization(req, intentionDto);
if (!isSuccessfulOpen) {
throw new BadRequestException({
statusCode: 400,
message: 'Authorization failed',
error: actionFailures,
});
}
await this.intentionRepository.addIntention(intentionDto);
return {
actions,
token: intentionDto.transaction.token,
transaction_id: intentionDto.transaction.hash,
expiry: new Date(intentionDto.expiry).toUTCString(),
};
}
/**
* Closes the intention.
* @param req The associated request object
* @param token The intention token
* @param outcome The outcome of the intention
* @param reason The reason for the outcome
* @returns Promise returning true if successfully closed and false otherwise
*/
public async close(
req: Request,
token: string,
outcome: 'failure' | 'success' | 'unknown',
reason: string | undefined,
): Promise<IntentionDto> {
const intention: IntentionDto =
await this.intentionRepository.getIntentionByToken(token);
if (!intention) {
throw new NotFoundException({
statusCode: 404,
message: 'Intention not found',
});
}
await this.finalizeIntention(intention, outcome, reason, req);
return intention;
}
private finalizeIntention(
intention: IntentionDto,
outcome: 'failure' | 'success' | 'unknown',
reason: string | undefined,
req: Request = undefined,
): Promise<boolean> {
const endDate = new Date();
const startDate = new Date(intention.transaction.start);
intention.transaction.end = endDate.toISOString();
intention.transaction.duration = endDate.valueOf() - startDate.valueOf();
intention.transaction.outcome = outcome;
this.auditService.recordIntentionClose(req, intention, reason);
return this.intentionRepository.closeIntention(intention);
}
/**
* Logs the start and end of an action
* @param req The associated request object
* @param token The intention action token
* @param type Start or end of action
* @returns Promise returning true if successfully logged and false otherwise
*/
public async actionLifecycle(
req: Request,
intention: IntentionDto,
action: ActionDto,
outcome: string | undefined,
type: 'start' | 'end',
): Promise<boolean> {
if (!action) {
throw new NotFoundException({
statusCode: 404,
message: 'Action not found',
});
}
if (
(type === 'start' &&
(action.lifecycle === 'started' || action.lifecycle === 'ended')) ||
(type === 'end' && action.lifecycle === 'ended')
) {
throw new BadRequestException({
statusCode: 400,
message: 'Illegal lifecycle request',
error: `Action's current lifecycle state (${action.lifecycle}) can not do transition: ${type}`,
});
}
action = await this.intentionRepository.setIntentionActionLifecycle(
action.trace.token,
outcome,
type,
);
this.auditService.recordIntentionActionLifecycle(
req,
intention,
action,
type,
);
return true;
}
/**
* Renders the audit url for the intention passed in
* @param intention The intention to create the audit url for
* @returns The audit url string
*/
public auditUrlForIntention(intention: IntentionDto): string {
return ejs.render(this.AUDIT_URL_TEMPLATE, { intention });
}
/**
* Creates a unique token and cooresponding hash of it.
* @returns Object containing token and hash
*/
private createTokenAndHash() {
const token = uuidv4();
const hasher = crypto.createHash('sha256');
hasher.update(token);
return {
token,
hash: hasher.digest('hex'),
};
}
@Cron(CronExpression.EVERY_MINUTE)
async handleIntentionExpiry() {
if (!IS_PRIMARY_NODE) {
// Nodes that are not the primary one should not do expiry
return;
}
const expiredIntentionArr =
await this.intentionRepository.findExpiredIntentions();
for (const intention of expiredIntentionArr) {
await this.finalizeIntention(intention, 'unknown', 'TTL expiry');
}
}
}