-
Notifications
You must be signed in to change notification settings - Fork 110
/
trusted_env.go
38 lines (32 loc) · 1.08 KB
/
trusted_env.go
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
package utils
import (
"context"
"sync/atomic"
"github.com/pkg/errors"
)
type ctxKey byte
const ctxKeyTrusted ctxKey = iota
// IsTrustedEnvironment is used to check the trusted state of the runtime.
// Note: by default, if no context is set up, trust is assumed; be careful.
func IsTrustedEnvironment(ctx context.Context) bool {
val, has := ctx.Value(ctxKeyTrusted).(*atomic.Bool)
return !has || val != nil && val.Load()
}
// WithTrustedEnvironment is used to inform environment trust across boundaries.
func WithTrustedEnvironment(ctx context.Context, trusted bool) (context.Context, error) {
alreadySet := ctx.Value(ctxKeyTrusted)
if alreadySet != nil {
currentTrust, ok := alreadySet.(*atomic.Bool)
if !ok || currentTrust == nil {
return nil, errors.Errorf("trust value is not a bool but %v (%T)", alreadySet, alreadySet)
}
if !currentTrust.Load() && trusted {
return nil, errors.New("cannot elevate trust")
}
currentTrust.Store(trusted)
return ctx, nil
}
var newTrust atomic.Bool
newTrust.Store(trusted)
return context.WithValue(ctx, ctxKeyTrusted, &newTrust), nil
}