ShtukbaseStandard
файл пакета→ .shtukbase/packages/std-twelve-factor/checks/tf01_config.ts

checks/tf01_config.ts

32 строки, 2.3 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // TF-R01 (III Config, observe): code does not hard-code the address of a backing service or a credential in a URL;
  2. // it reads them from the environment. A heuristic over code files (tests and fixtures excluded).
  3. import { codeFiles, COMMENT, PKG, PLACEHOLDER, READS_ENV, SAFE_HOST } from './tflib.ts';
  4. import { finish, norm, readTextFile } from './lib/std.ts';
  5. const n = norm(PKG, 'TF-R01', 'observe');
  6. const out: string[] = [];
  7. // "postgres://…", "redis://…", "amqp://…", "mongodb+srv://…" in a string literal.
  8. const CONN = /["'`](?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|rediss|amqps?|nats|kafka|mssql|sqlserver|clickhouse):\/\/[^"'`\s]+["'`]/i;
  9. // DATABASE_URL = "https://…", REDIS_HOST: 'cache.internal', apiEndpoint = "https://api…"
  10. const NAMED = /\b([A-Za-z_]*(?:DATABASE|DB|REDIS|MONGO|AMQP|RABBIT|KAFKA|ELASTIC|SMTP|BROKER|QUEUE|CACHE|API|SERVICE|BACKEND)[_]?(?:URL|URI|HOST|DSN|ENDPOINT|ADDR|ADDRESS))\b["']?\s*(?::=|=|:)\s*["'`]([^"'`\s]{4,})["'`]/i;
  11. const CRED = /\b[a-z][a-z0-9+.-]*:\/\/[^\s:/@'"`]+:([^\s@/'"`]{3,})@([^\s/:'"`]+)/i;
  12. /** The host of a URL-ish value, if any. */
  13. const host = (v: string) => /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]*@)?([^/:?#]+)/i.exec(v)?.[1] ?? v.replace(/:\d+$/, '');
  14. if (n.active)
  15. for (const f of codeFiles()) {
  16. const text = readTextFile(f);
  17. if (text === null) continue;
  18. text.split('\n').forEach((l, i) => {
  19. if (l.length > 2000 || COMMENT.test(l) || READS_ENV.test(l) || /secrets:allow|12factor:allow/.test(l)) return;
  20. const cred = CRED.exec(l);
  21. const conn = CONN.exec(l);
  22. if (cred && !PLACEHOLDER.test(cred[1]) && !SAFE_HOST.test(cred[2])) out.push(`${f}:${i + 1}: a login and password in an address right in the code → read the address from an environment variable`);
  23. else if (cred) return;
  24. else if (conn && !SAFE_HOST.test(host(conn[0].slice(1, -1)))) out.push(`${f}:${i + 1}: the address of an external service (database, queue, cache) right in the code → read it from an environment variable`);
  25. else {
  26. const m = NAMED.exec(l);
  27. if (m && /^[a-z]+:\/\/|\.[a-z]{2,}(:\d+)?$|:\d{2,5}$/i.test(m[2]) && !SAFE_HOST.test(host(m[2]))) out.push(`${f}:${i + 1}: "${m[1]}" is set in the code → read it from an environment variable`);
  28. }
  29. });
  30. }
  31. finish(n, out);