MATHCAST
Mathcast / Документы / Mathchast_41 — Security / Privacy / Backups
МАТЧАСТЬ / SECURITY · PRIVACY · BACKUPS / DOCUMENT 41 / 03.09.2026

Security, Privacy и Backups

Модель защиты «Матчасти» для single-host production: threat model, доступы, OIDC/MFA, session security, multi-tenant isolation, SSRF-safe crawler, безопасные uploads, secrets, audit, персональные данные, работа с внешними AI-провайдерами, PostgreSQL PITR, off-host backup, MinIO versioning, restore drills и disaster recovery. Основной принцип: продукт хранит проверяемые бизнес-данные и чувствительные evidence-файлы, поэтому безопасность строится не как «поставим Cloudflare позже», а как отдельная система контроля и восстановления.

Assume breachминимальные привилегии, сегментация, immutable evidence и audit уменьшают blast radius
Private ≠ Publicпубличная статья и договор клиента живут в разных policy/storage paths
Backups off-hostкопия на том же NVMe не считается disaster recovery
Restore is the proofbackup считается рабочим только после регулярного восстановления в изолированную среду

1. Главное решение

Security baseline — OWASP ASVS 5.0 + NIST CSF 2.0 logic, адаптированные под реальный риск продукта. ASVS используется как engineering verification checklist, а NIST CSF — как структура governance: Govern, Identify, Protect, Detect, Respond, Recover.

2. Что защищаем

TIER A — CRITICAL database identity/session billing/credits private evidence verification data agency private workspaces backup keys TIER B — SENSITIVE drafts prompt sets reports private media client notes email/contact data TIER C — PUBLIC articles companies experts public sources public reports where explicitly shared.

3. Главные угрозы

account takeover cross-tenant data leak privilege escalation SSRF through crawler/URL ingestion malicious file upload XSS/content injection SQL/injection secret leak backup loss/ransomware admin compromise payment webhook spoofing AI/provider data leakage supply-chain dependency compromise bot scraping/abuse data deletion/operator error.

4. Самый опасный продуктовый риск

Cross-client leakage в Agency Workspace. Один ошибочный query/filter может раскрыть private prompts, invoices, drafts, evidence или reports другому клиенту.

5. Defense in depth for tenancy

1. workspace_id in private rows 2. server-side authorization 3. explicit resource policies 4. deny-by-default 5. RLS on highest-risk tables 6. negative authorization tests 7. audit 8. no shared-cache private responses.

6. Runtime DB role

Application role не является владельцем таблиц и не имеет BYPASSRLS. Migration owner отделён от runtime, как зафиксировано в Doc 40.

7. Security ownership

Founder/Product: risk acceptance Engineering: implementation Trust & Safety: review/reputation fraud Editorial: content policy Ops: host/backups/alerts Legal/privacy: 152-ФЗ, contracts, requests MVP: one person may hold several roles, but permissions/audit remain separated.

8. Security register

risk_id asset threat likelihood impact controls owner status accepted_until last_review.

9. Security review cadence

Before launch After major auth/tenant change After incident Quarterly lightweight Annual deeper review Dependencies: continuous/update alerts.

10. OWASP ASVS

OWASP lists ASVS 5.0.0 as the latest stable Application Security Verification Standard. It is specifically designed as a yardstick for application owners/developers and as guidance for security controls.

11. Launch target

Не объявлять формальную «ASVS certification», если её никто независимо не проводил. Использовать ASVS 5.0 как internal verification baseline and checklist.

12. Identity provider

Authentik: authentication MFA/passkeys where configured OIDC user lifecycle Mathchast: authorization agency/client scopes entity delegation billing permissions.

13. Password storage

Mathchast не хранит user passwords. Они остаются в identity provider.

Если когда-либо появится собственное password auth, OWASP рекомендует современные slow password hashes, прежде всего Argon2id, а не SHA-256/MD5.

14. MFA

REQUIRED: platform admins agency admins billing/admin roles security-sensitive support RECOMMENDED: all editors/clients with private data access.

15. High-risk step-up

Re-auth/MFA for: change official entity owner change billing bank data create API key disable MFA export sensitive evidence delete workspace change admin role.

16. Session cookies

OWASP session guidance recommends meaningless high-entropy session identifiers, TLS and secure cookie controls.

HttpOnly Secure SameSite appropriate short path/domain scope server-side session state rotation after privilege change.

17. Session invalidation

logout password/identity reset MFA reset role removal agency employee offboarding client revocation security incident → active sessions revoked.

18. Session lifetime

Exact timeout is policy/config, not hard-coded architecture fact. Admin/high-risk roles use shorter idle lifetime than ordinary read-only client sessions.

19. No sensitive tokens in localStorage

Browser auth secrets should not be designed around long-lived localStorage tokens.

20. CSRF

Same-site cookies + framework CSRF protections for unsafe requests + Origin/Referer validation where appropriate + idempotency keys for financial writes.

21. Authorization principle

Every object access checks authorization on the server; UI hiding is not security.

22. IDOR testing

For every private endpoint: replace: workspace_id report_id file_id publication draft ID invoice ID with another tenant's ID Expected: deny without metadata leak.

23. Public IDs

UUIDv7: reduces trivial enumeration But: unguessable ID does NOT replace authz.

24. Admin access

MFA required separate admin role audit no broad sharing account no daily root login separate server SSH identities.

25. SSH

keys only root direct login disabled password login disabled if operationally safe allowlist/VPN where possible Fail2ban/rate controls optional sudo audited keys rotated on staff change.

26. Production shell access

Editorial/support users never receive host shell access.

27. Rootless containers?

Where practical, services run as non-root users and with reduced capabilities. Rootless Docker can be considered, but launch must prioritize tested operational reliability.

28. Container hardening

non-root process read-only root FS where possible tmpfs for temp drop capabilities no privileged no host PID/network no Docker socket resource limits healthchecks pinned images.

29. Docker socket

Application containers do not mount /var/run/docker.sock. It effectively grants host-level control.

30. Host filesystem

No app source bind mounts in prod Secrets root-owned State only explicit volumes Backups separate Private evidence not under web root.

31. Docker secrets

Docker Compose supports per-service secrets mounted under /run/secrets, reducing exposure compared with broad environment variables.

Use Docker secrets/root-owned files for DB passwords, provider keys and signing keys rather than checking them into Compose or Git.

32. Important Compose caveat

Compose secrets on a single host are ultimately files/bind-mounted material; they are not a magical external KMS. Host permissions, encryption and backup handling still matter.

33. Secret inventory

DB credentials Redis auth MinIO keys OIDC secret cookie/session signing email provider payment provider Search Console OAuth/service creds Yandex creds AI provider keys backup encryption keys webhook signing secrets.

34. Secret access matrix

web: no DB admin no backup key api: app DB OIDC payment worker-ai: AI provider keys scoped DB backup: backup repo key replication/backup DB role principle: minimum per service.

35. Secret rotation

immediate: suspected leak staff compromise scheduled: high-value provider/admin keys according provider capability procedure: dual key if possible rotate verify revoke old audit.

36. Git scanning

CI/pre-commit: secret scanner If secret committed: remove from repo history if needed BUT ALWAYS rotate key. Deleting Git line: not sufficient.

37. Dependency security

lockfiles pinned direct dependencies automated vulnerability alerts review major upgrades avoid unknown tiny auth/crypto libs container base image updates SBOM later.

38. Supply chain

Auth, crypto, sanitization and file parsing use mature libraries/frameworks; do not custom-build cryptography.

39. CI credentials

least privilege short-lived where possible production deploy role separate no prod DB password in developer environment protected branches/tags.

40. Artifact provenance

image: git SHA build time dependency lock registry digest Deploy: immutable digest/version.

41. XSS

React escaping structured editor HTML sanitizer allowlist safe URLs CSP no arbitrary script embeds iframe allowlist.

42. User publication HTML

Не хранить/рендерить произвольный user HTML как trusted. Structured block document renders through controlled components.

43. Allowed embeds

YouTube/etc only: known provider validated ID/URL sandboxed iframe privacy/config policy No: arbitrary iframe HTML.

44. Content Security Policy

default-src 'self' script-src nonce/hash strategy object-src 'none' base-uri 'self' frame-ancestors policy connect/img/media scoped report violations. Tune: staging first.

45. Other headers

HSTS after HTTPS proven X-Content-Type-Options: nosniff Referrer-Policy Permissions-Policy CSP frame-ancestors secure cache controls.

46. SQL injection

parameterized queries typed query layer no string-concatenated filters allowlisted sort/order fields statement timeouts.

47. Command injection

Workers must not concatenate user-controlled filenames/URLs into shell commands. Use library APIs or strict argument arrays.

48. SSRF is a core threat

OWASP defines SSRF as abuse of an application's server-side URL fetching to reach internal/external resources. «Матчасть» intentionally fetches user-supplied media URLs, source URLs, webhooks later and external media, so this is a first-class risk.

49. Crawler network isolation

Crawler/browser worker gets its own constrained network path. Core Postgres/Redis/admin endpoints should not be reachable from generic URL fetches.

50. URL schemes

Allow: http https Deny: file ftp gopher dict data javascript unix custom schemes.

51. Destination blocking

Reject: loopback RFC1918/private link-local multicast unspecified IPv6 local/private host network Docker bridge/internal metadata services.

52. DNS rebinding defense

Parse hostname resolve validate all IPs connect validate redirect target again limit redirect count consider IP pinning/connection verification.

53. Redirect defense

Every redirect: new URL parse scheme check DNS resolve private-IP check Never: validate first URL only.

54. Metadata endpoints

Block cloud/host metadata ranges even if current deployment is bare metal; future cloud migration then remains safe.

55. Fetch limits

connect timeout total timeout max redirects max response bytes allowed content types decompression limits per-domain concurrency.

56. Zip/decompression bomb

Do not trust Content-Length. Enforce streamed byte/decompressed limits.

57. Browser worker

isolated container non-root seccomp/default hardening memory/CPU timeout no private network fresh context downloads disabled no credential store.

58. Webhooks future

Outbound webhook URLs: same SSRF policy Incoming: signed payload timestamp/replay check event ID idempotency.

59. File upload threat

OWASP File Upload guidance recommends allowlisting extensions/types, validating signatures/content, using safe filenames, storing outside web root, applying permission limits and upload size limits.

60. Upload policy by purpose

PUBLIC MEDIA: jpg/png/webp/pdf perhaps PRIVATE EVIDENCE: pdf/images/docx/xlsx limited according workflow AVATAR: images only Never: arbitrary executable archives.

61. Extension is not enough

Check: declared MIME detected MIME magic/signature size parser validity Mismatch: quarantine/reject.

62. Original filename

Store as metadata for display only Object key: random UUID/hash Never: filesystem path from user filename.

63. Malware scanning

For private office/PDF uploads, add AV scanning before moderator download. ClamAV-class scanner is acceptable MVP if operationally maintained; high-risk file types can simply be disallowed.

64. PDF rendering

Never execute embedded scripts browser PDF preview isolated download headers safe no inline rendering of unknown active formats.

65. Office documents

Avoid server-side LibreOffice conversion in the public request path. If needed, isolated worker with strict resource/network limits.

66. EXIF metadata

Public images: strip unnecessary metadata Private evidence: preserve original when evidence integrity matters.

67. Public media variants

Original private ingest → validate → safe derivative → publish derivative Public delivery: never raw unvalidated upload.

68. Evidence files

private bucket/prefix signed temporary download role check every request no predictable public URL audit access retention policy.

69. Evidence encryption

Storage and backup encryption at rest is required for private evidence. Encryption key should not live only in the same unprotected backup repository.

70. MinIO versioning

MinIO AIStor supports object versioning; overwrites create new versions, helping recover from unintended overwrite/delete. Versioning is also a prerequisite for object locking.

71. Versioning policy

Enable: private evidence bucket backup repository critical reports Consider: public media Lifecycle: remove old versions only under documented retention.

72. Object Lock

For backup repository, immutable/object-lock retention is desirable if supported and operationally tested. This reduces ransomware/admin-delete risk but complicates retention and storage costs.

73. MinIO credential scopes

app-public: public media only app-private: evidence report-worker: reports backup: backup repo only No: single root key inside every container.

74. Payment security

Do not store card data if payment provider can handle it Webhooks: signature verify event ID unique amount/order verify state machine audit.

75. Invoice fraud

Bank detail changes: admin step-up audit second-person check later notification to finance.

76. Credit ledger fraud

append-only ledger no direct balance edit manual adjustment: reason + authorized actor audit.

77. Email security

SPF DKIM DMARC separate transactional sender least-priv provider key bounce/complaint processing.

78. Review invitation abuse

rate limit verified company relation neutral template signed invitation token expiry single-use where appropriate fraud monitoring.

79. Magic links

high entropy short expiry single-purpose single-use/rotatable hashed token server-side if practical no sensitive data inside URL.

80. Search/AI external providers

Do not send private client evidence, contracts, unpublished drafts or personal data to external AI providers by default.

81. P0 AI provider input policy

Allowed: public company name public prompt public URLs public article text public source metadata Not allowed: private evidence private notes billing personal documents unpublished confidential case data.

82. AI editor on unpublished content

If external LLM is used on drafts, this must be explicit in privacy/vendor processing policy and restricted by client/data classification. Safer P0: local model for sensitive precheck or no external processing until contracts/DPA are resolved.

83. External AI DLP gate

Before provider request: data classification PII detector optional workspace policy provider allowlist purpose logging without raw secret.

84. Prompt injection from crawled pages

External web pages are untrusted data. Their text must never become system instructions for internal agents/tools.

85. Agent/tool separation

Crawler output: DATA LLM: cannot arbitrarily execute shell cannot access secrets cannot query arbitrary tenant cannot publish directly Tool calls: allowlisted policy checked.

86. AI-generated recommendation

LLM explanation: untrusted draft Deterministic score/evidence: source of truth Human review: commercial/editorial high-impact.

87. Privacy by data class

DataPublic?Retention principle
Published articleYespublication policy/history
Company verified factsSelected publiccurrent + provenance/history
User account/contactNoaccount/legal need
Private evidenceNominimum verification/legal need
DraftNoworkspace lifecycle
Billing docsNoaccounting/legal retention
AI raw public monitoringPrivate/reportmethodology/reprocessing need
Audit/security logsNosecurity/legal need

88. Data minimization

If verification can be completed from one redacted invoice page, do not request a full 80-page contract.

89. Purpose limitation

Evidence uploaded for: verification Do not automatically reuse for: AI training marketing public case sales enablement.

90. Public-source personal data

A person's name/role being public online does not remove all personal-data obligations. Entity/profile publication needs a clear legal/editorial basis and correction/removal process.

91. 152-ФЗ baseline

Федеральный закон №152-ФЗ определяет персональные данные, оператора, обязанности при обработке и требования к безопасности. Для «Матчасти» нужен formal privacy/legal workstream before launch.

92. Localization requirement

Действующая редакция 152-ФЗ содержит требование: при сборе персональных данных граждан РФ через интернет запись, систематизация, накопление, хранение, уточнение и извлечение должны осуществляться с использованием баз данных, находящихся на территории РФ, за установленными законом исключениями.

Launch gate: физическое размещение production databases для персональных данных граждан РФ должно быть юридически проверено. Если текущий production host находится вне РФ, нельзя просто «считать, что всё нормально».

93. External AI and localization

Даже при российской primary database отправка персональных данных иностранному AI/SaaS provider может затрагивать отдельные правила передачи/поручения/трансграничной передачи. Поэтому P0 внешним AI передаёт только public/non-sensitive business context unless counsel approves more.

94. Data processor contracts

152-ФЗ предусматривает требования, когда оператор поручает обработку другому лицу: предмет, данные, операции, цели, конфиденциальность, безопасность и соответствующие обязанности должны быть определены.

95. Subprocessor register

provider purpose data classes country/location legal basis contract/DPA retention security last review.

96. Likely subprocessors

email payment AI providers monitoring/error service cloud backup/object storage if external support tools analytics if external.

97. P0 privacy preference

Self-host core identity/database/storage wherever reasonable; use external vendors only for well-bounded purposes.

98. Privacy notice

who operates what data purposes legal bases recipients/processors retention principles rights/requests cookies/analytics cross-border where relevant security contact.

99. Consent ≠ universal legal basis

Do not use one broad checkbox «согласен на всё» to justify every processing purpose. Legal counsel must map actual bases per flow.

100. Separate public-distribution consent

Expert portrait/bio review identity client logo/quote case person data Public display: explicit scope/status where required by legal basis.

101. Data subject request workflow

request identity verification scope search records legal/editorial exceptions correct/delete/restrict as applicable response audit.

102. One-click dangerous deletion

Deleting user account must not cascade-delete published articles, invoices or legally retained records blindly.

103. Deletion map

Account: disable/anonymize where permitted Private drafts: delete after lifecycle Evidence: delete after retention/legal hold Billing: legal retention Public publication: publication/correction policy Audit: security/legal retention.

104. Privacy deletion job

request_id subject data classes decision legal basis objects affected completed_at approver exceptions.

105. Cookies

Essential: session/security no consent banner trickery Analytics: choose privacy-preserving setup and legal basis/cookie requirements with counsel.

106. Analytics minimization

No: cross-site ad trackers fingerprinting unnecessary precise geolocation Need: publication performance referrer category meaningful read outbound click.

107. IP addresses

Access/security logs may contain IP addresses and other identifiers. Define retention and privacy treatment rather than keeping raw logs forever.

108. Logging security events

OWASP logging guidance explicitly highlights authentication failures, authorization failures, session failures, application errors, configuration changes and high-risk functionality.

Always security-log: login/MFA events authz denial admin role change entity delegation API key actions evidence access manual credit adjustment webhook verification failure backup/restore action.

109. Never log

password OIDC tokens session cookie full API keys private document body card/bank secret backup encryption key raw auth header.

110. Log redaction

structured logger: known secret fields redacted Errors: sanitize provider payload before logging.

111. Security audit vs telemetry

AUDIT: who changed business state SECURITY: auth/access anomaly OPS LOG: application execution Separate retention/access.

112. Vulnerability disclosure

Before public launch, publish a security contact and simple responsible-disclosure policy.
security@mathchast.com scope safe harbor language reviewed what not to test response expectation no bug bounty promise initially.

113. Security.txt

Consider RFC 9116 /.well-known/security.txt after launch.

114. Abuse protection

rate limits bot limits WAF/CDN later login throttling submission quotas AI run quotas crawler rate controls email invite limits.

115. DDoS

Single host: inherently limited resilience Mitigation: edge proxy/CDN/WAF later rate controls cached public pages provider-level network protection. Do not promise: DDoS-proof.

116. Backup is the highest priority recovery control

Single physical host means hardware loss is a real scenario, not theoretical.

117. Backup threat scenarios

NVMe dies server dies operator drops table bad migration ransomware root compromise MinIO deletion Docker volume deletion Postgres corruption credential compromise.

118. Local copy is not backup enough

Backup on another directory/volume of the same host does not protect against host theft, filesystem corruption or root compromise.

119. 3-layer backup recommendation

LAYER 1: continuous/local operational recovery LAYER 2: off-host backup on second physical machine/storage LAYER 3: independent encrypted copy preferably different failure domain/location.

120. Backup architecture

Mathchast Postgres │ ├─ WAL archive continuous │ ├─ base backups │ └─ logical pg_dump supplementary │ ▼ OFF-HOST BACKUP REPOSITORY │ └─ secondary encrypted copy MinIO critical buckets ├─ versioning ├─ replication/copy └─ off-host backup.

121. PostgreSQL PITR

PostgreSQL continuous archiving combines base backup + archived WAL and supports restoring to a chosen point in time. PostgreSQL describes PITR as a preferred strategy in many high-reliability situations.

122. Base backup

pg_basebackup can take a base backup from a running cluster and can serve as the starting point for point-in-time recovery or standby replication.

123. Recommended tool layer

Use pgBackRest or WAL-G rather than hand-written tar scripts.

pgBackRest provides backup/restore, WAL archiving, retention and repository encryption. WAL-G supports compressed/encrypted full/incremental backups and remote S3-compatible storage. Pick one, document it, and test restore.

124. Recommendation

Preferred initial: pgBackRest Reason: mature PostgreSQL-focused backup/restore/retention encryption monitoring clear operational docs. WAL-G: valid alternative, especially S3-oriented.

125. Do not run two backup systems casually

Two half-configured backup tools are worse than one fully tested system plus one supplementary logical dump.

126. Backup repository

Primary backup repo: OFF-HOST Optional local staging/cache: not sole repository Encryption: client/tool-side Credentials: backup-only.

127. RPO target hypothesis

Core PostgreSQL: RPO ≤ 15 minutes target via continuous WAL archive Critical object storage: RPO ≤ 1 hour target or near-continuous replication Public media: can tolerate longer if original available.

These are project SLO hypotheses; final operational SLO/RTO is locked in Doc 42 after restore/load testing.

128. RTO target hypothesis

Core public/API: ≤4 hours target Full async/search/AI: ≤8 hours target Catastrophic host rebuild: may be longer until tested automation exists.

129. Backup schedule starting point

Postgres: continuous WAL daily differential/incremental weekly full daily logical dump supplementary Retention starting point: 7–14 daily recovery points 4–8 weekly 3–6 monthly Tune by: DB size WAL volume legal retention storage cost.

130. Retention is not a universal law

Exact numbers above are operational hypotheses, not PostgreSQL recommendations. Measure storage growth and legal needs.

131. Logical dump role

Useful for: schema inspection selective logical restore portable extra layer Not sufficient alone for: tight RPO/PITR.

132. pg_dump alone

Doc 40 already noted PostgreSQL documentation does not position pg_dump as the sole regular production backup method for high-reliability scenarios.

133. Off-host copy

Physical second server/storage or trusted object storage with encrypted repository Must survive: production host loss.

134. Same-rack/home risk

A second physical server in the same room protects against disk/server failure but not fire/theft/power disaster. A third copy in a separate failure domain gives materially stronger recovery.

135. Backup credentials separation

Production app: cannot delete backup repo Backup process: write backups Restore admin: separate privileged path Ideal: object lock/immutable retention.

136. Ransomware-resistant backup

off-host encrypted versioned delete-restricted immutable window where possible credentials not available to normal app containers.

137. Backup encryption key

If encryption key is stored only on production host and host is lost, backup is useless. If key sits unprotected next to backup, confidentiality is weak.

138. Key escrow

At least: encrypted password manager/offline secure record two authorized owners documented recovery procedure rotation plan.

139. PostgreSQL backup verification

Every backup: tool status size WAL continuity checksum/metadata age alert But: still not enough.

140. Restore test is definitive

NIST recovery guidance explicitly says to verify integrity of backups/recovery assets before relying on them.

141. Automated restore test

Weekly: new isolated PostgreSQL restore latest start DB run integrity queries check critical row counts verify migration/version destroy test instance.

142. PITR test

Monthly: create known marker backup/WAL simulate deletion restore to timestamp verify marker/state document actual RPO/RTO.

143. Full disaster drill

Quarterly initially: assume production host lost Rebuild: nginx/app Postgres Redis MinIO Authentik dependency secrets/config restore DNS/routing smoke tests.

144. Backup alert

CRITICAL if: WAL archive lag > threshold no recent successful base backup repo unreachable restore test failed backup size anomalous object copy stale.

145. MinIO backup classes

CRITICAL: private evidence report snapshots raw provider evidence needed for methodology REBUILDABLE: derived thumbnails cached exports PUBLIC: article media still backed up, but priority lower.

146. Object storage replication

Versioning alone does not protect against losing the entire MinIO host. Critical bucket data needs off-host copy/replication.

147. Versioning vs backup

Versioning protects: overwrite/delete mistakes Off-host backup protects: host/storage loss Object Lock protects: some destructive actions Need: combination.

148. Authentik backup

Authentik documentation states that its PostgreSQL database is the most important part of backup because it stores users, policies, flows and configuration, and recommends keeping backups somewhere other than the database host when possible.

149. Shared Authentik implication

Mathchast DR plan is incomplete if the application DB is restorable but Authentik cannot be restored.

150. Authentik dependency backup

Authentik Postgres configuration secrets/certs custom templates if any version/image info restore procedure.

151. Redis backup

Redis contains: queues/transient jobs possibly sessions/cache Design: critical business truth in Postgres Therefore: Redis loss should be recoverable without losing paid orders/publications.

152. Queue recovery

Outbox in Postgres → redis queues can be rebuilt Scheduled work: DB schedule table → re-enqueue This is why: Redis isn't source of truth.

153. Redis persistence

Use appropriate AOF/RDB based on queue/session needs, but backup architecture should not assume Redis persistence is enough for business recovery.

154. nginx/config backup

Git: nginx templates compose infra scripts Secrets: separate encrypted backup Host config: document/bootstrap automation.

155. Infrastructure as code lite

Single host should still be reproducible with scripts/Ansible-class automation rather than a handwritten wiki of shell commands.

156. Rebuild repository

infra/ install Docker create users firewall mount disks restore secrets deploy compose restore DB/storage verify.

157. Backup inventory

asset backup method location encryption frequency retention RPO restore procedure last restore test owner.

158. Backup inventory P0

AssetBackupOff-host
Mathchast PostgresPITR + base + logicalRequired
Private MinIO objectsversion + copyRequired
Public mediacopyRequired
Authentik DBPostgres-nativeRequired
Redispersistence optionalNot primary recovery source
Secretsencrypted recovery copyRequired
Code/infraGit remoteRequired

159. Redis-only data is a smell

If losing Redis means losing a paid action permanently, architecture is wrong.

160. Disaster classes

D1: single container D2: database process/volume D3: NVMe/storage D4: whole host D5: credential/root compromise D6: site/location disaster Each: different restore plan.

161. Recovery priority

1. identity/auth 2. PostgreSQL core 3. public web/API 4. private evidence storage 5. billing/order 6. async queues 7. Search/AI monitoring 8. derived analytics/backfills.

162. Maintenance mode

If write integrity uncertain: public read-only mode disable writes/orders show incident notice if needed restore/check resume deliberately.

163. Read-only fallback

P1: public cached articles/company pages may remain available during some DB incidents if architecture supports safe cached read-only serving.

164. Recovery access

Break-glass credentials: offline/secure MFA if possible logged use rotate after incident Never: unknown password known only to one laptop.

165. Incident response preview

DETECT CONTAIN PRESERVE EVIDENCE ERADICATE RECOVER COMMUNICATE LEARN Detailed: Doc 42.

166. Privacy incident

A suspected personal-data leak is not just an engineering outage. It triggers a legal/privacy response workflow and potentially statutory notification duties, which must be defined with counsel before launch.

167. Evidence preservation during incident

Do not immediately wipe: logs audit affected containers/disks provider event IDs Preserve enough: to understand scope.

168. Access review

Monthly/quarterly: admins agency staff former employees service accounts API keys backup users MinIO access.

169. Dormant accounts

Disable: former staff expired contractors Notify/review: long-unused privileged accounts.

170. Service accounts

named purpose-bound non-interactive where possible owner rotation last used scoped secret.

171. Shared accounts

No shared «admin@» login for humans.

172. API keys future

prefix/id visible secret shown once hash at rest scopes workspace/org expiry optional last used revoke.

173. API key logs

Log: key ID/prefix not full secret.

174. Rate limit bypass

Admin support cannot silently set: unlimited AI calls for arbitrary client Quota override: reason expiry audit.

175. Data export security

async export authorization at request snapshot scope signed URL short expiry audit optional re-auth for sensitive exports.

176. CSV injection

When exporting user-controlled text to CSV/XLSX, protect against spreadsheet formula injection for cells beginning with =, +, - or @ where relevant.

177. PDF/report injection

escape content sanitize HTML no arbitrary local file URL browser renderer isolated network restricted.

178. Image processing

memory/time limits pixel dimension limits known decoder versions sandbox worker reject malformed bombs.

179. Domain/email verification

verification token DNS/email proof expiration rate limits anti-takeover audit.

180. Company takeover risk

Do not grant control because: free mailbox address uploaded logo payment agency statement alone. Use: Doc 20 verification evidence.

181. Reputation abuse

Review fraud reference fraud case fake credential fake Security signals: identity reuse burst IP/device pattern document reuse counterparty verification.

182. Trust & Safety data

Fraud signals are sensitive internal data and should not be broadly exposed to companies/agencies.

183. Backoffice impersonation

Support/admin should not have an invisible «login as user» that performs actions without attribution.

184. If impersonation needed later

explicit support mode reason time-limited banner audit user action attribution preserved sensitive actions disabled.

185. Privacy-safe support

Default: metadata/status Need private file: explicit elevated access reason audit Avoid: support browsing all client evidence casually.

186. Production data in dev

Do not dump production DB with personal/evidence data into local developer machines.

187. Test data

synthetic or anonymized/minimized Staging: separate identities no real payment no private evidence by default.

188. Anonymization

Simple removal of name may not be sufficient if company/role/context re-identifies a person. Use genuine minimization/synthetic data for dev.

189. Backups contain personal data too

Privacy deletion policy must account for backups: immediate selective deletion from PITR archives may be impossible; document expiry/restore handling and prevent deleted data from becoming active again after restore.

190. Post-restore deletion reconciliation

After old backup restore: replay deletion/tombstone ledger or run privacy reconciliation before external service resumes.

191. Backup access audit

Who can: list read restore delete change retention Keep: very small group.

192. Backup repository network

Not publicly exposed authenticated TLS firewall backup-only account admin path restricted.

193. Storage health

SMART filesystem free space IO errors RAID/ZFS state if used backup repo capacity Alert: before full disk.

194. Disk full is a security/reliability event

PostgreSQL/WAL/archive failures caused by no space can destroy recovery assumptions.

195. Time synchronization

NTP/systemd-timesyncd consistent UTC clocks Needed for: audit OIDC webhook replay PITR incident timeline.

196. TLS

HTTPS only public modern TLS automatic renewal HSTS after validation internal TLS where risk/architecture requires.

197. Internal Docker network

Postgres/Redis: no public host port Only app network and admin/backup path. MinIO admin: not internet exposed casually.

198. Firewall

Default deny inbound Expose: 80/443 VPN/SSH restricted Do not expose: 5432 6379 MinIO admin Docker API.

199. Egress control

Especially important for crawler/browser/AI workers. Core DB should not need arbitrary internet egress.

200. Security headers test

Automated: CSP baseline HSTS nosniff referrer frame ancestors cookies Run: CI/staging.

201. Dependency patch window

Critical remotely exploitable: as soon as tested Regular: weekly/monthly maintenance Base images: rebuild even if app code unchanged.

202. PostgreSQL/Redis/Auth updates

Patch supported versions deliberately; backup/restore compatibility and extension compatibility tested in staging.

203. Security scanner scope

SAST dependency container image secret scan DAST staging TLS/header scan Manual: authz/SSRF/business logic.

204. Why automated scanner is not enough

Cross-tenant logic, entity takeover, billing/credit fraud and publication authorization are business-logic vulnerabilities scanners often miss.

205. Pre-launch penetration test

Before accepting significant private evidence/billing scale, arrange focused external test or experienced security review covering authz, SSRF, uploads, tenancy and admin surfaces.

206. Scope first external test

OIDC/session workspace isolation file access URL crawler publishing XSS billing/webhooks admin API authorization rate/abuse.

207. Security launch gates

MUST before public paid launch: MFA admin no public DB/Redis tenant authz tests SSRF protections upload allowlist private bucket separation secret handling audit backup off-host restore test privacy policy/legal review incident contact.

208. Additional launch gate: location

Confirm where production DB physically resides and whether it satisfies Russian personal-data localization obligations for actual processing flows.

209. Additional launch gate: external AI

No private/personal client payloads to foreign AI providers until legal/privacy/vendor contracts and data-flow map are reviewed.

210. RPO/RTO measurement

Target written ≠ achieved After each restore drill: record: data loss window restore duration manual steps failure new target.

211. Recovery runbook

Who declares DR Where secrets are How get fresh host How restore Postgres How restore objects How restore Authentik How deploy app How validate How switch DNS How communicate.

212. Runbook storage

Keep an offline/off-platform copy. A runbook only inside the broken server is useless.

213. Backup runbook secrets

Do not put plaintext encryption keys directly inside runbook document.

214. Restore smoke checks

login company page publication draft agency tenant billing ledger private file AI report snapshot audit new write queue dispatch.

215. Integrity queries

foreign-key consistency published version exists credit balance ledger file references exist workspace subjects count latest migration outbox state.

216. Recovery after compromise

Do not restore: compromised secrets known malicious app image unknown backdoor Need: clean images rotated secrets patched vulnerability then data restore.

217. Backup malware concern

Backups may contain malicious uploaded files. Restoring data is not the same as automatically republishing/executing every object.

218. Security KPIs P0

privileged MFA coverage critical authz test coverage backup age WAL archive age restore test success unpatched critical vulns open security incidents privileged account count.

219. Privacy KPIs P0

data subject requests overdue requests processors reviewed sensitive AI export blocks private evidence age privacy incidents.

220. Don't gamify security score

No public «Security Score 97». Security posture is a set of controls, evidence and unresolved risk.

221. Security documentation set

Threat Model Access Control Matrix Data Classification Processor Register Backup Policy Restore Runbook Incident Runbook Vulnerability Policy Privacy Data Map Key/Secret Register Security ADRs.

222. Data-flow diagram

Browser → Mathchast → Authentik → PostgreSQL → MinIO Optional external: payment email Google/Yandex AI providers For each arrow: data category purpose country/location retention encryption.

223. Privacy-by-design review for every integration

Before new vendor: What data leaves? Why? Can we send less? Is it personal/private? Where processed? Retention? Training use? DPA? Can client opt out? Can local worker replace it?

224. Vendor AI training settings

For every provider, verify current API terms/data-retention/training settings at integration time. Do not assume consumer-chat privacy terms equal API terms.

225. Vendor outage vs data breach

Availability: Doc 42 incident Security/privacy: this doc + Doc 42 Need: separate severity dimensions.

226. Security incident severity preview

SEV1: confirmed cross-tenant/private breach root/DB compromise backup destruction SEV2: privilege weakness exploited/likely sensitive vendor leak SEV3: limited account compromise no broader evidence Final: Doc 42.

227. Security event notification to client

Contract/privacy policy must define channels and responsibilities; statutory deadlines require legal counsel. Product should have contact data and ability to identify affected workspaces quickly.

228. Breach scope query

Need ability to answer: which users which workspaces which files which actions which timestamps which processors Therefore: audit + object access logging.

229. Evidence access log

file_id actor workspace purpose view/download timestamp request_id.

230. Published public data access logs

No need to store every visitor IP indefinitely just because it is technically possible.

231. Retention design principle

Keep data because a defined product/legal/security purpose still exists, not because storage is cheap.

232. Security by product tier

Same baseline: free/paying Enterprise adds: SSO audit exports custom retention security questionnaire SLA Paying more: does not create basic confidentiality.

233. White-label agency security

Agency branding never changes underlying workspace authz/provenance. White-label presentation cannot create alternate data-access logic.

234. Client exports after agency revocation

Agency: retains own accounting records Client: retains entity/public history and authorized client reports Private future access: revoked.

235. Security testing in CI

unit: policy functions integration: DB/RLS e2e: tenant isolation SSRF: blocked IP fixtures upload: malformed/MIME mismatch headers: public pages.

236. Canary secrets

Optional P1: honey/canary credential or file markers can help detect unexpected secret/data access, but never replace normal monitoring.

237. Backup canary

Known restore marker in DB/object repo Restore test: must find it and verify timestamp/version.

238. First 30-day hardening sprint

Week 1: data map, firewall, secrets, MFA Week 2: tenant tests, SSRF, uploads, CSP Week 3: PITR/off-host backup, MinIO copy Week 4: restore drill, incident runbook, privacy/legal gap review.

239. P0 security

MFA admins OIDC secure sessions least privilege workspace authorization RLS selected SSRF controls upload allowlist private object storage Docker secrets firewall audit security logs off-host backup PITR restore test privacy map/policy.

240. P1

advanced DLP AV/quarantine automation object lock external security scan API keys security.txt privileged access reviews staging DAST backup immutable copy privacy request automation.

241. P2

SSO enterprise SCIM dedicated secret manager WAF/CDN central SIEM/security analytics separate crawler host advanced fraud signals formal external pentest cadence secondary DR environment.

242. Что НЕ делать

Не делатьПочему
Хранить backup только на prod hostне переживает host disaster
Считать versioning полноценным backupне защищает от whole-host loss
Отправлять private evidence в внешний LLMprivacy/vendor risk
Разрешать crawler private IP rangesSSRF
Mount Docker socket в apphost compromise
Хранить secrets в Git/.env bundlecredential leak
Использовать app DB role как ownerRLS/privilege bypass
Публиковать raw user HTMLXSS
Считать pg_dump единственным DRweak RPO/recovery
Говорить «мы соответствуем ASVS» без проверкиmisleading security claim

243. Acceptance test: tenant leak

Acme agency user requests Beta file/report Expected: 403 no filename/title leak security/audit record negative test in CI.

244. Acceptance test: SSRF

User submits: http://127.0.0.1:5432 http://169.254.169.254/ private DNS target redirect to 10.0.0.1 Expected: blocked before connection.

245. Acceptance test: upload

evil.exe renamed invoice.pdf Expected: MIME/signature mismatch quarantine/reject never public.

246. Acceptance test: XSS

Article contains: script/onerror/javascript URL Expected: structured renderer/sanitizer removes/escapes CSP provides defense-in-depth.

247. Acceptance test: secret

Worker container: tries read payment secret not assigned to service Expected: not mounted/unavailable.

248. Acceptance test: DB owner

App role: DROP TABLE Expected: permission denied.

249. Acceptance test: backup

Production Postgres volume deleted Expected: restore from off-host base+WAL to target time critical checks pass RPO/RTO measured.

250. Acceptance test: full host loss

Assume: host unavailable Expected: runbook + code repo + secrets recovery + off-host DB/object backups can rebuild product without old host.

251. Acceptance test: deleted object

Moderator accidentally deletes evidence Expected: version/off-host copy allows recovery audit identifies action.

252. Acceptance test: AI private data

Private evidence marked SENSITIVE workflow tries external AI Expected: policy blocks or explicit approved processing path.

253. Acceptance test: compromised session

Agency employee removed Expected: membership revoked sessions invalidated future API denied audit preserved.

254. Acceptance test: payment replay

Provider sends same webhook 3x Expected: signature valid event ID unique one payment transition one credit grant.

255. Acceptance test: old backup restore

Restore backup from before privacy deletion Expected: reconciliation/tombstone process prevents deleted data from silently returning to active service.

256. Security launch checklist

[ ] prod host location legally reviewed [ ] DB/Redis not public [ ] MFA admin [ ] no shared human admin [ ] tenant tests [ ] private file tests [ ] SSRF tests [ ] upload tests [ ] CSP/security headers [ ] secrets outside Git [ ] payment webhook checks [ ] audit [ ] off-host DB backup [ ] WAL continuity [ ] MinIO off-host copy [ ] Authentik backup [ ] restore drill [ ] privacy policy/data map [ ] processor register [ ] external AI data policy [ ] security contact.

257. Main security philosophy

У «Матчасти» нет задачи стать банком по уровню инфраструктуры на первом дне. Есть задача не допустить очевидных архитектурных ошибок, обеспечить минимальный blast radius и доказуемое восстановление.

258. Решение документа

Утвердить security/privacy/backup baseline. Mathchast uses OWASP ASVS 5.0 as internal application-security verification framework and NIST CSF 2.0 as risk-management structure. Auth remains in Authentik/OIDC; Mathchast does not store passwords and requires MFA for privileged roles. Server-side authorization, workspace scoping, selected PostgreSQL RLS, dedicated runtime roles and negative cross-tenant tests protect Agency data. User HTML is rendered only through structured/sanitized content. Crawler/browser workers are isolated and must block loopback/private/link-local/metadata destinations, validate DNS and every redirect to prevent SSRF. Uploads use file-type allowlists, signature/MIME validation, size/resource limits, random object keys and separate public/private storage policies. Secrets use service-scoped Docker secrets/protected files and are never committed to Git. External AI providers receive only public/non-sensitive input by default; private evidence/personal data require explicit approved vendor/legal processing. Russian 152-ФЗ privacy work is a hard launch gate, including verification of database physical location/localization requirements and processor/cross-border data flows. PostgreSQL recovery is based on continuous WAL archiving + base backups/PITR using pgBackRest or WAL-G, supplemented by logical dumps. Backup repository must be off-host and encrypted; a second independent copy/failure domain is strongly recommended. MinIO versioning protects against accidental overwrite/delete but does not replace off-host backup. Authentik database is included in DR. Initial targets are roughly RPO ≤15 min for core DB and RTO ≤4 h for core public/API, but these become real only after measured restore drills. Weekly automated restore, monthly PITR test and periodic full-host disaster drill are required. Security is considered launch-ready only when backups have actually been restored, tenant isolation is tested, sensitive vendor flows are mapped, and critical controls are auditable.

259. Что этот документ разблокирует

Mathchast_41 Security / Privacy / Backups → Mathchast_42 Monitoring / SLA / Incidents → Mathchast_43 MVP Scope / Roadmap

Источники исследования

RPO/RTO targets, backup schedule/retention counts, exact service hardening choices and phased P0/P1/P2 controls are Mathchast project recommendations. They require real restore/security testing before becoming contractual SLA. This document is not legal advice: Russian personal-data localization, operator notification duties, processing legal bases, transfer to foreign providers and incident notifications must be reviewed against the exact launch data flows and current law by qualified counsel.