-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecurity.gs
More file actions
311 lines (276 loc) · 11.3 KB
/
Copy pathSecurity.gs
File metadata and controls
311 lines (276 loc) · 11.3 KB
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/**
* @file Security.gs
* @description Camada de segurança e controle de acesso do EnSiSanar.
* Complementa o Config.gs garantindo que segredos são válidos antes do uso
* e que rotas/operações exigem o papel correto do usuário autenticado.
*
* Responsabilidades:
* • Validar Config antes de operações críticas (API, DB).
* • Verificar se o usuário da sessão possui o papel exigido.
* • Sanitizar inputs para prevenir injeção em fórmulas do Sheets (OWASP A03).
* • Gerar e verificar tokens de sessão simples via HMAC-SHA256.
*
* @module Security
* @namespace Security
* @author EnSiSanar Dev Team
* @version 1.0.0
* @since 2026-04-16
* @requires Config – para HMAC secret via PropertiesService
*/
const Security = {
// ─── CONSTANTES INTERNAS ──────────────────────────────────────────────────
/** @private Papéis válidos no sistema. */
_ROLES: ['admin', 'terapeuta', 'paciente'],
/** @private Duração do token de sessão em milissegundos (8 horas). */
_TOKEN_TTL_MS: 8 * 60 * 60 * 1000,
/**
* @private
* Prefixo de armazenamento para tokens na UserCache.
* Isola tokens EnSiSanar de outros dados no cache.
*/
_TOKEN_CACHE_PREFIX: 'ENS_TOKEN_',
/** @private Prefixo para contadores curtos de rate limit no ScriptCache. */
_RATE_LIMIT_PREFIX: 'ENS_RATE_',
/** @private Prefixo para tokens CSRF vinculados à sessão no UserCache. */
_CSRF_CACHE_PREFIX: 'ENS_CSRF_',
/** @private TTL dos tokens CSRF em segundos. */
_CSRF_TTL_SECONDS: 2 * 60 * 60,
// ─── HELPERS PRIVADOS ─────────────────────────────────────────────────────
/**
* @private
* Retorna o segredo HMAC do PropertiesService.
* Usa GEMINI_API_KEY como entropia adicional se nenhum segredo dedicado
* estiver configurado — nunca usa string hardcoded.
* @returns {string}
*/
_getHmacSecret: function () {
const secret = PropertiesService.getScriptProperties().getProperty('SESSION_SECRET');
if (secret && secret.trim() !== '') return secret.trim();
// Fallback: deriva do API key (já é segredo do environment)
return 'ENS_' + Config.GEMINI_API_KEY.substring(0, 24);
},
// ─── API PÚBLICA: VALIDAÇÃO DE ACESSO ────────────────────────────────────
/**
* Lança Error se o papel do usuário não estiver na lista permitida.
* Use nos métodos de CRUD antes de qualquer operação sensível.
*
* @public
* @param {string} userRole – papel do usuário autenticado
* @param {string[]} allowedRoles – papéis que têm acesso
* @throws {Error} se o papel não for permitido
*
* @example
* Security.requireRole(session.role, ['admin', 'terapeuta']);
*/
requireRole: function (userRole, allowedRoles) {
if (!userRole || !allowedRoles || !Array.isArray(allowedRoles)) {
throw new Error('[Security.requireRole] Parâmetros inválidos.');
}
if (allowedRoles.indexOf(userRole) === -1) {
throw new Error(
'[Security] Acesso negado. Papel "' + userRole +
'" não permitido. Requerido: ' + allowedRoles.join(' | ')
);
}
},
/**
* Verifica se um papel é válido no sistema.
*
* @public
* @param {string} role
* @returns {boolean}
*/
isValidRole: function (role) {
return Security._ROLES.indexOf(role) !== -1;
},
// ─── API PÚBLICA: SANITIZAÇÃO ────────────────────────────────────────────
/**
* Remove prefixos que ativariam fórmulas em células do Google Sheets.
* Previne injeção de fórmulas (OWASP A03: Injection) ao escrever
* dados fornecidos pelo usuário diretamente em células.
*
* Caracteres de risco: = + - @ (início de célula) e \t \r.
*
* @public
* @param {string} value – valor de entrada do usuário
* @returns {string} valor sanitizado
*
* @example
* const safe = Security.sanitizeCell(formData.name);
* sheet.getRange(row, col).setValue(safe);
*/
sanitizeCell: function (value) {
if (typeof value !== 'string') return value;
// Remove caracteres de fórmula no início da string
return value.replace(/^[=+\-@\t\r]+/, '').trim();
},
/**
* Sanitiza um objeto inteiro de dados, aplicando sanitizeCell a cada
* campo string. Ideal para usar antes de qualquer DB_Core.insert().
*
* @public
* @param {Object} data
* @returns {Object} cópia do objeto com valores sanitizados
*
* @example
* const safeData = Security.sanitizeObject(req);
* DB_Core.insert('Patients', safeData);
*/
sanitizeObject: function (data) {
if (!data || typeof data !== 'object') return data;
return Object.keys(data).reduce(function (acc, key) {
acc[key] = Security.sanitizeCell(data[key]);
return acc;
}, {});
},
// ─── API PÚBLICA: CSRF E RATE LIMIT ──────────────────────────────────────
/**
* Gera um token CSRF curto, vinculado ao token de sessão atual.
* Útil para integrações HTTP POST fora do google.script.run.
*
* @public
* @param {string} sessionToken Token de sessão já validado.
* @returns {string} Token CSRF opaco.
*/
createCsrfToken: function (sessionToken) {
if (!sessionToken || typeof sessionToken !== 'string') {
throw new Error('[Security.createCsrfToken] Token de sessão obrigatório.');
}
var seed = sessionToken + '|' + Date.now() + '|' + Utilities.getUuid();
var secret = Security._getHmacSecret();
var csrf = Utilities.computeHmacSha256Signature(seed, secret)
.map(function (b) { return (b < 0 ? b + 256 : b).toString(16).padStart(2, '0'); })
.join('');
CacheService.getUserCache().put(
Security._CSRF_CACHE_PREFIX + sessionToken.substring(0, 16),
csrf,
Security._CSRF_TTL_SECONDS
);
return csrf;
},
/**
* Verifica se um token CSRF pertence à sessão informada.
*
* @public
* @param {string} sessionToken Token de sessão.
* @param {string} csrfToken Token CSRF recebido.
* @returns {boolean}
*/
verifyCsrfToken: function (sessionToken, csrfToken) {
if (!sessionToken || !csrfToken) return false;
var expected = CacheService.getUserCache().get(
Security._CSRF_CACHE_PREFIX + String(sessionToken).substring(0, 16)
);
return expected === csrfToken;
},
/**
* Rate limit simples por chave lógica usando ScriptCache.
* Lança Error com code='RATE_LIMITED' quando o limite é excedido.
*
* @public
* @param {string} key Chave lógica (ex.: rota, token, usuário).
* @param {number} maxRequests Máximo de chamadas na janela.
* @param {number} windowSeconds Janela em segundos.
*/
checkRateLimit: function (key, maxRequests, windowSeconds) {
var safeKey = String(key || 'anonymous').replace(/[^a-zA-Z0-9_.:-]/g, '_').substring(0, 120);
var limit = Math.max(1, Number(maxRequests) || 60);
var ttl = Math.max(1, Number(windowSeconds) || 60);
var cacheKey = Security._RATE_LIMIT_PREFIX + safeKey;
var cache = CacheService.getScriptCache();
var count = Number(cache.get(cacheKey) || '0');
if (count >= limit) {
var err = new Error('Limite de requisições excedido. Tente novamente em instantes.');
err.code = 'RATE_LIMITED';
throw err;
}
cache.put(cacheKey, String(count + 1), ttl);
},
// ─── API PÚBLICA: TOKENS DE SESSÃO ───────────────────────────────────────
/**
* Gera um token de sessão HMAC-SHA256 para o usuário autenticado.
* Armazena o token na UserCache com TTL de _TOKEN_TTL_MS.
* O token é opaco: não contém dados do usuário em texto claro.
*
* @public
* @param {string} userId – UUID do usuário
* @param {string} role – papel do usuário
* @returns {string} token de sessão (hex)
*
* @example
* const token = Security.createSessionToken(user.id, user.role);
* // retornar ao cliente via cookie HttpOnly ou header
*/
createSessionToken: function (userId, role) {
if (!userId || !role) {
throw new Error('[Security.createSessionToken] userId e role são obrigatórios.');
}
const payload = userId + '|' + role + '|' + Date.now();
const secret = Security._getHmacSecret();
const token = Utilities.computeHmacSha256Signature(payload, secret)
.map(function (b) { return (b < 0 ? b + 256 : b).toString(16).padStart(2, '0'); })
.join('');
// Armazena mapeamento token → payload na UserCache (TTL em segundos)
const ttlSeconds = Math.floor(Security._TOKEN_TTL_MS / 1000);
CacheService.getUserCache().put(
Security._TOKEN_CACHE_PREFIX + token,
JSON.stringify({ userId: userId, role: role, createdAt: Date.now() }),
ttlSeconds
);
return token;
},
/**
* Verifica um token de sessão e retorna os dados do usuário.
* Retorna null se o token for inválido, expirado ou adulterado.
*
* @public
* @param {string} token
* @returns {{ userId: string, role: string, createdAt: number }|null}
*
* @example
* const session = Security.verifySessionToken(token);
* if (!session) { return { error: 'Sessão expirada' }; }
* Security.requireRole(session.role, ['terapeuta']);
*/
verifySessionToken: function (token) {
if (!token || typeof token !== 'string' || token.length < 10) return null;
// Caracteres válidos: apenas hexadecimais (64 chars SHA256)
if (!/^[0-9a-f]{64}$/.test(token)) return null;
const raw = CacheService.getUserCache().get(
Security._TOKEN_CACHE_PREFIX + token
);
if (!raw) return null;
try {
const data = JSON.parse(raw);
// Verifica TTL manualmente como camada extra
if (Date.now() - data.createdAt > Security._TOKEN_TTL_MS) {
CacheService.getUserCache().remove(Security._TOKEN_CACHE_PREFIX + token);
return null;
}
return data;
} catch (e) {
return null;
}
},
/**
* Invalida um token de sessão (logout explícito).
*
* @public
* @param {string} token
*/
revokeSessionToken: function (token) {
if (!token) return;
CacheService.getUserCache().remove(Security._TOKEN_CACHE_PREFIX + token);
},
// ─── API PÚBLICA: VERIFICAÇÃO DE CONFIGURAÇÃO ─────────────────────────────
/**
* Atalho para verificar Config antes de operações críticas.
* Lança Error se qualquer segredo obrigatório estiver ausente.
*
* @public
* @throws {Error} propagado de Config.validate()
*/
assertConfigured: function () {
Config.validate();
}
}; // ── fim do namespace Security ───────────────────────────────────────────────