/
server.go
236 lines (203 loc) · 5.98 KB
/
server.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package ccptest
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"math/rand"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"time"
)
// Server is a mock CCP WebService implementation for testing purposes
type Server struct {
// Host is the hostname with an optional port number.
Host string
// HTTP Test Server
ts *httptest.Server
// The CA used to generate Client Certificates
ca *CA
}
// testPasswordResponse contains the retrieved password information
// The Central Credential Provider returns all data as a string
type testPasswordResponse struct {
SequenceID string `json:",omitempty"`
// Password
Content string `json:",omitempty"`
Safe string `json:",omitempty"`
Folder string `json:",omitempty"`
UserName string `json:",omitempty"`
LogonDomain string `json:",omitempty"`
Name string `json:",omitempty"`
AccountDescription string `json:",omitempty"`
Address string `json:",omitempty"`
DeviceType string `json:",omitempty"`
Environment string `json:",omitempty"`
Database string `json:",omitempty"` // Is Database a valid response?
CreationMethod string `json:",omitempty"`
PolicyID string `json:",omitempty"`
CPMStatus string `json:",omitempty"`
CPMDisabled string `json:",omitempty"`
PasswordChangeInProcess string `json:",omitempty"`
LastTask string `json:",omitempty"`
LastSuccessReconciliation string `json:",omitempty"` // Unix time, the number of seconds elapsed since January 1, 1970 UTC
RetriesCount string `json:",omitempty"`
// Error Information
ErrorCode string `json:",omitempty"`
ErrorMsg string `json:",omitempty"`
}
// NewCCPServer start a mock CCP Web Service
func NewCCPServer() *Server {
ca, err := NewCA()
if err != nil {
panic(err)
}
mux := http.NewServeMux()
mux.HandleFunc("/", http.HandlerFunc(defaultHandler))
mux.HandleFunc("/AIMWebService/api/Accounts", http.HandlerFunc(ccpHandler))
ts := httptest.NewUnstartedServer(mux)
ts.TLS = &tls.Config{
ClientCAs: x509.NewCertPool(),
ClientAuth: tls.RequireAndVerifyClientCert,
}
ts.TLS.ClientCAs.AddCert(ca.Certificate)
ts.StartTLS()
url, err := url.Parse(ts.URL)
if err != nil {
panic(err)
}
return &Server{
Host: url.Host,
ts: ts,
ca: ca,
}
}
// Default Handler return 403 Error
func defaultHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
e := json.NewEncoder(w)
e.Encode(testPasswordResponse{
ErrorCode: "CCPWS403E",
ErrorMsg: "An error occured " + http.StatusText(http.StatusForbidden),
})
}
// CCP Web Serivce Handler
func ccpHandler(w http.ResponseWriter, r *http.Request) {
status := http.StatusOK
// Status 401, No Client Certificate Privided or Common Name is empty
var cn string
if status == http.StatusOK {
if len(r.TLS.PeerCertificates) != 0 {
for _, pc := range r.TLS.PeerCertificates {
cn = pc.Subject.CommonName
if len(cn) == 0 {
status = http.StatusUnauthorized
}
}
} else {
status = http.StatusUnauthorized
}
}
// Status 400, Form Parsing failed
err := r.ParseForm()
if status == http.StatusOK && err != nil {
status = http.StatusBadRequest
}
// Status 400, No AppID provided
appID := r.Form.Get("AppID")
if status == http.StatusOK && len(appID) == 0 {
status = http.StatusBadRequest
}
// Status 403, ClientCert CN != AppID
if status == http.StatusOK && cn != appID {
status = http.StatusForbidden
}
resp := testPasswordResponse{
SequenceID: "1",
PasswordChangeInProcess: "False",
LastSuccessReconciliation: strconv.FormatInt(time.Now().Unix(), 10),
RetriesCount: "-1",
}
// Object, OtherObject results in error
object := r.Form.Get("Object")
if len(object) != 0 {
if object == "OtherObject" {
status = http.StatusNotFound
}
}
// Safe
safe := r.Form.Get("Safe")
if len(safe) != 0 {
resp.Safe = safe
}
// Folder
folder := r.Form.Get("Folder")
if len(folder) != 0 {
resp.Folder = folder
} else {
resp.Folder = "Root"
}
// UserName
resp.UserName = "user-" + object
// Password
passwd := func() string {
const chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
b := make([]byte, 8)
for i := range b {
b[i] = chars[rand.Int63()%int64(len(chars))]
}
return string(b)
}
resp.Content = passwd()
switch status {
case http.StatusBadRequest: // 400
fallthrough
case http.StatusUnauthorized: // 401
fallthrough
case http.StatusForbidden: // 403
fallthrough
case http.StatusNotFound: // 404
resp = testPasswordResponse{
ErrorCode: "CCPWS" + strconv.Itoa(status) + "E",
ErrorMsg: "An error occured " + strconv.Itoa(status) + " " + http.StatusText(status),
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
e := json.NewEncoder(w)
e.Encode(resp)
}
/*
StatusBadRequest = 400 // RFC 7231, 6.5.1
AIMWS030E BadRequest (400) // invalid query format, etc
APPAP227E BadRequest (400) // 1. too many objects
APPAP228E BadRequest (400) // 2. too many objects
APPAP229E BadRequest (400) // 3. too many objects
APPAP007E BadRequest (400) // Connection to the Vault has failed
APPAP081E BadRequest (400) // Request Message content is invalid
CASVL010E BadRequest (400) // Invalid characters in User Name
AIMWS031E BadRequest (400) // Invalid request. The AppID Parameter is require
*/
// ServerRootCA returns the server's (root) Certificate
func (s *Server) ServerRootCA() []byte {
return pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: s.ts.Certificate().Raw,
})
}
// ClientCertificate creates a new test client certificate
func (s *Server) ClientCertificate(cn string) ([]byte, []byte) {
cert, key, err := s.ca.NewClientCertificate(cn)
if err != nil {
panic(err)
}
return cert, key
}
// Close shuts down the server and blocks until all outstanding requests
// on this server have completed.
func (s *Server) Close() {
s.ts.Close()
}