podman

Форк
0
/
policy_test.go 
196 строк · 5.6 Кб
1
package trust
2

3
import (
4
	"encoding/json"
5
	"os"
6
	"path/filepath"
7
	"testing"
8

9
	"github.com/containers/image/v5/signature"
10
	"github.com/stretchr/testify/assert"
11
	"github.com/stretchr/testify/require"
12
)
13

14
func TestAddPolicyEntries(t *testing.T) {
15
	tempDir := t.TempDir()
16
	policyPath := filepath.Join(tempDir, "policy.json")
17

18
	minimalPolicy := &signature.Policy{
19
		Default: []signature.PolicyRequirement{
20
			signature.NewPRInsecureAcceptAnything(),
21
		},
22
	}
23
	minimalPolicyJSON, err := json.Marshal(minimalPolicy)
24
	require.NoError(t, err)
25
	err = os.WriteFile(policyPath, minimalPolicyJSON, 0600)
26
	require.NoError(t, err)
27

28
	// Invalid input:
29
	for _, invalid := range []AddPolicyEntriesInput{
30
		{
31
			Scope:       "default",
32
			Type:        "accept",
33
			PubKeyFiles: []string{"/does-not-make-sense"},
34
		},
35
		{
36
			Scope:       "default",
37
			Type:        "insecureAcceptAnything",
38
			PubKeyFiles: []string{"/does-not-make-sense"},
39
		},
40
		{
41
			Scope:       "default",
42
			Type:        "reject",
43
			PubKeyFiles: []string{"/does-not-make-sense"},
44
		},
45
		{
46
			Scope:       "default",
47
			Type:        "signedBy",
48
			PubKeyFiles: []string{}, // A key is missing
49
		},
50
		{
51
			Scope:       "default",
52
			Type:        "sigstoreSigned",
53
			PubKeyFiles: []string{}, // A key is missing
54
		},
55
		{
56
			Scope:       "default",
57
			Type:        "this-is-unknown",
58
			PubKeyFiles: []string{},
59
		},
60
	} {
61
		err := AddPolicyEntries(policyPath, invalid)
62
		assert.Error(t, err, "%#v", invalid)
63
	}
64

65
	err = AddPolicyEntries(policyPath, AddPolicyEntriesInput{
66
		Scope: "default",
67
		Type:  "reject",
68
	})
69
	assert.NoError(t, err)
70
	err = AddPolicyEntries(policyPath, AddPolicyEntriesInput{
71
		Scope: "quay.io/accepted",
72
		Type:  "accept",
73
	})
74
	assert.NoError(t, err)
75
	err = AddPolicyEntries(policyPath, AddPolicyEntriesInput{
76
		Scope:       "quay.io/multi-signed",
77
		Type:        "signedBy",
78
		PubKeyFiles: []string{"/1.pub", "/2.pub"},
79
	})
80
	assert.NoError(t, err)
81
	err = AddPolicyEntries(policyPath, AddPolicyEntriesInput{
82
		Scope:       "quay.io/sigstore-signed",
83
		Type:        "sigstoreSigned",
84
		PubKeyFiles: []string{"/1.pub", "/2.pub"},
85
	})
86
	assert.NoError(t, err)
87

88
	// Test that the outcome is consumable, and compare it with the expected values.
89
	parsedPolicy, err := signature.NewPolicyFromFile(policyPath)
90
	require.NoError(t, err)
91
	assert.Equal(t, &signature.Policy{
92
		Default: signature.PolicyRequirements{
93
			signature.NewPRReject(),
94
		},
95
		Transports: map[string]signature.PolicyTransportScopes{
96
			"docker": {
97
				"quay.io/accepted": {
98
					signature.NewPRInsecureAcceptAnything(),
99
				},
100
				"quay.io/multi-signed": {
101
					xNewPRSignedByKeyPath(t, "/1.pub", signature.NewPRMMatchRepoDigestOrExact()),
102
					xNewPRSignedByKeyPath(t, "/2.pub", signature.NewPRMMatchRepoDigestOrExact()),
103
				},
104
				"quay.io/sigstore-signed": {
105
					xNewPRSigstoreSignedKeyPath(t, "/1.pub", signature.NewPRMMatchRepoDigestOrExact()),
106
					xNewPRSigstoreSignedKeyPath(t, "/2.pub", signature.NewPRMMatchRepoDigestOrExact()),
107
				},
108
			},
109
		},
110
	}, parsedPolicy)
111

112
	// Test that completely unknown JSON is preserved
113
	jsonWithUnknownData := `{
114
    "default": [
115
        {
116
            "type": "this is unknown",
117
			"unknown field": "should be preserved"
118
        }
119
    ],
120
    "transports":
121
        {
122
            "docker-daemon":
123
                {
124
                    "": [{
125
						"type":"this is unknown 2",
126
						"unknown field 2": "should be preserved 2"
127
						}]
128
                }
129
        }
130
}`
131
	err = os.WriteFile(policyPath, []byte(jsonWithUnknownData), 0600)
132
	require.NoError(t, err)
133
	err = AddPolicyEntries(policyPath, AddPolicyEntriesInput{
134
		Scope:       "quay.io/innocuous",
135
		Type:        "signedBy",
136
		PubKeyFiles: []string{"/1.pub"},
137
	})
138
	require.NoError(t, err)
139
	updatedJSONWithUnknownData, err := os.ReadFile(policyPath)
140
	require.NoError(t, err)
141
	// Decode updatedJSONWithUnknownData so that this test does not depend on details of the encoding.
142
	// To reduce noise in the constants below:
143
	type a = []interface{}
144
	type m = map[string]interface{}
145
	var parsedUpdatedJSON m
146
	err = json.Unmarshal(updatedJSONWithUnknownData, &parsedUpdatedJSON)
147
	require.NoError(t, err)
148
	assert.Equal(t, m{
149
		"default": a{
150
			m{
151
				"type":          "this is unknown",
152
				"unknown field": "should be preserved",
153
			},
154
		},
155
		"transports": m{
156
			"docker-daemon": m{
157
				"": a{
158
					m{
159
						"type":            "this is unknown 2",
160
						"unknown field 2": "should be preserved 2",
161
					},
162
				},
163
			},
164
			"docker": m{
165
				"quay.io/innocuous": a{
166
					m{
167
						"type":    "signedBy",
168
						"keyType": "GPGKeys",
169
						"keyPath": "/1.pub",
170
					},
171
				},
172
			},
173
		},
174
	}, parsedUpdatedJSON)
175
}
176

177
// xNewPRSignedByKeyPath is a wrapper for NewPRSignedByKeyPath which must not fail.
178
func xNewPRSignedByKeyPath(t *testing.T, keyPath string, signedIdentity signature.PolicyReferenceMatch) signature.PolicyRequirement {
179
	pr, err := signature.NewPRSignedByKeyPath(signature.SBKeyTypeGPGKeys, keyPath, signedIdentity)
180
	require.NoError(t, err)
181
	return pr
182
}
183

184
// xNewPRSignedByKeyPaths is a wrapper for NewPRSignedByKeyPaths which must not fail.
185
func xNewPRSignedByKeyPaths(t *testing.T, keyPaths []string, signedIdentity signature.PolicyReferenceMatch) signature.PolicyRequirement {
186
	pr, err := signature.NewPRSignedByKeyPaths(signature.SBKeyTypeGPGKeys, keyPaths, signedIdentity)
187
	require.NoError(t, err)
188
	return pr
189
}
190

191
// xNewPRSigstoreSignedKeyPath is a wrapper for NewPRSigstoreSignedKeyPath which must not fail.
192
func xNewPRSigstoreSignedKeyPath(t *testing.T, keyPath string, signedIdentity signature.PolicyReferenceMatch) signature.PolicyRequirement {
193
	pr, err := signature.NewPRSigstoreSignedKeyPath(keyPath, signedIdentity)
194
	require.NoError(t, err)
195
	return pr
196
}
197

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.