forked from mendersoftware/mender
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmender_test.go
1103 lines (933 loc) · 28.8 KB
/
mender_test.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 Northern.tech AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"crypto/rand"
"io"
"io/ioutil"
"os"
"path"
"syscall"
"testing"
"time"
"github.com/mendersoftware/mender-artifact/artifact"
"github.com/mendersoftware/mender-artifact/awriter"
"github.com/mendersoftware/mender-artifact/handlers"
"github.com/mendersoftware/mender/client"
cltest "github.com/mendersoftware/mender/client/test"
"github.com/mendersoftware/mender/datastore"
"github.com/mendersoftware/mender/store"
stest "github.com/mendersoftware/mender/system/testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
type testMenderPieces struct {
MenderPieces
}
func Test_getArtifactName_noArtifactNameInFile_returnsEmptyName(t *testing.T) {
mender := newDefaultTestMender()
artifactInfoFile, _ := os.Create("artifact_info")
defer os.Remove("artifact_info")
fileContent := "#dummy comment"
artifactInfoFile.WriteString(fileContent)
// rewind to the beginning of file
//artifactInfoFile.Seek(0, 0)
mender.artifactInfoFile = "artifact_info"
artName, err := mender.GetCurrentArtifactName()
assert.NoError(t, err)
assert.Equal(t, "", artName)
}
func Test_getArtifactName_malformedArtifactNameLine_returnsError(t *testing.T) {
mender := newDefaultTestMender()
artifactInfoFile, _ := os.Create("artifact_info")
defer os.Remove("artifact_info")
fileContent := "artifact_name"
artifactInfoFile.WriteString(fileContent)
// rewind to the beginning of file
//artifactInfoFile.Seek(0, 0)
mender.artifactInfoFile = "artifact_info"
artName, err := mender.GetCurrentArtifactName()
assert.Error(t, err)
assert.Equal(t, "", artName)
}
func Test_getArtifactName_haveArtifactName_returnsName(t *testing.T) {
mender := newDefaultTestMender()
artifactInfoFile, _ := os.Create("artifact_info")
defer os.Remove("artifact_info")
fileContent := "artifact_name=mender-image"
artifactInfoFile.WriteString(fileContent)
mender.artifactInfoFile = "artifact_info"
artName, err := mender.GetCurrentArtifactName()
assert.NoError(t, err)
assert.Equal(t, "mender-image", artName)
}
func newTestMender(runner *stest.TestOSCalls, config menderConfig, pieces testMenderPieces) *mender {
// fill out missing pieces
if pieces.store == nil {
pieces.store = store.NewMemStore()
}
if pieces.dualRootfsDevice == nil {
pieces.dualRootfsDevice = &fakeDevice{}
}
if pieces.authMgr == nil {
ks := store.NewKeystore(pieces.store, defaultKeyFile)
cmdr := stest.NewTestOSCalls("mac=foobar", 0)
pieces.authMgr = NewAuthManager(AuthManagerConfig{
AuthDataStore: pieces.store,
KeyStore: ks,
IdentitySource: &IdentityDataRunner{
cmdr: cmdr,
},
})
}
mender, _ := NewMender(&config, pieces.MenderPieces)
mender.stateScriptPath = ""
return mender
}
func newDefaultTestMender() *mender {
return newTestMender(nil, menderConfig{
menderConfigFromFile: menderConfigFromFile{
Servers: []client.MenderServer{{}},
},
}, testMenderPieces{})
}
func Test_ForceBootstrap(t *testing.T) {
// generate valid keys
ms := store.NewMemStore()
mender := newTestMender(nil,
menderConfig{},
testMenderPieces{
MenderPieces: MenderPieces{
store: ms,
},
},
)
merr := mender.Bootstrap()
assert.NoError(t, merr)
kdataold, err := ms.ReadAll(defaultKeyFile)
assert.NoError(t, err)
assert.NotEmpty(t, kdataold)
mender.ForceBootstrap()
assert.True(t, mender.needsBootstrap())
merr = mender.Bootstrap()
assert.NoError(t, merr)
// bootstrap should have generated a new key
kdatanew, err := ms.ReadAll(defaultKeyFile)
assert.NoError(t, err)
assert.NotEmpty(t, kdatanew)
// we should have a new key
assert.NotEqual(t, kdatanew, kdataold)
}
func Test_Bootstrap(t *testing.T) {
mender := newTestMender(nil,
menderConfig{},
testMenderPieces{},
)
assert.True(t, mender.needsBootstrap())
assert.NoError(t, mender.Bootstrap())
mam, _ := mender.authMgr.(*MenderAuthManager)
k := store.NewKeystore(mam.store, defaultKeyFile)
assert.NotNil(t, k)
assert.NoError(t, k.Load())
}
func Test_BootstrappedHaveKeys(t *testing.T) {
// generate valid keys
ms := store.NewMemStore()
k := store.NewKeystore(ms, defaultKeyFile)
assert.NotNil(t, k)
assert.NoError(t, k.Generate())
assert.NoError(t, k.Save())
mender := newTestMender(nil,
menderConfig{},
testMenderPieces{
MenderPieces: MenderPieces{
store: ms,
},
},
)
assert.NotNil(t, mender)
mam, _ := mender.authMgr.(*MenderAuthManager)
assert.Equal(t, ms, mam.keyStore.GetStore())
assert.NotNil(t, mam.keyStore.GetPrivateKey())
// subsequen bootstrap should not fail
assert.NoError(t, mender.Bootstrap())
}
func Test_BootstrapError(t *testing.T) {
ms := store.NewMemStore()
ms.Disable(true)
var mender *mender
mender = newTestMender(nil, menderConfig{}, testMenderPieces{
MenderPieces: MenderPieces{
store: ms,
},
})
// store is disabled, attempts to load keys when creating authMgr should have
// failed, resulting in empty keys.
assert.False(t, mender.authMgr.HasKey())
ms.Disable(false)
mender = newTestMender(nil, menderConfig{}, testMenderPieces{
MenderPieces: MenderPieces{
store: ms,
},
})
assert.NotNil(t, mender.authMgr)
ms.ReadOnly(true)
err := mender.Bootstrap()
assert.Error(t, err)
}
func Test_CheckUpdateSimple(t *testing.T) {
// create temp dir
td, _ := ioutil.TempDir("", "mender-install-update-")
defer os.RemoveAll(td)
// prepare fake artifactInfo file
artifactInfo := path.Join(td, "artifact_info")
// prepare fake device type file
deviceType := path.Join(td, "device_type")
var mender *mender
mender = newTestMender(nil, menderConfig{
menderConfigFromFile: menderConfigFromFile{
Servers: []client.MenderServer{{ServerURL: "bogusurl"}},
},
}, testMenderPieces{})
up, err := mender.CheckUpdate()
assert.Error(t, err)
assert.Nil(t, up)
srv := cltest.NewClientTestServer()
defer srv.Close()
srv.Update.Has = true
mender = newTestMender(nil,
menderConfig{
menderConfigFromFile: menderConfigFromFile{
Servers: []client.MenderServer{{ServerURL: srv.URL}},
},
},
testMenderPieces{})
mender.artifactInfoFile = artifactInfo
mender.deviceTypeFile = deviceType
srv.Update.Current = client.CurrentUpdate{
Artifact: "fake-id",
DeviceType: "hammer",
}
// test server expects current update information, request should fail
up, err = mender.CheckUpdate()
assert.Error(t, err)
assert.Nil(t, nil)
// NOTE: manifest file data must match current update information expected by
// the server
ioutil.WriteFile(artifactInfo, []byte("artifact_name=fake-id\nDEVICE_TYPE=hammer"), 0600)
ioutil.WriteFile(deviceType, []byte("device_type=hammer"), 0600)
currID, sErr := mender.GetCurrentArtifactName()
assert.NoError(t, sErr)
assert.Equal(t, "fake-id", currID)
// make artifact name same as current, will result in no updates being available
srv.Update.Data.Artifact.ArtifactName = currID
up, err = mender.CheckUpdate()
assert.Equal(t, err, NewTransientError(os.ErrExist))
assert.NotNil(t, up)
// make artifact name different from current
srv.Update.Data.Artifact.ArtifactName = currID + "-fake"
srv.Update.Has = true
up, err = mender.CheckUpdate()
assert.NoError(t, err)
assert.NotNil(t, up)
assert.Equal(t, *up, srv.Update.Data)
// pretend that we got 204 No Content from the server, i.e empty response body
srv.Update.Has = false
up, err = mender.CheckUpdate()
assert.NoError(t, err)
assert.Nil(t, up)
}
func TestMenderGetUpdatePollInterval(t *testing.T) {
mender := newTestMender(nil, menderConfig{
menderConfigFromFile: menderConfigFromFile{
UpdatePollIntervalSeconds: 20,
},
}, testMenderPieces{})
intvl := mender.GetUpdatePollInterval()
assert.Equal(t, time.Duration(20)*time.Second, intvl)
}
func TestMenderGetInventoryPollInterval(t *testing.T) {
mender := newTestMender(nil, menderConfig{
menderConfigFromFile: menderConfigFromFile{
InventoryPollIntervalSeconds: 10,
},
}, testMenderPieces{})
intvl := mender.GetInventoryPollInterval()
assert.Equal(t, time.Duration(10)*time.Second, intvl)
}
type testAuthDataMessenger struct {
reqData []byte
sigData []byte
code client.AuthToken
reqError error
rspError error
rspData []byte
}
func (t *testAuthDataMessenger) MakeAuthRequest() (*client.AuthRequest, error) {
return &client.AuthRequest{
Data: t.reqData,
Token: t.code,
Signature: t.sigData,
}, t.reqError
}
func (t *testAuthDataMessenger) RecvAuthResponse(data []byte) error {
t.rspData = data
return t.rspError
}
type testAuthManager struct {
authorized bool
authtoken client.AuthToken
authtokenErr error
haskey bool
generatekeyErr error
testAuthDataMessenger
}
func (a *testAuthManager) IsAuthorized() bool {
return a.authorized
}
func (a *testAuthManager) AuthToken() (client.AuthToken, error) {
return a.authtoken, a.authtokenErr
}
func (a *testAuthManager) HasKey() bool {
return a.haskey
}
func (a *testAuthManager) GenerateKey() error {
return a.generatekeyErr
}
func (a *testAuthManager) RemoveAuthToken() error {
return nil
}
func TestMenderAuthorize(t *testing.T) {
runner := stest.NewTestOSCalls("", -1)
rspdata := []byte("foobar")
atok := client.AuthToken("authorized")
authMgr := &testAuthManager{
authorized: false,
authtoken: atok,
}
srv := cltest.NewClientTestServer()
defer srv.Close()
mender := newTestMender(runner,
menderConfig{},
testMenderPieces{
MenderPieces: MenderPieces{
authMgr: authMgr,
},
})
// Should return empty server list error
err := mender.Authorize()
assert.Error(t, err)
mender.config.Servers = make([]client.MenderServer, 1)
mender.config.Servers[0].ServerURL = srv.URL
authMgr.authorized = true
err = mender.Authorize()
// we should initialize with valid token
assert.Equal(t, atok, mender.authToken)
// 1. client already authorized
err = mender.Authorize()
assert.NoError(t, err)
// no need to build send request if auth data is valid
assert.False(t, srv.Auth.Called)
assert.Equal(t, atok, mender.authToken)
// 2. pretend caching of authorization code fails
authMgr.authtokenErr = errors.New("auth code load failed")
mender.authToken = noAuthToken
err = mender.Authorize()
assert.Error(t, err)
// no need to build send request if auth data is valid
assert.False(t, srv.Auth.Called)
assert.Equal(t, noAuthToken, mender.authToken)
authMgr.authtokenErr = nil
// 3. call the server, server denies authorization
authMgr.authorized = false
err = mender.Authorize()
assert.Error(t, err)
assert.False(t, err.IsFatal())
assert.True(t, srv.Auth.Called)
assert.Equal(t, noAuthToken, mender.authToken)
// 4. pretend authorization manager fails to parse response
srv.Auth.Called = false
authMgr.testAuthDataMessenger.rspError = errors.New("response parse error")
// we need the server authorize the client
srv.Auth.Authorize = true
srv.Auth.Token = rspdata
err = mender.Authorize()
assert.Error(t, err)
assert.False(t, err.IsFatal())
assert.True(t, srv.Auth.Called)
// response data should be passed verbatim to AuthDataMessenger interface
assert.Equal(t, rspdata, authMgr.testAuthDataMessenger.rspData)
// 5. authorization manger throws no errors, server authorizes the client
srv.Auth.Called = false
authMgr.testAuthDataMessenger.rspError = nil
// server will authorize the client
srv.Auth.Authorize = true
srv.Auth.Token = rspdata
err = mender.Authorize()
// all good
assert.NoError(t, err)
// Authorize() should have reloaded the cache (token comes from mock
// auth manager)
assert.Equal(t, atok, mender.authToken)
}
func TestMenderReportStatus(t *testing.T) {
srv := cltest.NewClientTestServer()
defer srv.Close()
ms := store.NewMemStore()
mender := newTestMender(nil,
menderConfig{
menderConfigFromFile: menderConfigFromFile{
Servers: []client.MenderServer{{ServerURL: srv.URL}},
},
},
testMenderPieces{
MenderPieces: MenderPieces{
store: ms,
},
},
)
ms.WriteAll(datastore.AuthTokenName, []byte("tokendata"))
err := mender.Authorize()
assert.NoError(t, err)
srv.Auth.Verify = true
srv.Auth.Token = []byte("tokendata")
// 1. successful report
err = mender.ReportUpdateStatus(
&datastore.UpdateInfo{
ID: "foobar",
},
client.StatusSuccess,
)
assert.Nil(t, err)
assert.Equal(t, client.StatusSuccess, srv.Status.Status)
// 2. pretend authorization fails, server expects a different token
srv.Reset()
srv.Auth.Token = []byte("footoken")
srv.Auth.Verify = true
err = mender.ReportUpdateStatus(
&datastore.UpdateInfo{
ID: "foobar",
},
client.StatusSuccess,
)
assert.NotNil(t, err)
assert.False(t, err.IsFatal())
// 3. pretend that deployment was aborted
srv.Reset()
srv.Auth.Authorize = true
srv.Auth.Token = []byte("tokendata")
srv.Auth.Verify = true
srv.Status.Aborted = true
err = mender.ReportUpdateStatus(
&datastore.UpdateInfo{
ID: "foobar",
},
client.StatusSuccess,
)
assert.NotNil(t, err)
assert.True(t, err.IsFatal())
}
func TestMenderLogUpload(t *testing.T) {
srv := cltest.NewClientTestServer()
defer srv.Close()
ms := store.NewMemStore()
mender := newTestMender(nil,
menderConfig{
menderConfigFromFile: menderConfigFromFile{
Servers: []client.MenderServer{{ServerURL: srv.URL}},
},
},
testMenderPieces{
MenderPieces: MenderPieces{
store: ms,
},
},
)
ms.WriteAll(datastore.AuthTokenName, []byte("tokendata"))
err := mender.Authorize()
assert.NoError(t, err)
srv.Auth.Verify = true
srv.Auth.Token = []byte("tokendata")
// 1. log upload successful
logs := []byte(`{ "messages":
[{ "time": "12:12:12", "level": "error", "msg": "log foo" },
{ "time": "12:12:13", "level": "debug", "msg": "log bar" }]
}`)
err = mender.UploadLog(
&datastore.UpdateInfo{
ID: "foobar",
},
logs,
)
assert.Nil(t, err)
assert.JSONEq(t, `{
"messages": [
{
"time": "12:12:12",
"level": "error",
"msg": "log foo"
},
{
"time": "12:12:13",
"level": "debug",
"msg": "log bar"
}
]}`, string(srv.Log.Logs))
// 2. pretend authorization fails, server expects a different token
srv.Auth.Token = []byte("footoken")
err = mender.UploadLog(
&datastore.UpdateInfo{
ID: "foobar",
},
logs,
)
assert.NotNil(t, err)
}
func TestAuthToken(t *testing.T) {
ts := cltest.NewClientTestServer()
defer ts.Close()
ms := store.NewMemStore()
mender := newTestMender(nil,
menderConfig{
menderConfigFromFile: menderConfigFromFile{
Servers: []client.MenderServer{{ServerURL: ts.URL}},
},
},
testMenderPieces{
MenderPieces: MenderPieces{
store: ms,
},
},
)
ms.WriteAll(datastore.AuthTokenName, []byte("tokendata"))
token, err := ms.ReadAll(datastore.AuthTokenName)
assert.NoError(t, err)
assert.Equal(t, []byte("tokendata"), token)
ts.Update.Unauthorized = true
ts.Update.Current = client.CurrentUpdate{
"fake-id",
"foo-bar",
}
td, _ := ioutil.TempDir("", "mender-install-update-")
defer os.RemoveAll(td)
artifactInfo := path.Join(td, "artifact_info")
ioutil.WriteFile(artifactInfo, []byte("artifact_name=fake-id"), 0600)
deviceType := path.Join(td, "device_type")
ioutil.WriteFile(deviceType, []byte("device_type=foo-bar"), 0600)
mender.artifactInfoFile = artifactInfo
mender.deviceTypeFile = deviceType
_, updErr := mender.CheckUpdate()
assert.EqualError(t, errors.Cause(updErr), client.ErrNotAuthorized.Error())
token, err = ms.ReadAll(datastore.AuthTokenName)
assert.Equal(t, os.ErrNotExist, err)
assert.Empty(t, token)
}
func TestMenderInventoryRefresh(t *testing.T) {
// create temp dir
td, _ := ioutil.TempDir("", "mender-install-update-")
defer os.RemoveAll(td)
// prepare fake artifactInfo file, it is read when submitting inventory to
// fill some default fields (device_type, artifact_name)
artifactInfo := path.Join(td, "artifact_info")
ioutil.WriteFile(artifactInfo, []byte("artifact_name=fake-id"), 0600)
deviceType := path.Join(td, "device_type")
ioutil.WriteFile(deviceType, []byte("device_type=foo-bar"), 0600)
srv := cltest.NewClientTestServer()
defer srv.Close()
ms := store.NewMemStore()
mender := newTestMender(nil,
menderConfig{
menderConfigFromFile: menderConfigFromFile{
Servers: []client.MenderServer{{ServerURL: srv.URL}},
},
},
testMenderPieces{
MenderPieces: MenderPieces{
store: ms,
},
},
)
mender.artifactInfoFile = artifactInfo
mender.deviceTypeFile = deviceType
ms.WriteAll(datastore.AuthTokenName, []byte("tokendata"))
merr := mender.Authorize()
assert.NoError(t, merr)
// prepare fake inventory scripts
// 1. setup a temporary path $TMPDIR/mendertest<random>/inventory
tdir, err := ioutil.TempDir("", "mendertest")
assert.NoError(t, err)
invpath := path.Join(tdir, "inventory")
err = os.MkdirAll(invpath, os.FileMode(syscall.S_IRWXU))
assert.NoError(t, err)
defer os.RemoveAll(tdir)
oldDefaultPathDataDir := defaultPathDataDir
// override datadir path for subsequent getDataDirPath() calls
defaultPathDataDir = tdir
defer func() {
// restore old datadir path
defaultPathDataDir = oldDefaultPathDataDir
}()
// 1a. no scripts hence no inventory data, submit should have been
// called with default inventory attributes only
srv.Auth.Verify = true
srv.Auth.Token = []byte("tokendata")
err = mender.InventoryRefresh()
assert.Nil(t, err)
assert.True(t, srv.Inventory.Called)
exp := []client.InventoryAttribute{
{Name: "device_type", Value: "foo-bar"},
{Name: "artifact_name", Value: "fake-id"},
{Name: "mender_client_version", Value: "unknown"},
}
for _, a := range exp {
assert.Contains(t, srv.Inventory.Attrs, a)
}
// 2. fake inventory script
err = ioutil.WriteFile(path.Join(invpath, "mender-inventory-foo"),
[]byte(`#!/bin/sh
echo foo=bar`),
os.FileMode(syscall.S_IRWXU))
assert.NoError(t, err)
srv.Reset()
srv.Auth.Verify = true
srv.Auth.Token = []byte("tokendata")
err = mender.InventoryRefresh()
assert.Nil(t, err)
exp = []client.InventoryAttribute{
{Name: "device_type", Value: "foo-bar"},
{Name: "artifact_name", Value: "fake-id"},
{Name: "mender_client_version", Value: "unknown"},
{Name: "foo", Value: "bar"},
}
for _, a := range exp {
assert.Contains(t, srv.Inventory.Attrs, a)
}
// no artifact name should error
ioutil.WriteFile(artifactInfo, []byte(""), 0600)
err = mender.InventoryRefresh()
assert.Error(t, err)
assert.EqualError(t, errors.Cause(err), errNoArtifactName.Error())
// 3. pretend client is no longer authorized
srv.Auth.Token = []byte("footoken")
err = mender.InventoryRefresh()
assert.NotNil(t, err)
}
func MakeFakeUpdate(data string) (string, error) {
f, err := ioutil.TempFile("", "test_update")
if err != nil {
return "", err
}
defer f.Close()
if len(data) > 0 {
if _, err := f.WriteString(data); err != nil {
return "", err
}
}
return f.Name(), nil
}
type rc struct {
*bytes.Buffer
}
func (r *rc) Close() error {
return nil
}
const (
PublicRSAKey = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDSTLzZ9hQq3yBB+dMDVbKem6ia
v1J6opg6DICKkQ4M/yhlw32BCGm2ArM3VwQRgq6Q1sNSq953n5c1EO3Xcy/qTAKc
XwaUNml5EhW79AdibBXZiZt8fMhCjUd/4ce3rLNjnbIn1o9L6pzV4CcVJ8+iNhne
5vbA+63vRCnrc8QuYwIDAQAB
-----END PUBLIC KEY-----`
PrivateRSAKey = `-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDSTLzZ9hQq3yBB+dMDVbKem6iav1J6opg6DICKkQ4M/yhlw32B
CGm2ArM3VwQRgq6Q1sNSq953n5c1EO3Xcy/qTAKcXwaUNml5EhW79AdibBXZiZt8
fMhCjUd/4ce3rLNjnbIn1o9L6pzV4CcVJ8+iNhne5vbA+63vRCnrc8QuYwIDAQAB
AoGAQKIRELQOsrZsxZowfj/ia9jPUvAmO0apnn2lK/E07k2lbtFMS1H4m1XtGr8F
oxQU7rLyyP/FmeJUqJyRXLwsJzma13OpxkQtZmRpL9jEwevnunHYJfceVapQOJ7/
6Oz0pPWEq39GCn+tTMtgSmkEaSH8Ki9t32g9KuQIKBB2hbECQQDsg7D5fHQB1BXG
HJm9JmYYX0Yk6Z2SWBr4mLO0C4hHBnV5qPCLyevInmaCV2cOjDZ5Sz6iF5RK5mw7
qzvFa8ePAkEA46Anom3cNXO5pjfDmn2CoqUvMeyrJUFL5aU6W1S6iFprZ/YwdHcC
kS5yTngwVOmcnT65Vnycygn+tZan2A0h7QJBAJNlowZovDdjgEpeCqXp51irD6Dz
gsLwa6agK+Y6Ba0V5mJyma7UoT//D62NYOmdElnXPepwvXdMUQmCtpZbjBsCQD5H
VHDJlCV/yzyiJz9+tZ5giaAkO9NOoUBsy6GvdfXWn2prXmiPI0GrrpSvp7Gj1Tjk
r3rtT0ysHWd7l+Kx/SUCQGlitd5RDfdHl+gKrCwhNnRG7FzRLv5YOQV81+kh7SkU
73TXPIqLESVrqWKDfLwfsfEpV248MSRou+y0O1mtFpo=
-----END RSA PRIVATE KEY-----`
)
func MakeRootfsImageArtifact(version int, signed bool) (io.ReadCloser, error) {
upd, err := MakeFakeUpdate("test update")
if err != nil {
return nil, err
}
defer os.Remove(upd)
art := bytes.NewBuffer(nil)
var aw *awriter.Writer
comp := artifact.NewCompressorGzip()
if !signed {
aw = awriter.NewWriter(art, comp)
} else {
s := artifact.NewSigner([]byte(PrivateRSAKey))
aw = awriter.NewWriterSigned(art, comp, s)
}
var u handlers.Composer
switch version {
case 1:
u = handlers.NewRootfsV1(upd)
case 2:
u = handlers.NewRootfsV2(upd)
case 3:
u = handlers.NewRootfsV3(upd)
}
updates := &awriter.Updates{Updates: []handlers.Composer{u}}
err = aw.WriteArtifact(&awriter.WriteArtifactArgs{
Format: "mender",
Version: version,
Devices: []string{"vexpress-qemu"},
Name: "mender-1.1",
Updates: updates,
Scripts: nil,
Provides: &artifact.ArtifactProvides{
ArtifactName: "TestName",
},
Depends: &artifact.ArtifactDepends{
CompatibleDevices: []string{"vexpress-qemu"},
},
TypeInfoV3: &artifact.TypeInfoV3{},
})
if err != nil {
return nil, err
}
return &rc{art}, nil
}
type mockReader struct {
mock.Mock
}
func (m *mockReader) Read(p []byte) (int, error) {
ret := m.Called()
return ret.Get(0).(int), ret.Error(1)
}
func TestMenderStoreUpdate(t *testing.T) {
// create temp dir
td, _ := ioutil.TempDir("", "mender-install-update-")
defer os.RemoveAll(td)
// prepare fake artifactInfo file, with bogus
deviceType := path.Join(td, "device_type")
mender := newTestMender(nil, menderConfig{},
testMenderPieces{
MenderPieces: MenderPieces{
dualRootfsDevice: &fakeDevice{consumeUpdate: true},
},
},
)
mender.deviceTypeFile = deviceType
// try some failure scenarios first
// EOF
_, err := mender.ReadArtifactHeaders(ioutil.NopCloser(&bytes.Buffer{}))
assert.Error(t, err)
// some error from reader
mr := mockReader{}
mr.On("Read").Return(0, errors.New("failed"))
_, err = mender.ReadArtifactHeaders(ioutil.NopCloser(&mr))
assert.Error(t, err)
// make a fake update artifact
upd, err := MakeRootfsImageArtifact(1, false)
assert.NoError(t, err)
assert.NotNil(t, upd)
// setup some bogus device_type so that we don't match the update
ioutil.WriteFile(deviceType, []byte("device_type=bogusdevicetype\n"), 0644)
_, err = mender.ReadArtifactHeaders(upd)
assert.Error(t, err)
// try with a legit device_type
upd, err = MakeRootfsImageArtifact(1, false)
assert.NoError(t, err)
assert.NotNil(t, upd)
ioutil.WriteFile(deviceType, []byte("device_type=vexpress-qemu\n"), 0644)
installer, err := mender.ReadArtifactHeaders(upd)
require.NoError(t, err)
err = installer.StorePayloads()
assert.NoError(t, err)
// now try with device throwing errors durin ginstall
upd, err = MakeRootfsImageArtifact(1, false)
assert.NoError(t, err)
assert.NotNil(t, upd)
mender = newTestMender(nil, menderConfig{},
testMenderPieces{
MenderPieces: MenderPieces{
dualRootfsDevice: &fakeDevice{retStoreUpdate: errors.New("failed")},
},
},
)
mender.deviceTypeFile = deviceType
installer, err = mender.ReadArtifactHeaders(upd)
require.NoError(t, err)
err = installer.StorePayloads()
assert.Error(t, err)
}
func TestMenderFetchUpdate(t *testing.T) {
srv := cltest.NewClientTestServer()
defer srv.Close()
srv.Update.Has = true
ms := store.NewMemStore()
mender := newTestMender(nil,
menderConfig{
menderConfigFromFile: menderConfigFromFile{
ServerURL: srv.URL,
},
},
testMenderPieces{
MenderPieces: MenderPieces{
store: ms,
},
})
ms.WriteAll(datastore.AuthTokenName, []byte("tokendata"))
merr := mender.Authorize()
assert.NoError(t, merr)
// populate download data with random bytes
rdata := bytes.Buffer{}
rcount := 8192
_, err := io.CopyN(&rdata, rand.Reader, int64(rcount))
assert.NoError(t, err)
assert.Equal(t, rcount, rdata.Len())
rbytes := rdata.Bytes()
_, err = io.Copy(&srv.UpdateDownload.Data, &rdata)
assert.NoError(t, err)
assert.Equal(t, rcount, len(rbytes))
img, sz, err := mender.FetchUpdate(srv.URL + "/api/devices/v1/download")
assert.NoError(t, err)
assert.NotNil(t, img)
assert.EqualValues(t, len(rbytes), sz)
dl := bytes.Buffer{}
_, err = io.Copy(&dl, img)
assert.NoError(t, err)
assert.EqualValues(t, sz, dl.Len())
assert.True(t, bytes.Equal(rbytes, dl.Bytes()))
}
// TestReauthorization triggers the reauthorization mechanic when
// issuing an API request and getting a 401 response code.
// In this test we use check update as our reference API-request for
// convenience, but the behaviour is similar across all API-requests
// (excluding auth_request). The test then changes the authorization
// token on the server, causing the first checkUpdate to retry after
// doing reauthorization, which causes the server to serve the request
// the other time around. Lastly we force the server to only give
// unauthorized responses, causing the request to fail and an error
// returned.
func TestReauthorization(t *testing.T) {
// Create temporary artifact_info / device_type files
artifactInfoFile, _ := os.Create("artifact_info")
devInfoFile, _ := os.Create("device_type")
defer os.Remove("artifact_info")
defer os.Remove("device_type")
// add artifact- / device name
artifactInfoFile.WriteString("artifact_name=mender-image")
devInfoFile.WriteString("device_type=dev")
// Create and configure server
srv := cltest.NewClientTestServer()
defer srv.Close()