Debian Codegraph @

core/core.go

raw symbols SCIP
1 // Package core handles the main operations of the Red October server.
2 //
3 // Copyright (c) 2013 CloudFlare, Inc.
4
5 package core
6
7 import (
8 "encoding/json"
9 "errors"
10 "fmt"
11 "log"
12 "strconv"
13 "strings"
14 "time"
15
16 "github.com/cloudflare/redoctober/config"
17 "github.com/cloudflare/redoctober/cryptor"
18 "github.com/cloudflare/redoctober/hipchat"
19 "github.com/cloudflare/redoctober/keycache"
20 "github.com/cloudflare/redoctober/order"
21 "github.com/cloudflare/redoctober/passvault"
22 )
23
24 var (
25 crypt *cryptor.Cryptor
26 records passvault.Records
27 orders order.Orderer
28 )
29
30 // Each of these structures corresponds to the JSON expected on the
31 // correspondingly named URI (e.g. the delegate structure maps to the
32 // JSON that should be sent on the /delegate URI and it is handled by
33 // the Delegate function below).
34
35 type CreateRequest struct {
36 Name string
37 Password string
38 }
39
40 type SummaryRequest struct {
41 Name string
42 Password string
43 }
44
45 type PurgeRequest struct {
46 Name string
47 Password string
48 }
49
50 type DelegateRequest struct {
51 Name string
52 Password string
53
54 Uses int
55 Time string
56 Slot string
57 Users []string
58 Labels []string
59 }
60
61 type CreateUserRequest struct {
62 Name string
63 Password string
64 UserType string
65 HipchatName string
66 }
67
68 type PasswordRequest struct {
69 Name string
70 Password string
71
72 NewPassword string
73 HipchatName string
74 }
75
76 type EncryptRequest struct {
77 Name string
78 Password string
79
80 Minimum int
81 Owners []string
82 LeftOwners []string
83 RightOwners []string
84 Predicate string
85
86 Data []byte
87
88 Labels []string
89 }
90
91 type ReEncryptRequest EncryptRequest
92
93 type DecryptRequest struct {
94 Name string
95 Password string
96
97 Data []byte
98 }
99
100 type OwnersRequest struct {
101 Data []byte
102 }
103
104 type ModifyRequest struct {
105 Name string
106 Password string
107
108 ToModify string
109 Command string
110 }
111
112 type ExportRequest struct {
113 Name string
114 Password string
115 }
116
117 type OrderRequest struct {
118 Name string
119 Password string
120 Duration string
121 Uses int
122 Users []string
123 EncryptedData []byte
124 Labels []string
125 }
126
127 type OrderInfoRequest struct {
128 Name string
129 Password string
130
131 OrderNum string
132 }
133
134 type OrderOutstandingRequest struct {
135 Name string
136 Password string
137 }
138
139 type OrderCancelRequest struct {
140 Name string
141 Password string
142
143 OrderNum string
144 }
145
146 type StatusRequest struct {
147 Name string
148 Password string
149 }
150
151 // These structures map the JSON responses that will be sent from the API
152
153 type ResponseData struct {
154 Status string
155 Response []byte `json:",omitempty"`
156 }
157
158 type SummaryData struct {
159 Status string
160 State string
161 Live map[string]keycache.ActiveUser
162 All map[string]passvault.Summary
163 }
164
165 type DecryptWithDelegates struct {
166 Data []byte
167 Secure bool
168 Delegates []string
169 }
170
171 type OwnersData struct {
172 Status string
173 Owners []string
174 Predicate string
175 }
176
177 type StatusData struct {
178 Status string
179 }
180
181 // Helper functions that create JSON responses sent by core
182
183 func jsonStatusOk() ([]byte, error) {
184 return json.Marshal(ResponseData{Status: "ok"})
185 }
186 func jsonStatusError(err error) ([]byte, error) {
187 return json.Marshal(ResponseData{Status: err.Error()})
188 }
189 func jsonSummary() ([]byte, error) {
190 state := crypt.Status()
191 return json.Marshal(SummaryData{Status: "ok", State: state.State, Live: crypt.LiveSummary(), All: records.GetSummary()})
192 }
193 func jsonResponse(resp []byte) ([]byte, error) {
194 return json.Marshal(ResponseData{Status: "ok", Response: resp})
195 }
196
197 // validateUser checks that the username and password passed in are
198 // correct. If admin is true, the user must be an admin as well.
199 func validateUser(name, password string, admin bool) error {
200 if records.NumRecords() == 0 {
201 return errors.New("Vault is not created yet")
202 }
203
204 pr, ok := records.GetRecord(name)
205 if !ok {
206 return errors.New("User not present")
207 }
208
209 if err := pr.ValidatePassword(password); err != nil {
210 return err
211 }
212
213 if admin && !pr.IsAdmin() {
214 return errors.New("Admin required")
215 }
216
217 return nil
218 }
219
220 // validateName checks that the username and password pass a validation test.
221 func validateName(name, password string) error {
222 if name == "" {
223 return errors.New("User name must not be blank")
224 }
225 if password == "" {
226 return errors.New("Password must be at least one character")
227 }
228
229 return nil
230 }
231
232 // Init reads the records from disk from a given path
233 func Init(path string, config *config.Config) error {
234 var err error
235
236 defer func() {
237 if err != nil {
238 log.Printf("core.init failed: %v", err)
239 } else {
240 log.Printf("core.init success: path=%s", path)
241 }
242 }()
243
244 if records, err = passvault.InitFrom(path); err != nil {
245 err = fmt.Errorf("failed to load password vault %s: %s", path, err)
246 }
247
248 var hipchatClient hipchat.HipchatClient
249 hc := config.HipChat
250 if hc.Valid() {
251 roomId, err := strconv.Atoi(hc.Room)
252 if err != nil {
253 return errors.New("core.init unable to use hipchat roomId provided")
254 }
255
256 hipchatClient = hipchat.HipchatClient{
257 ApiKey: hc.APIKey,
258 RoomId: roomId,
259 HcHost: hc.Host,
260 RoHost: config.UI.Root,
261 }
262 }
263
264 orders = order.NewOrderer(hipchatClient)
265 crypt, err = cryptor.New(&records, nil, config)
266
267 return err
268 }
269
270 // Create processes a create request.
271 func Create(jsonIn []byte) ([]byte, error) {
272 var s CreateRequest
273 var err error
274
275 defer func() {
276 if err != nil {
277 log.Printf("core.create failed: user=%s %v", s.Name, err)
278 } else {
279 log.Printf("core.create success: user=%s", s.Name)
280 }
281 }()
282
283 if err = json.Unmarshal(jsonIn, &s); err != nil {
284 return jsonStatusError(err)
285 }
286
287 if records.NumRecords() != 0 {
288 err = errors.New("Vault is already created")
289 return jsonStatusError(err)
290 }
291
292 // Validate the Name and Password as valid
293 if err = validateName(s.Name, s.Password); err != nil {
294 return jsonStatusError(err)
295 }
296
297 if _, err = records.AddNewRecord(s.Name, s.Password, true, passvault.DefaultRecordType); err != nil {
298 return jsonStatusError(err)
299 }
300
301 return jsonStatusOk()
302 }
303
304 // Summary processes a summary request.
305 func Summary(jsonIn []byte) ([]byte, error) {
306 var s SummaryRequest
307 var err error
308
309 defer func() {
310 if err != nil {
311 log.Printf("core.summary failed: user=%s %v", s.Name, err)
312 } else {
313 log.Printf("core.summary success: user=%s", s.Name)
314 }
315 }()
316
317 err = crypt.Refresh()
318 if err != nil {
319 return jsonStatusError(err)
320 }
321
322 if err := json.Unmarshal(jsonIn, &s); err != nil {
323 return jsonStatusError(err)
324 }
325
326 if records.NumRecords() == 0 {
327 err = errors.New("vault has not been created")
328 return jsonStatusError(err)
329 }
330
331 if err := validateUser(s.Name, s.Password, false); err != nil {
332 return jsonStatusError(err)
333 }
334
335 return jsonSummary()
336 }
337
338 // Purge processes a delegation purge request.
339 func Purge(jsonIn []byte) ([]byte, error) {
340 var s PurgeRequest
341 var err error
342
343 defer func() {
344 if err != nil {
345 log.Printf("core.purge failed: user=%s %v", s.Name, err)
346 } else {
347 log.Printf("core.purge success: user=%s", s.Name)
348 }
349 }()
350
351 if err = json.Unmarshal(jsonIn, &s); err != nil {
352 return jsonStatusError(err)
353 }
354
355 if records.NumRecords() == 0 {
356 err = errors.New("vault has not been created")
357 return jsonStatusError(err)
358 }
359
360 // Validate the Name and Password as valid and admin
361 if err = validateUser(s.Name, s.Password, true); err != nil {
362 return jsonStatusError(err)
363 }
364
365 err = crypt.Flush()
366 if err != nil {
367 return jsonStatusError(err)
368 }
369
370 return jsonStatusOk()
371 }
372
373 // Delegate processes a delegation request.
374 func Delegate(jsonIn []byte) ([]byte, error) {
375 var s DelegateRequest
376 var err error
377
378 defer func() {
379 if err != nil {
380 log.Printf("core.delegate failed: user=%s %v", s.Name, err)
381 } else {
382 log.Printf("core.delegate success: user=%s uses=%d time=%s users=%v labels=%v", s.Name, s.Uses, s.Time, s.Users, s.Labels)
383 }
384 }()
385
386 if err = json.Unmarshal(jsonIn, &s); err != nil {
387 return jsonStatusError(err)
388 }
389
390 if records.NumRecords() == 0 {
391 err = errors.New("Vault is not created yet")
392 return jsonStatusError(err)
393 }
394
395 // Validate the Name and Password as valid
396 if err = validateName(s.Name, s.Password); err != nil {
397 return jsonStatusError(err)
398 }
399
400 // Make sure the user we are delegating to exists
401 var invalidUsers []string
402 for _, user := range s.Users {
403 if _, ok := records.GetRecord(user); !ok {
404 invalidUsers = append(invalidUsers, user)
405 }
406 }
407
408 if len(invalidUsers) != 0 {
409 err = fmt.Errorf("User(s) not present: %s", strings.Join(invalidUsers, ", "))
410 return jsonStatusError(err)
411 }
412
413 // Find password record for user and verify that their password
414 // matches. If not found then add a new entry for this user.
415
416 pr, found := records.GetRecord(s.Name)
417 if found {
418 if err = pr.ValidatePassword(s.Password); err != nil {
419 return jsonStatusError(err)
420 }
421 } else {
422 if pr, err = records.AddNewRecord(s.Name, s.Password, false, passvault.DefaultRecordType); err != nil {
423 return jsonStatusError(err)
424 }
425 }
426
427 // add signed-in record to active set
428 if err = crypt.Delegate(pr, s.Name, s.Password, s.Users, s.Labels, s.Uses, s.Slot, s.Time); err != nil {
429 return jsonStatusError(err)
430 }
431
432 // Make sure we capture the number who have already delegated.
433 for _, delegatedUser := range s.Users {
434 if orderKey, found := orders.FindOrder(delegatedUser, s.Labels); found {
435 order := orders.Orders[orderKey]
436
437 // Don't re-add names to the list of people who have delegated. Instead
438 // just skip them but make sure we count their delegation
439 if len(order.OwnersDelegated) == 0 {
440 order.OwnersDelegated = append(order.OwnersDelegated, s.Name)
441 } else {
442 for _, ownerName := range order.OwnersDelegated {
443 if ownerName == s.Name {
444 continue
445 }
446 order.OwnersDelegated = append(order.OwnersDelegated, s.Name)
447 order.Delegated++
448 }
449 }
450 orders.Orders[orderKey] = order
451
452 // Notify the hipchat room that there was a new delegator
453 orders.NotifyDelegation(s.Name, delegatedUser, orderKey, s.Time, s.Labels)
454
455 }
456 }
457
458 return jsonStatusOk()
459 }
460
461 // Create User processes a create-user request.
462 func CreateUser(jsonIn []byte) ([]byte, error) {
463 var s CreateUserRequest
464 var err error
465
466 defer func() {
467 if err != nil {
468 log.Printf("core.create-user failed: user=%s %v", s.Name, err)
469 } else {
470 log.Printf("core.create-user success: user=%s", s.Name)
471 }
472 }()
473
474 if err = json.Unmarshal(jsonIn, &s); err != nil {
475 return jsonStatusError(err)
476 }
477
478 // If no UserType if provided use the default one
479 if s.UserType == "" {
480 s.UserType = passvault.DefaultRecordType
481 }
482
483 if records.NumRecords() == 0 {
484 err = errors.New("Vault is not created yet")
485 return jsonStatusError(err)
486 }
487
488 // Validate the Name and Password as valid
489 if err = validateName(s.Name, s.Password); err != nil {
490 return jsonStatusError(err)
491 }
492
493 _, found := records.GetRecord(s.Name)
494 if found {
495 err = errors.New("User with that name already exists")
496 return jsonStatusError(err)
497 }
498
499 if _, err := records.AddNewRecord(s.Name, s.Password, false, s.UserType); err != nil {
500 return jsonStatusError(err)
501 }
502
503 if err = records.ChangePassword(s.Name, s.Password, "", s.HipchatName); err != nil {
504 return jsonStatusError(err)
505 }
506 return jsonStatusOk()
507 }
508
509 // Password processes a password change request.
510 func Password(jsonIn []byte) ([]byte, error) {
511 var err error
512 var s PasswordRequest
513
514 defer func() {
515 if err != nil {
516 log.Printf("core.password failed: user=%s %v", s.Name, err)
517 } else {
518 log.Printf("core.password success: user=%s", s.Name)
519 }
520 }()
521
522 if err = json.Unmarshal(jsonIn, &s); err != nil {
523 return jsonStatusError(err)
524 }
525
526 if records.NumRecords() == 0 {
527 err = errors.New("Vault is not created yet")
528 return jsonStatusError(err)
529 }
530
531 // add signed-in record to active set
532 err = records.ChangePassword(s.Name, s.Password, s.NewPassword, s.HipchatName)
533 if err != nil {
534 return jsonStatusError(err)
535 }
536
537 return jsonStatusOk()
538 }
539
540 // Encrypt processes an encrypt request.
541 func Encrypt(jsonIn []byte) ([]byte, error) {
542 var s EncryptRequest
543 var err error
544
545 defer func() {
546 if err != nil {
547 log.Printf("core.encrypt failed: user=%s size=%d %v", s.Name, len(s.Data), err)
548 } else {
549 log.Printf("core.encrypt success: user=%s size=%d", s.Name, len(s.Data))
550 }
551 }()
552
553 err = json.Unmarshal(jsonIn, &s)
554 if err != nil {
555 return jsonStatusError(err)
556 }
557
558 if err = validateUser(s.Name, s.Password, false); err != nil {
559 return jsonStatusError(err)
560 }
561
562 access := cryptor.AccessStructure{
563 Minimum: s.Minimum,
564 Names: s.Owners,
565 LeftNames: s.LeftOwners,
566 RightNames: s.RightOwners,
567 Predicate: s.Predicate,
568 }
569
570 resp, err := crypt.Encrypt(s.Data, s.Labels, access)
571 if err != nil {
572 return jsonStatusError(err)
573 }
574 return jsonResponse(resp)
575 }
576
577 // ReEncrypt processes an Re-encrypt request.
578 func ReEncrypt(jsonIn []byte) ([]byte, error) {
579 var s ReEncryptRequest
580 var err error
581
582 defer func() {
583 if err != nil {
584 log.Printf("core.re-encrypt failed: user=%s size=%d %v", s.Name, len(s.Data), err)
585 } else {
586 log.Printf("core.re-encrypt success: user=%s size=%d", s.Name, len(s.Data))
587 }
588 }()
589
590 err = json.Unmarshal(jsonIn, &s)
591 if err != nil {
592 return jsonStatusError(err)
593 }
594
595 if err = validateUser(s.Name, s.Password, false); err != nil {
596 return jsonStatusError(err)
597 }
598
599 data, _, _, secure, err := crypt.Decrypt(s.Data, s.Name)
600 if err != nil {
601 return jsonStatusError(err)
602 }
603 if !secure {
604 return jsonStatusError(errors.New("decryption's secure bit is false"))
605 }
606
607 access := cryptor.AccessStructure{
608 Minimum: s.Minimum,
609 Names: s.Owners,
610 LeftNames: s.LeftOwners,
611 RightNames: s.RightOwners,
612 Predicate: s.Predicate,
613 }
614
615 resp, err := crypt.Encrypt(data, s.Labels, access)
616 if err != nil {
617 return jsonStatusError(err)
618 }
619 return jsonResponse(resp)
620 }
621
622 // Decrypt processes a decrypt request.
623 func Decrypt(jsonIn []byte) ([]byte, error) {
624 var s DecryptRequest
625 var err error
626
627 defer func() {
628 if err != nil {
629 log.Printf("core.decrypt failed: user=%s %v", s.Name, err)
630 } else {
631 log.Printf("core.decrypt success: user=%s", s.Name)
632 }
633 }()
634
635 err = json.Unmarshal(jsonIn, &s)
636 if err != nil {
637 return jsonStatusError(err)
638 }
639
640 err = validateUser(s.Name, s.Password, false)
641 if err != nil {
642 return jsonStatusError(err)
643 }
644
645 data, allLabels, names, secure, err := crypt.Decrypt(s.Data, s.Name)
646 if err != nil {
647 return jsonStatusError(err)
648 }
649
650 resp := &DecryptWithDelegates{
651 Data: data,
652 Secure: secure,
653 Delegates: names,
654 }
655
656 out, err := json.Marshal(resp)
657 if err != nil {
658 return jsonStatusError(err)
659 }
660
661 // Cleanup any orders that have been fulfilled and notify the room.
662 if orderKey, found := orders.FindOrder(s.Name, allLabels); found {
663 delete(orders.Orders, orderKey)
664 orders.NotifyOrderFulfilled(s.Name, orderKey)
665 }
666 return jsonResponse(out)
667 }
668
669 // Modify processes a modify request.
670 func Modify(jsonIn []byte) ([]byte, error) {
671 var s ModifyRequest
672 var err error
673
674 defer func() {
675 if err != nil {
676 log.Printf("core.modify failed: user=%s target=%s command=%s %v", s.Name, s.ToModify, s.Command, err)
677 } else {
678 log.Printf("core.modify success: user=%s target=%s command=%s", s.Name, s.ToModify, s.Command)
679 }
680 }()
681
682 err = json.Unmarshal(jsonIn, &s)
683 if err != nil {
684 return jsonStatusError(err)
685 }
686
687 if err = validateUser(s.Name, s.Password, true); err != nil {
688 return jsonStatusError(err)
689 }
690
691 if _, ok := records.GetRecord(s.ToModify); !ok {
692 err = errors.New("core: record to modify missing")
693 return jsonStatusError(err)
694 }
695
696 if s.Name == s.ToModify {
697 err = errors.New("core: cannot modify own record")
698 return jsonStatusError(err)
699 }
700
701 switch s.Command {
702 case "delete":
703 err = records.DeleteRecord(s.ToModify)
704 case "revoke":
705 err = records.RevokeRecord(s.ToModify)
706 case "admin":
707 err = records.MakeAdmin(s.ToModify)
708 default:
709 err = fmt.Errorf("core: unknown command '%s' passed to modify", s.Command)
710 return jsonStatusError(err)
711 }
712
713 if err != nil {
714 return jsonStatusError(err)
715 } else {
716 return jsonStatusOk()
717 }
718 }
719
720 // Owners processes a owners request.
721 func Owners(jsonIn []byte) ([]byte, error) {
722 var s OwnersRequest
723 var err error
724
725 defer func() {
726 if err != nil {
727 log.Printf("core.owners failed: size=%d %v", len(s.Data), err)
728 } else {
729 log.Printf("core.owners success: size=%d", len(s.Data))
730 }
731 }()
732
733 err = json.Unmarshal(jsonIn, &s)
734 if err != nil {
735 return jsonStatusError(err)
736 }
737
738 names, predicate, err := crypt.GetOwners(s.Data)
739 if err != nil {
740 return jsonStatusError(err)
741 }
742
743 return json.Marshal(OwnersData{Status: "ok", Owners: names, Predicate: predicate})
744 }
745
746 // Export returns a backed up vault.
747 func Export(jsonIn []byte) ([]byte, error) {
748 var s ExportRequest
749 var err error
750
751 defer func() {
752 if err != nil {
753 log.Printf("core.export failed: user=%s %v", s.Name, err)
754 } else {
755 log.Printf("core.export success: user=%s", s.Name)
756 }
757 }()
758
759 err = json.Unmarshal(jsonIn, &s)
760 if err != nil {
761 return jsonStatusError(err)
762 }
763
764 err = validateUser(s.Name, s.Password, true)
765 if err != nil {
766 return jsonStatusError(err)
767 }
768
769 out, err := json.Marshal(records)
770 if err != nil {
771 return jsonStatusError(err)
772 }
773
774 return jsonResponse(out)
775 }
776
777 // Order will request delegations from other users.
778 func Order(jsonIn []byte) (out []byte, err error) {
779 var o OrderRequest
780
781 defer func() {
782 if err != nil {
783 log.Printf("core.order failed: user=%s %v", o.Name, err)
784 } else {
785 log.Printf("core.order success: user=%s", o.Name)
786 }
787 }()
788
789 if err = json.Unmarshal(jsonIn, &o); err != nil {
790 return jsonStatusError(err)
791 }
792
793 if err := validateUser(o.Name, o.Password, false); err != nil {
794 return jsonStatusError(err)
795 }
796
797 // Get the owners of the ciphertext.
798 owners, _, err := crypt.GetOwners(o.EncryptedData)
799 if err != nil {
800 return jsonStatusError(err)
801 }
802 if o.Duration == "" {
803 err = errors.New("Duration required when placing an order.")
804 return jsonStatusError(err)
805 }
806 if o.Uses == 0 {
807 err = errors.New("Number of required uses necessary when placing an order.")
808 return jsonStatusError(err)
809 }
810
811 err = crypt.Refresh()
812 if err != nil {
813 return jsonStatusError(err)
814 }
815
816 orderNum := order.GenerateNum()
817
818 if len(o.Users) == 0 {
819 err = errors.New("Must specify at least one user per order.")
820 return jsonStatusError(err)
821 }
822 adminsDelegated, numDelegated := crypt.DelegateStatus(o.Users[0], o.Labels, owners)
823 duration, err := time.ParseDuration(o.Duration)
824 if err != nil {
825 return jsonStatusError(err)
826 }
827 currentTime := time.Now()
828 ord := order.CreateOrder(o.Name,
829 orderNum,
830 currentTime,
831 duration,
832 adminsDelegated,
833 owners,
834 o.Users,
835 o.Labels,
836 numDelegated)
837 orders.Orders[orderNum] = ord
838 out, err = json.Marshal(ord)
839
840 // Get a map to any alternative name we want to notify
841 altOwners := records.GetAltNamesFromName(orders.AlternateName, owners)
842
843 // Let everyone on hipchat know there is a new order.
844 orders.NotifyNewOrder(o.Duration, orderNum, o.Users, o.Labels, o.Uses, altOwners)
845 if err != nil {
846 return jsonStatusError(err)
847 }
848 return jsonResponse(out)
849 }
850
851 // OrdersOutstanding will return a list of currently outstanding orders.
852 func OrdersOutstanding(jsonIn []byte) (out []byte, err error) {
853 var o OrderOutstandingRequest
854
855 defer func() {
856 if err != nil {
857 log.Printf("core.ordersout failed: user=%s %v", o.Name, err)
858 } else {
859 log.Printf("core.ordersout success: user=%s", o.Name)
860 }
861 }()
862
863 if err = json.Unmarshal(jsonIn, &o); err != nil {
864 return jsonStatusError(err)
865 }
866
867 if err := validateUser(o.Name, o.Password, false); err != nil {
868 return jsonStatusError(err)
869 }
870
871 out, err = json.Marshal(orders.Orders)
872 if err != nil {
873 return jsonStatusError(err)
874 }
875 return jsonResponse(out)
876 }
877
878 // OrderInfo will return a list of currently outstanding order numbers.
879 func OrderInfo(jsonIn []byte) (out []byte, err error) {
880 var o OrderInfoRequest
881
882 defer func() {
883 if err != nil {
884 log.Printf("core.order failed: user=%s %v", o.Name, err)
885 } else {
886 log.Printf("core.order success: user=%s", o.Name)
887 }
888 }()
889
890 if err = json.Unmarshal(jsonIn, &o); err != nil {
891 return jsonStatusError(err)
892 }
893 if err := validateUser(o.Name, o.Password, false); err != nil {
894 return jsonStatusError(err)
895 }
896
897 if ord, ok := orders.Orders[o.OrderNum]; ok {
898 if out, err = json.Marshal(ord); err != nil {
899 return jsonStatusError(err)
900 } else if len(out) == 0 {
901 return jsonStatusError(errors.New("No order with that number"))
902 }
903
904 return jsonResponse(out)
905 }
906
907 return jsonStatusError(errors.New("No order with that number"))
908 }
909
910 // OrderCancel will cancel an order given an order num
911 func OrderCancel(jsonIn []byte) (out []byte, err error) {
912 var o OrderCancelRequest
913
914 defer func() {
915 if err != nil {
916 log.Printf("core.order failed: user=%s %v", o.Name, err)
917 } else {
918 log.Printf("core.order success: user=%s", o.Name)
919 }
920 }()
921
922 if err = json.Unmarshal(jsonIn, &o); err != nil {
923 return jsonStatusError(err)
924 }
925
926 if err := validateUser(o.Name, o.Password, false); err != nil {
927 return jsonStatusError(err)
928 }
929
930 if ord, ok := orders.Orders[o.OrderNum]; ok {
931 if o.Name == ord.Creator {
932 delete(orders.Orders, o.OrderNum)
933 out = []byte("Successfully removed order")
934 return jsonResponse(out)
935 }
936 }
937 err = errors.New("Invalid Order Number")
938 return jsonStatusError(err)
939 }
940
941 // Status returns the current delegation persistence state. In the
942 // future, this may return more data.
943 func Status(jsonIn []byte) (out []byte, err error) {
944 var req StatusRequest
945
946 defer func() {
947 if err != nil {
948 log.Printf("core.status failed: user=%s %v", req.Name, err)
949 } else {
950 log.Printf("core.status success: user=%s", req.Name)
951 }
952 }()
953
954 if err = json.Unmarshal(jsonIn, &req); err != nil {
955 return jsonStatusError(err)
956 }
957
958 if err := validateUser(req.Name, req.Password, false); err != nil {
959 return jsonStatusError(err)
960 }
961
962 st := crypt.Status()
963 resp := &StatusData{Status: st.State}
964 if out, err = json.Marshal(resp); err != nil {
965 return jsonStatusError(err)
966 }
967
968 return jsonResponse(out)
969 }
970
971 // Restore attempts a restoration of the persistence store.
972 func Restore(jsonIn []byte) (out []byte, err error) {
973 var req DelegateRequest
974
975 defer func() {
976 if err != nil {
977 log.Printf("core.restore failed: user=%s %v", req.Name, err)
978 } else {
979 log.Printf("core.restore success: user=%s", req.Name)
980 }
981 }()
982
983 if err = json.Unmarshal(jsonIn, &req); err != nil {
984 return jsonStatusError(err)
985 }
986
987 if err := validateUser(req.Name, req.Password, false); err != nil {
988 return jsonStatusError(err)
989 }
990
991 err = crypt.Restore(req.Name, req.Password, 1, "", req.Time)
992 if err != nil && err != cryptor.ErrRestoreDelegations {
993 return jsonStatusError(err)
994 }
995
996 st := crypt.Status()
997 resp := &StatusData{Status: st.State}
998 if out, err = json.Marshal(resp); err != nil {
999 return jsonStatusError(err)
1000 }
1001
1002 return jsonResponse(out)
1003 }
1004
1005 // ResetPersisted clears the persisted user data from the server. This
1006 // request requires an admin.
1007 func ResetPersisted(jsonIn []byte) (out []byte, err error) {
1008 var req PurgeRequest
1009
1010 defer func() {
1011 if err != nil {
1012 log.Printf("core.resetpersisted failed: user=%s %v", req.Name, err)
1013 } else {
1014 log.Printf("core.resetpersisted success: user=%s", req.Name)
1015 }
1016 }()
1017
1018 if err = json.Unmarshal(jsonIn, &req); err != nil {
1019 return jsonStatusError(err)
1020 }
1021
1022 if err := validateUser(req.Name, req.Password, true); err != nil {
1023 return jsonStatusError(err)
1024 }
1025
1026 st, err := crypt.ResetPersisted()
1027 if err != nil {
1028 return jsonStatusError(err)
1029 }
1030
1031 resp := &StatusData{Status: st.State}
1032 if out, err = json.Marshal(resp); err != nil {
1033 return jsonStatusError(err)
1034 }
1035
1036 return jsonResponse(out)
1037 }