Skip to content

Commit 1508e30

Browse files
feat(build, secrets): include plain secret values in giterminism scope (#6495)
Signed-off-by: Yaroslav Pershin <62902094+iapershin@users.noreply.github.com> Co-authored-by: Aleksei Igrychev <alexey.igrychev@flant.com>
1 parent ebe3e4b commit 1508e30

File tree

13 files changed

+131
-2
lines changed

13 files changed

+131
-2
lines changed

docs/_data/werf_giterminism_yaml.yml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ directives:
5353
ru: Правила использования значений секретов
5454
directives:
5555
- name: allowEnvVariables
56-
value: "[ string || /REGEXP/, ... ]"
56+
value: "[ string, ... ]"
5757
description:
5858
en: Allow the use of specific environment variables as secrets
5959
ru: Разрешить использование определённых переменных окружения в качестве секретов
@@ -62,6 +62,11 @@ directives:
6262
description:
6363
en: Allow the use of specific paths to files as secrets
6464
ru: Разрешить использование определённых путей к файлам в качестве секретов
65+
- name: allowValueIds
66+
value: "[ string, ... ]"
67+
description:
68+
en: Allow the use of specific identifiers of arbitrary secret values
69+
ru: Разрешить использование определённых идентификаторов произвольных значений секретов
6570
- name: stapel
6671
description:
6772
en: The rules for the stapel image

docs/pages_en/usage/build/images.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,8 @@ In the example above, werf will use the Dockerfile at `docs/Dockerfile` to build
131131

132132
#### Using build secrets
133133

134+
> **NOTE:** To use secrets in builds, you need to enable them explicitly in the giterminism settings. Learn more ([here]({{ "/usage/project_configuration/giterminism.html#using-build-secrets" | true_relative_url }}))
135+
134136
A build secret is any sensitive information, such as a password or API token, required during the build process of your application.
135137

136138
Build arguments and environment variables are not suitable for passing secrets to the build process, as they are retained in the final image.
@@ -153,6 +155,20 @@ secrets:
153155
value: plainSecretValue
154156
```
155157

158+
```yaml
159+
# werf-giterminism.yaml
160+
giterminismConfigVersion: 1
161+
162+
config:
163+
secrets:
164+
allowEnvVariables:
165+
- "AWS_ACCESS_KEY_ID"
166+
allowFiles:
167+
- "~/.aws/credentials"
168+
allowValueIds:
169+
- plainSecret
170+
```
171+
156172
To access a secret during the build, use the `--mount=type=secret` flag in the Dockerfile's `RUN` instructions.
157173

158174
When a secret is mounted, it is available as a file by default. The default mount path for the secret file inside the build container is `/run/secrets/<id>`. If an `id` is not specified for a secret in `werf.yaml`, the default value is assigned automatically:

docs/pages_en/usage/build/stapel/instructions.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,12 +342,18 @@ In the example above the current commit hash will be inserted into the `echo ...
342342

343343
## Using build secrets
344344

345+
> **NOTE:** To use secrets in builds, you need to enable them explicitly in the giterminism settings. Learn more ([here]({{ "/usage/project_configuration/giterminism.html#using-build-secrets" | true_relative_url }}))
346+
345347
A build secret is any confidential information, such as a password or API token, used during the build process of your application.
346348

347349
Build arguments and environment variables are not suitable for passing secrets during a build, as they may be retained in the final image.
348350
You can use secrets during the build process by defining them in `werf.yaml`.
349351

350352
```yaml
353+
# werf.yaml
354+
project: example
355+
configVersion: 1
356+
---
351357
image: stapel-shell
352358
from: ubuntu:22.04
353359
secrets:
@@ -359,6 +365,20 @@ secrets:
359365
value: plainSecretValue
360366
```
361367

368+
```yaml
369+
# werf-giterminism.yaml
370+
giterminismConfigVersion: 1
371+
372+
config:
373+
secrets:
374+
allowEnvVariables:
375+
- "AWS_ACCESS_KEY_ID"
376+
allowFiles:
377+
- "~/.aws/credentials"
378+
allowValueIds:
379+
- plainSecret
380+
```
381+
362382
When using a secret in Stapel instructions, the secret is mounted to a file. The path for the secret file inside the build container is `/run/secrets/<id>`. If an `id` is not specified for a secret in `werf.yaml`, the default value is assigned automatically:
363383

364384
- For `env`, the `id` defaults to the name of the environment variable.
@@ -367,6 +387,10 @@ When using a secret in Stapel instructions, the secret is mounted to a file. The
367387
> For `value` — the `id` field is mandatory.
368388

369389
```yaml
390+
# werf.yaml
391+
project: example
392+
configVersion: 1
393+
---
370394
image: stapel-shell
371395
from: ubuntu:22.04
372396
secrets:

docs/pages_en/usage/project_configuration/giterminism.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,18 @@ The use of the [fromPath]({{"usage/build/stapel/mounts.html" | true_relative_url
8181

8282
The `fromPath` directive can be activated using [werf-giterminism.yaml]({{"reference/werf_giterminism_yaml.html" | true_relative_url }}), but we strongly recommend that you carefully consider the possible implications of this.
8383

84+
#### Using build secrets
85+
86+
The use of secrets complicates the sharing and reproducibility of configuration in CI jobs and among developers.
87+
88+
To manage secrets and ensure their consistent use, you can configure the [werf-giterminism.yaml]({{ "reference/werf_giterminism_yaml.html" | true_relative_url }}) file with the following:
89+
90+
- `allowEnvVariables` — allows the use of specific environment variables.
91+
- `allowFiles` — grants access to secrets stored in specified files.
92+
- `allowValueIds` — enables the use of arbitrary secret values identified by IDs.
93+
94+
We strongly recommend carefully considering the potential implications and avoiding the use of secrets unless absolutely necessary.
95+
8496
### Deploying
8597

8698
#### The --use-custom-tag option

docs/pages_ru/usage/build/images.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,8 @@ dockerfile: Dockerfile
131131

132132
#### Использование сборочных секретов
133133

134+
> **ЗАМЕЧАНИЕ:** Чтобы использовать секреты в сборках, их нужно явно разрешить в настройках гитерминизма. Подробнее ([здесь]({{ "/usage/project_configuration/giterminism.html#использование-сборочных-секретов" | true_relative_url }}))
135+
134136
Секрет сборки — это любая конфиденциальная информация, например пароль или токен API, используемая в процессе сборки вашего приложения.
135137

136138
Аргументы сборки и переменные окружения не подходят для передачи секретов в сборку, поскольку они сохраняются в конечном образе.
@@ -152,6 +154,19 @@ secrets:
152154
- id: plainSecret
153155
value: plainSecretValue
154156
```
157+
```yaml
158+
# werf-giterminism.yaml
159+
giterminismConfigVersion: 1
160+
161+
config:
162+
secrets:
163+
allowEnvVariables:
164+
- "AWS_ACCESS_KEY_ID"
165+
allowFiles:
166+
- "~/.aws/credentials"
167+
allowValueIds:
168+
- plainSecret
169+
```
155170

156171
Чтобы использовать секрет в сборке и сделать его доступным для инструкции `RUN`, используйте флаг `--mount=type=secret` в Dockerfile.
157172

docs/pages_ru/usage/build/stapel/instructions.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,12 +364,18 @@ shell:
364364

365365
## Использование сборочных секретов
366366

367+
> **ЗАМЕЧАНИЕ:** Чтобы использовать секреты в сборках, их нужно явно разрешить в настройках гитерминизма. Подробнее ([здесь]({{ "/usage/project_configuration/giterminism.html#использование-сборочных-секретов" | true_relative_url }}))
368+
367369
Секрет сборки — это любая конфиденциальная информация, например пароль или токен API, используемая в процессе сборки вашего приложения.
368370

369371
Аргументы сборки и переменные окружения не подходят для передачи секретов в сборку, поскольку они сохраняются в конечном образе.
370372
Вы можете использовать секреты при сборке, описав их в `werf.yaml`.
371373

372374
```yaml
375+
# werf.yaml
376+
project: example
377+
configVersion: 1
378+
---
373379
image: stapel-shell
374380
from: ubuntu:22.04
375381
secrets:
@@ -381,6 +387,20 @@ secrets:
381387
value: plainSecretValue
382388
```
383389

390+
```yaml
391+
# werf-giterminism.yaml
392+
giterminismConfigVersion: 1
393+
394+
config:
395+
secrets:
396+
allowEnvVariables:
397+
- "AWS_ACCESS_KEY_ID"
398+
allowFiles:
399+
- "~/.aws/credentials"
400+
allowValueIds:
401+
- plainSecret
402+
```
403+
384404
При использовании секрета в Stapel инструкциях, секрет монтируется в файл по умолчанию. Путь к файлу секрета по умолчанию внутри контейнера сборки — `/run/secrets/<id>`. Если `id` секрета явно не указан в `werf.yaml`, то в качестве `id` будет использовано значение по умолчанию:
385405

386406
- Для `env` — имя переменной окружения.

docs/pages_ru/usage/project_configuration/giterminism.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,18 @@ werf не позволяет работать с незакоммиченным
8181

8282
Для активации директивы `fromPath` необходимо использовать [werf-giterminism.yaml]({{ "reference/werf_giterminism_yaml.html" | true_relative_url }}), но мы рекомендуем еще раз подумать о возможных последствиях.
8383

84+
#### Использование сборочных секретов
85+
86+
Использование секретов усложняет совместное использование и воспроизводимость конфигурации в заданиях CI и среди разработчиков.
87+
88+
Чтобы управлять секретами и обеспечить их согласованное использование, в файле [werf-giterminism.yaml]({{ "reference/werf_giterminism_yaml.html" | true_relative_url }}) можно настроить:
89+
90+
- `allowEnvVariables` — разрешение использования определённых переменных окружения.
91+
- `allowFiles` — доступ к секретам из указанных файлов.
92+
- `allowValueIds` — использование произвольных значений секретов по идентификаторам.
93+
94+
Мы рекомендуем еще раз подумать о возможных последствиях и не использовать секреты без реальной необходимости.
95+
8496
### Развёртывание
8597

8698
#### Опция --use-custom-tag

pkg/config/secrets.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ func (s *SecretFromSrc) InspectByGiterminism(giterminismManager giterminism_mana
130130
}
131131

132132
func (s *SecretFromPlainValue) InspectByGiterminism(giterminismManager giterminism_manager.Interface) error {
133-
return nil
133+
return giterminismManager.Inspector().InspectConfigSecretValueAccepted(s.Id)
134134
}
135135

136136
func GetValidatedSecrets(rawSecrets []*rawSecret, giterminismManager giterminism_manager.Interface, doc *doc) ([]Secret, error) {

pkg/giterminism_manager/config/config.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,10 @@ func (c Config) IsConfigSecretSrcAccepted(path string) bool {
110110
return c.Config.Secrets.IsAllowSecretsFileAccepted(path)
111111
}
112112

113+
func (c Config) IsConfigSecretValueAccepted(path string) bool {
114+
return c.Config.Secrets.IsValueIdAccepted(path)
115+
}
116+
113117
type cli struct {
114118
AllowCustomTags bool `json:"allowCustomTags"`
115119
}
@@ -223,6 +227,7 @@ func pathMatcher(patterns []string) path_matcher.PathMatcher {
223227
type secrets struct {
224228
AllowEnvVariables []string `json:"allowEnvVariables"`
225229
AllowFiles []string `json:"allowFiles"`
230+
AllowValueIds []string `json:"allowValueIds"`
226231
}
227232

228233
func (s *secrets) IsEnvNameAccepted(name string) bool {
@@ -233,6 +238,10 @@ func (s *secrets) IsAllowSecretsFileAccepted(path string) bool {
233238
return isAbsPathMatched(s.AllowFiles, path)
234239
}
235240

241+
func (s *secrets) IsValueIdAccepted(name string) bool {
242+
return slices.Contains(s.AllowValueIds, name)
243+
}
244+
236245
func isAbsPathMatched(patterns []string, p string) bool {
237246
absPath := make([]string, 0, len(patterns))
238247
for _, p := range patterns {

pkg/giterminism_manager/inspector/config_secrets.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,15 @@ func (i Inspector) InspectConfigSecretSrcAccepted(secret string) error {
3131

3232
return NewExternalDependencyFoundError(fmt.Sprintf(secretsErrMsg, secret))
3333
}
34+
35+
func (i Inspector) InspectConfigSecretValueAccepted(secret string) error {
36+
if i.sharedOptions.LooseGiterminism() {
37+
return nil
38+
}
39+
40+
if i.giterminismConfig.IsConfigSecretValueAccepted(secret) {
41+
return nil
42+
}
43+
44+
return NewExternalDependencyFoundError(fmt.Sprintf(secretsErrMsg, secret))
45+
}

0 commit comments

Comments
 (0)