-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathsignaturedispatcher.go
201 lines (176 loc) · 6.65 KB
/
signaturedispatcher.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package server
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
kapierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctxu "github.com/docker/distribution/context"
"github.com/docker/distribution/context"
"github.com/docker/distribution/registry/api/errcode"
"github.com/docker/distribution/registry/api/v2"
"github.com/docker/distribution/registry/handlers"
"github.com/openshift/image-registry/pkg/dockerregistry/server/client"
imageapi "github.com/openshift/origin/pkg/image/apis/image"
imageapiv1 "github.com/openshift/origin/pkg/image/apis/image/v1"
gorillahandlers "github.com/gorilla/handlers"
)
const (
errGroup = "registry.api.v2"
defaultSchemaVersion = 2
)
// signature represents a Docker image signature.
type signature struct {
// Version specifies the schema version
Version int `json:"schemaVersion"`
// Name must be in "sha256:<digest>@signatureName" format
Name string `json:"name"`
// Type is optional, of not set it will be defaulted to "AtomicImageV1"
Type string `json:"type"`
// Content contains the signature
Content []byte `json:"content"`
}
// signatureList represents list of Docker image signatures.
type signatureList struct {
Signatures []signature `json:"signatures"`
}
var (
ErrorCodeSignatureInvalid = errcode.Register(errGroup, errcode.ErrorDescriptor{
Value: "SIGNATURE_INVALID",
Message: "invalid image signature",
HTTPStatusCode: http.StatusBadRequest,
})
ErrorCodeSignatureAlreadyExists = errcode.Register(errGroup, errcode.ErrorDescriptor{
Value: "SIGNATURE_EXISTS",
Message: "image signature already exists",
HTTPStatusCode: http.StatusConflict,
})
)
type signatureHandler struct {
ctx *handlers.Context
reference imageapi.DockerImageReference
isImageClient client.ImageStreamImagesNamespacer
}
// NewSignatureDispatcher provides a function that handles the GET and PUT
// requests for signature endpoint.
func NewSignatureDispatcher(isImageClient client.ImageStreamImagesNamespacer) func(*handlers.Context, *http.Request) http.Handler {
return func(ctx *handlers.Context, r *http.Request) http.Handler {
reference, _ := imageapi.ParseDockerImageReference(
ctxu.GetStringValue(ctx, "vars.name") + "@" + ctxu.GetStringValue(ctx, "vars.digest"),
)
signatureHandler := &signatureHandler{
ctx: ctx,
isImageClient: isImageClient,
reference: reference,
}
return gorillahandlers.MethodHandler{
"GET": http.HandlerFunc(signatureHandler.Get),
"PUT": http.HandlerFunc(signatureHandler.Put),
}
}
}
func (s *signatureHandler) Put(w http.ResponseWriter, r *http.Request) {
context.GetLogger(s.ctx).Debugf("(*signatureHandler).Put")
if len(s.reference.String()) == 0 {
s.handleError(s.ctx, v2.ErrorCodeNameInvalid.WithDetail("missing image name or image ID"), w)
return
}
client, ok := userClientFrom(s.ctx)
if !ok {
s.handleError(s.ctx, errcode.ErrorCodeUnknown.WithDetail("unable to get origin client"), w)
return
}
sig := signature{}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
s.handleError(s.ctx, ErrorCodeSignatureInvalid.WithDetail(err.Error()), w)
return
}
if err := json.Unmarshal(body, &sig); err != nil {
s.handleError(s.ctx, ErrorCodeSignatureInvalid.WithDetail(err.Error()), w)
return
}
if len(sig.Type) == 0 {
sig.Type = imageapi.ImageSignatureTypeAtomicImageV1
}
if sig.Version != defaultSchemaVersion {
s.handleError(s.ctx, ErrorCodeSignatureInvalid.WithDetail(errors.New("only schemaVersion=2 is currently supported")), w)
return
}
newSig := &imageapiv1.ImageSignature{Content: sig.Content, Type: sig.Type}
newSig.Name = sig.Name
_, err = client.ImageSignatures().Create(newSig)
switch {
case err == nil:
case kapierrors.IsUnauthorized(err):
s.handleError(s.ctx, errcode.ErrorCodeUnauthorized.WithDetail(err.Error()), w)
return
case kapierrors.IsBadRequest(err):
s.handleError(s.ctx, ErrorCodeSignatureInvalid.WithDetail(err.Error()), w)
return
case kapierrors.IsNotFound(err):
w.WriteHeader(http.StatusNotFound)
return
case kapierrors.IsAlreadyExists(err):
s.handleError(s.ctx, ErrorCodeSignatureAlreadyExists.WithDetail(err.Error()), w)
return
default:
s.handleError(s.ctx, errcode.ErrorCodeUnknown.WithDetail(fmt.Sprintf("unable to create image %s signature: %v", s.reference.String(), err)), w)
return
}
// Return just 201 with no body.
// TODO: The docker registry actually returns the Location header
w.WriteHeader(http.StatusCreated)
context.GetLogger(s.ctx).Debugf("(*signatureHandler).Put signature successfully added to %s", s.reference.String())
}
func (s *signatureHandler) Get(w http.ResponseWriter, req *http.Request) {
context.GetLogger(s.ctx).Debugf("(*signatureHandler).Get")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if len(s.reference.String()) == 0 {
s.handleError(s.ctx, v2.ErrorCodeNameInvalid.WithDetail("missing image name or image ID"), w)
return
}
if len(s.reference.ID) == 0 {
s.handleError(s.ctx, v2.ErrorCodeNameInvalid.WithDetail("the image ID must be specified (sha256:<digest>"), w)
return
}
image, err := s.isImageClient.ImageStreamImages(s.reference.Namespace).Get(imageapi.JoinImageStreamImage(s.reference.Name, s.reference.ID), metav1.GetOptions{})
switch {
case err == nil:
case kapierrors.IsUnauthorized(err):
s.handleError(s.ctx, errcode.ErrorCodeUnauthorized.WithDetail(fmt.Sprintf("not authorized to get image %q signature: %v", s.reference.String(), err)), w)
return
case kapierrors.IsNotFound(err):
w.WriteHeader(http.StatusNotFound)
return
default:
s.handleError(s.ctx, errcode.ErrorCodeUnknown.WithDetail(fmt.Sprintf("unable to get image %q signature: %v", s.reference.String(), err)), w)
return
}
// Transform the OpenShift ImageSignature into Registry signature object.
signatures := signatureList{Signatures: []signature{}}
for _, s := range image.Image.Signatures {
signatures.Signatures = append(signatures.Signatures, signature{
Version: defaultSchemaVersion,
Name: s.Name,
Type: s.Type,
Content: s.Content,
})
}
if data, err := json.Marshal(signatures); err != nil {
s.handleError(s.ctx, errcode.ErrorCodeUnknown.WithDetail(fmt.Sprintf("failed to serialize image signature %v", err)), w)
} else {
// TODO(dmage): log error?
_, _ = w.Write(data)
}
}
func (s *signatureHandler) handleError(ctx context.Context, err error, w http.ResponseWriter) {
context.GetLogger(ctx).Errorf("(*signatureHandler): %v", err)
ctx, w = context.WithResponseWriter(ctx, w)
if serveErr := errcode.ServeJSON(w, err); serveErr != nil {
context.GetResponseLogger(ctx).Errorf("error sending error response: %v", serveErr)
return
}
}