Security

From SteelMorgan/1c-agent-based-dev-framework · View interactive version

Security is an AI agent skill from the GitHub repository SteelMorgan/1c-agent-based-dev-framework. For secrets, tokens, TLS, signatures, and 1C privileges

How to use this skill

Skill file

1C Security: secrets, authentication, cryptography

This skill is a map of topics on the security of 1C application code. Platform API specifics are moved into references/. Here are the trust boundaries, typical mistakes, and stop-rules that any agent (architect / developer-code / reviewer) must follow when working with sensitive data.

Security in 1C is not a separate subsystem, but an end-to-end property of the code:


When to apply

| Trigger | Action |

|---------|----------|

| You see work with a password/token/secret in a procedure parameter or in a code string | Read references/secrets.md, move it to БезопасноеХранилище, check masking in logs |

| You see work with МенеджерКриптографии, СертификатКриптографии, ХранилищеСертификатовКриптографии, or ПараметрыПодписиCMS | Read references/crypto.md, check the provider, GOST version, context (client/server), and the private key lifecycle |

| You see an HTTP call to an external API, OpenID/OAuth, basic-auth, or a client TLS certificate | Read references/auth.md, check error semantics and credential storage |

| You are reviewing code that touches rights, RLS, privileged mode, or external integrations | Use references/review-checklist.md as a mandatory filter before the final answer |

| You need to design a new integration/service with authentication | First define the trust boundary (see below), then choose the API |


Trust boundaries

Before writing or reviewing code, explicitly define which boundary it crosses:

  1. User → 1C server — platform authentication, roles, RLS, data separation.
  2. 1C client → 1C server — procedure parameters cross the network boundary (see the stop-rule about passwords).
  3. 1C server → external API — HTTPСоединение, OpenID/OAuth, client certificate, TLS.
  4. 1C server → OS / cryptography provider — МенеджерКриптографии, CryptoPro CSP / ViPNet, access to the certificate store under the rphost/srv1cv8 account.
  5. 1C server → persistent secret storage — БезопасноеХранилище, or an external vault through a connector.

If the boundary is not named, the skill is applied incorrectly: go back to the design stage.


Topics and where to look

1. Secrets and `БезопасноеХранилище` → [`references/secrets.md`](references/secrets.md)

2. Cryptography and digital signatures → [`references/crypto.md`](references/crypto.md)

3. Authentication and external APIs → [`references/auth.md`](references/auth.md)

4. Review checklist → [`references/review-checklist.md`](references/review-checklist.md)

A stack-neutral checklist that the agent-reviewer must pass before the final answer if the code touches any of the topics above.


Stop rules (1C-specific)

These rules are strict. A violation means a blocking review comment and code rewrite.

  1. A password/token/private key must not be passed through a procedure parameter that has a "client ↔ server" boundary
  1. A private key / cryptography container is not stored in a common module, directory attribute, or constant
  1. УстановитьПривилегированныйРежим(Истина) around work with БезопасноеХранилище is mandatory and targeted
  1. Logs and the registration log do not contain tokens, passwords, private keys, or full Authorization headers
  1. An authentication error is different from a validation error and a business error

Usage scenarios

Scenario 1: A new integration module with OAuth

Context: You need to call an external REST API with OAuth 2.0 (client credentials).

Steps:

  1. Name the trust boundary: "1C server → external API".
  2. Create an account directory; client_secret and refresh_token go into БезопасноеХранилище, owner = reference to the directory item.
  3. Read the secret on the server, in a targeted way under УстановитьПривилегированныйРежим.
  4. Build the Authorization header on the server; the header is not returned to the client.
  5. Define error semantics: expired token → refresh, invalid client → configuration error (no retry), provider unavailable → retry with backoff.
  6. Logs: client_id is visible, client_secret/access_token are masked (last 4 characters).
  7. Run references/review-checklist.md.

Scenario 2: Signing a CMS document

Context: You need to sign XML/PDF with a qualified digital signature under GOST R 34.10-2012.

Steps:

  1. Trust boundary: "1C server → CryptoPro CSP" (or ViPNet).
  2. If БСП "Электронная подпись" is in the configuration, use its modules, do not write your own МенеджерКриптографии manually.
  3. If БСП is not present, use МенеджерКриптографии("Crypto-Pro GOST R 34.10-2012 Cryptographic Service Provider", 80) with an explicit ТипПровайдера.
  4. Take the certificate by fingerprint (Отпечаток), not by "the first suitable one".
  5. ПараметрыПодписиCMS (detached/attached, encoding).
  6. The private key container is available under the rphost account - check it in the deployment checklist, not in code.
  7. Do not log ДанныеПодписи in full; log the certificate Отпечаток and the business object identifier.

Scenario 3: Reviewing a pull request that touches rights

Context: A УстановитьПривилегированныйРежим(Истина) appeared in the PR.

Steps:

  1. Find the paired УстановитьПривилегированныйРежим(Ложь) in the same scope and in Попытка/Исключение.
  2. Check that inside the privileged block there is only access to the secret/system table, not the entire business logic.
  3. Check that the result does not leak into a form/report without an explicit check of the current user's rights.
  4. Run references/review-checklist.md.

Examples

Correct

// Сервер. Чтение токена внешнего API из безопасного хранилища.
// Привилегированный режим — точечный, только вокруг чтения секрета.
Функция ПолучитьТокенДоступа(УчётнаяЗапись) Экспорт

    УстановитьПривилегированныйРежим(Истина);
    Попытка
        ДанныеСекрета = ОбщегоНазначения.ПрочитатьДанныеИзБезопасногоХранилища(УчётнаяЗапись, "access_token");
    Исключение
        УстановитьПривилегированныйРежим(Ложь);
        ВызватьИсключение;
    КонецПопытки;
    УстановитьПривилегированныйРежим(Ложь);

    Если ДанныеСекрета = Неопределено Тогда
        ВызватьИсключение НСтр("ru = 'Токен не настроен для учётной записи.'");
    КонецЕсли;

    Возврат ДанныеСекрета;

КонецФункции

Incorrect

// АНТИПАТТЕРН: пароль пересекает границу клиент/сервер в открытом параметре.
// АНТИПАТТЕРН: пароль попадает в журнал регистрации.
&НаСервереБезКонтекста
Функция ОтправитьДокумент(URL, Логин, Пароль, ТелоЗапроса) Экспорт

    ЗаписьЖурналаРегистрации("Интеграция",
        УровеньЖурналаРегистрации.Информация,
        ,
        ,
        "Отправка: URL=" + URL + ", Логин=" + Логин + ", Пароль=" + Пароль);

    // ... вызов внешнего API ...

КонецФункции

Typical mistakes

| Mistake | Consequence | How to avoid |

|--------|-------------|--------------|

| Password/token in the parameter of an exported server procedure | Leak over the network, in dumps, in client logs | Pass only the secret owner (reference), read the secret on the server |

| УстановитьПривилегированныйРежим(Истина) for the whole module/function | Bypassing RLS and role checks across all business logic | A targeted block only around work with БезопасноеХранилище |

| Storing access_token in a directory attribute / constant / layout | Any user with directory read permission gets the token | БезопасноеХранилище + owner = reference to the directory item |

| МенеджерКриптографии() without an explicit provider and type | The code works in the test environment, fails in production with a different provider | Explicit ИмяПровайдера + ТипПровайдера, GOST version fixed |

| The certificate is chosen as "the first one in the store" | Signature with the wrong certificate at rotation time | Search strictly by Отпечаток |

| 401 from an external API → Сообщить("Ошибка при сохранении") | It is impossible to distinguish an expired token from a data error | Separate authentication error type + refresh handling |

| Logging the entire HTTP request/response body | Passwords/tokens/PII are stored in the registration log | Sanitization before logging, masking sensitive fields |


Related resources


depends_on: []


Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.