cp_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cp
  14. import (
  15. "archive/tar"
  16. "bytes"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "net/http"
  21. "os"
  22. "path"
  23. "path/filepath"
  24. "reflect"
  25. "strings"
  26. "testing"
  27. "github.com/stretchr/testify/assert"
  28. "github.com/stretchr/testify/require"
  29. "k8s.io/api/core/v1"
  30. "k8s.io/apimachinery/pkg/api/errors"
  31. "k8s.io/apimachinery/pkg/runtime"
  32. "k8s.io/apimachinery/pkg/runtime/schema"
  33. "k8s.io/cli-runtime/pkg/genericclioptions"
  34. "k8s.io/client-go/rest/fake"
  35. kexec "k8s.io/kubectl/pkg/cmd/exec"
  36. cmdtesting "k8s.io/kubectl/pkg/cmd/testing"
  37. "k8s.io/kubectl/pkg/scheme"
  38. )
  39. type FileType int
  40. const (
  41. RegularFile FileType = 0
  42. SymLink FileType = 1
  43. RegexFile FileType = 2
  44. )
  45. func TestExtractFileSpec(t *testing.T) {
  46. tests := []struct {
  47. spec string
  48. expectedPod string
  49. expectedNamespace string
  50. expectedFile string
  51. expectErr bool
  52. }{
  53. {
  54. spec: "namespace/pod:/some/file",
  55. expectedPod: "pod",
  56. expectedNamespace: "namespace",
  57. expectedFile: "/some/file",
  58. },
  59. {
  60. spec: "pod:/some/file",
  61. expectedPod: "pod",
  62. expectedFile: "/some/file",
  63. },
  64. {
  65. spec: "/some/file",
  66. expectedFile: "/some/file",
  67. },
  68. {
  69. spec: ":file:not:exist:in:local:filesystem",
  70. expectErr: true,
  71. },
  72. {
  73. spec: "namespace/pod/invalid:/some/file",
  74. expectErr: true,
  75. },
  76. {
  77. spec: "pod:/some/filenamewith:in",
  78. expectedPod: "pod",
  79. expectedFile: "/some/filenamewith:in",
  80. },
  81. }
  82. for _, test := range tests {
  83. spec, err := extractFileSpec(test.spec)
  84. if test.expectErr && err == nil {
  85. t.Errorf("unexpected non-error")
  86. continue
  87. }
  88. if err != nil && !test.expectErr {
  89. t.Errorf("unexpected error: %v", err)
  90. continue
  91. }
  92. if spec.PodName != test.expectedPod {
  93. t.Errorf("expected: %s, saw: %s", test.expectedPod, spec.PodName)
  94. }
  95. if spec.PodNamespace != test.expectedNamespace {
  96. t.Errorf("expected: %s, saw: %s", test.expectedNamespace, spec.PodNamespace)
  97. }
  98. if spec.File != test.expectedFile {
  99. t.Errorf("expected: %s, saw: %s", test.expectedFile, spec.File)
  100. }
  101. }
  102. }
  103. func TestGetPrefix(t *testing.T) {
  104. tests := []struct {
  105. input string
  106. expected string
  107. }{
  108. {
  109. input: "/foo/bar",
  110. expected: "foo/bar",
  111. },
  112. {
  113. input: "foo/bar",
  114. expected: "foo/bar",
  115. },
  116. }
  117. for _, test := range tests {
  118. out := getPrefix(test.input)
  119. if out != test.expected {
  120. t.Errorf("expected: %s, saw: %s", test.expected, out)
  121. }
  122. }
  123. }
  124. func TestStripPathShortcuts(t *testing.T) {
  125. tests := []struct {
  126. name string
  127. input string
  128. expected string
  129. }{
  130. {
  131. name: "test single path shortcut prefix",
  132. input: "../foo/bar",
  133. expected: "foo/bar",
  134. },
  135. {
  136. name: "test multiple path shortcuts",
  137. input: "../../foo/bar",
  138. expected: "foo/bar",
  139. },
  140. {
  141. name: "test multiple path shortcuts with absolute path",
  142. input: "/tmp/one/two/../../foo/bar",
  143. expected: "tmp/foo/bar",
  144. },
  145. {
  146. name: "test multiple path shortcuts with no named directory",
  147. input: "../../",
  148. expected: "",
  149. },
  150. {
  151. name: "test multiple path shortcuts with no named directory and no trailing slash",
  152. input: "../..",
  153. expected: "",
  154. },
  155. {
  156. name: "test multiple path shortcuts with absolute path and filename containing leading dots",
  157. input: "/tmp/one/two/../../foo/..bar",
  158. expected: "tmp/foo/..bar",
  159. },
  160. {
  161. name: "test multiple path shortcuts with no named directory and filename containing leading dots",
  162. input: "../...foo",
  163. expected: "...foo",
  164. },
  165. {
  166. name: "test filename containing leading dots",
  167. input: "...foo",
  168. expected: "...foo",
  169. },
  170. {
  171. name: "test root directory",
  172. input: "/",
  173. expected: "",
  174. },
  175. }
  176. for _, test := range tests {
  177. out := stripPathShortcuts(test.input)
  178. if out != test.expected {
  179. t.Errorf("expected: %s, saw: %s", test.expected, out)
  180. }
  181. }
  182. }
  183. func TestIsDestRelative(t *testing.T) {
  184. tests := []struct {
  185. base string
  186. dest string
  187. relative bool
  188. }{
  189. {
  190. base: "/dir",
  191. dest: "/dir/../link",
  192. relative: false,
  193. },
  194. {
  195. base: "/dir",
  196. dest: "/dir/../../link",
  197. relative: false,
  198. },
  199. {
  200. base: "/dir",
  201. dest: "/link",
  202. relative: false,
  203. },
  204. {
  205. base: "/dir",
  206. dest: "/dir/link",
  207. relative: true,
  208. },
  209. {
  210. base: "/dir",
  211. dest: "/dir/int/../link",
  212. relative: true,
  213. },
  214. {
  215. base: "dir",
  216. dest: "dir/link",
  217. relative: true,
  218. },
  219. {
  220. base: "dir",
  221. dest: "dir/int/../link",
  222. relative: true,
  223. },
  224. {
  225. base: "dir",
  226. dest: "dir/../../link",
  227. relative: false,
  228. },
  229. }
  230. for i, test := range tests {
  231. t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
  232. if test.relative != isDestRelative(test.base, test.dest) {
  233. t.Errorf("unexpected result for: base %q, dest %q", test.base, test.dest)
  234. }
  235. })
  236. }
  237. }
  238. func checkErr(t *testing.T, err error) {
  239. if err != nil {
  240. t.Errorf("unexpected error: %v", err)
  241. t.FailNow()
  242. }
  243. }
  244. func TestTarUntar(t *testing.T) {
  245. dir, err := ioutil.TempDir("", "input")
  246. checkErr(t, err)
  247. dir2, err := ioutil.TempDir("", "output")
  248. checkErr(t, err)
  249. dir3, err := ioutil.TempDir("", "dir")
  250. checkErr(t, err)
  251. dir = dir + "/"
  252. defer func() {
  253. os.RemoveAll(dir)
  254. os.RemoveAll(dir2)
  255. os.RemoveAll(dir3)
  256. }()
  257. files := []struct {
  258. name string
  259. nameList []string
  260. data string
  261. omitted bool
  262. fileType FileType
  263. }{
  264. {
  265. name: "foo",
  266. data: "foobarbaz",
  267. fileType: RegularFile,
  268. },
  269. {
  270. name: "dir/blah",
  271. data: "bazblahfoo",
  272. fileType: RegularFile,
  273. },
  274. {
  275. name: "some/other/directory/",
  276. data: "with more data here",
  277. fileType: RegularFile,
  278. },
  279. {
  280. name: "blah",
  281. data: "same file name different data",
  282. fileType: RegularFile,
  283. },
  284. {
  285. name: "gakki",
  286. data: "tmp/gakki",
  287. omitted: true,
  288. fileType: SymLink,
  289. },
  290. {
  291. name: "relative_to_dest",
  292. data: path.Join(dir2, "foo"),
  293. omitted: true,
  294. fileType: SymLink,
  295. },
  296. {
  297. name: "tricky_relative",
  298. data: path.Join(dir3, "xyz"),
  299. omitted: true,
  300. fileType: SymLink,
  301. },
  302. {
  303. name: "absolute_path",
  304. data: "/tmp/gakki",
  305. omitted: true,
  306. fileType: SymLink,
  307. },
  308. {
  309. name: "blah*",
  310. nameList: []string{"blah1", "blah2"},
  311. data: "regexp file name",
  312. fileType: RegexFile,
  313. },
  314. }
  315. for _, file := range files {
  316. filepath := path.Join(dir, file.name)
  317. if err := os.MkdirAll(path.Dir(filepath), 0755); err != nil {
  318. t.Fatalf("unexpected error: %v", err)
  319. }
  320. if file.fileType == RegularFile {
  321. createTmpFile(t, filepath, file.data)
  322. } else if file.fileType == SymLink {
  323. err := os.Symlink(file.data, filepath)
  324. if err != nil {
  325. t.Fatalf("unexpected error: %v", err)
  326. }
  327. } else if file.fileType == RegexFile {
  328. for _, fileName := range file.nameList {
  329. createTmpFile(t, path.Join(dir, fileName), file.data)
  330. }
  331. } else {
  332. t.Fatalf("unexpected file type: %v", file)
  333. }
  334. }
  335. opts := NewCopyOptions(genericclioptions.NewTestIOStreamsDiscard())
  336. writer := &bytes.Buffer{}
  337. if err := makeTar(dir, dir, writer); err != nil {
  338. t.Fatalf("unexpected error: %v", err)
  339. }
  340. reader := bytes.NewBuffer(writer.Bytes())
  341. if err := opts.untarAll(fileSpec{}, reader, dir2, ""); err != nil {
  342. t.Fatalf("unexpected error: %v", err)
  343. }
  344. for _, file := range files {
  345. absPath := filepath.Join(dir2, strings.TrimPrefix(dir, os.TempDir()))
  346. filePath := filepath.Join(absPath, file.name)
  347. if file.fileType == RegularFile {
  348. cmpFileData(t, filePath, file.data)
  349. } else if file.fileType == SymLink {
  350. dest, err := os.Readlink(filePath)
  351. if file.omitted {
  352. if err != nil && strings.Contains(err.Error(), "no such file or directory") {
  353. continue
  354. }
  355. t.Fatalf("expected to omit symlink for %s", filePath)
  356. }
  357. if err != nil {
  358. t.Fatalf("unexpected error: %v", err)
  359. }
  360. if file.data != dest {
  361. t.Fatalf("expected: %s, saw: %s", file.data, dest)
  362. }
  363. } else if file.fileType == RegexFile {
  364. for _, fileName := range file.nameList {
  365. cmpFileData(t, path.Join(dir, fileName), file.data)
  366. }
  367. } else {
  368. t.Fatalf("unexpected file type: %v", file)
  369. }
  370. }
  371. }
  372. func TestTarUntarWrongPrefix(t *testing.T) {
  373. dir, err := ioutil.TempDir("", "input")
  374. checkErr(t, err)
  375. dir2, err := ioutil.TempDir("", "output")
  376. checkErr(t, err)
  377. dir = dir + "/"
  378. defer func() {
  379. os.RemoveAll(dir)
  380. os.RemoveAll(dir2)
  381. }()
  382. filepath := path.Join(dir, "foo")
  383. if err := os.MkdirAll(path.Dir(filepath), 0755); err != nil {
  384. t.Fatalf("unexpected error: %v", err)
  385. }
  386. createTmpFile(t, filepath, "sample data")
  387. opts := NewCopyOptions(genericclioptions.NewTestIOStreamsDiscard())
  388. writer := &bytes.Buffer{}
  389. if err := makeTar(dir, dir, writer); err != nil {
  390. t.Fatalf("unexpected error: %v", err)
  391. }
  392. reader := bytes.NewBuffer(writer.Bytes())
  393. err = opts.untarAll(fileSpec{}, reader, dir2, "verylongprefix-showing-the-tar-was-tempered-with")
  394. if err == nil || !strings.Contains(err.Error(), "tar contents corrupted") {
  395. t.Fatalf("unexpected error: %v", err)
  396. }
  397. }
  398. func TestTarDestinationName(t *testing.T) {
  399. dir, err := ioutil.TempDir(os.TempDir(), "input")
  400. dir2, err2 := ioutil.TempDir(os.TempDir(), "output")
  401. if err != nil || err2 != nil {
  402. t.Errorf("unexpected error: %v | %v", err, err2)
  403. t.FailNow()
  404. }
  405. defer func() {
  406. if err := os.RemoveAll(dir); err != nil {
  407. t.Errorf("Unexpected error cleaning up: %v", err)
  408. }
  409. if err := os.RemoveAll(dir2); err != nil {
  410. t.Errorf("Unexpected error cleaning up: %v", err)
  411. }
  412. }()
  413. files := []struct {
  414. name string
  415. data string
  416. }{
  417. {
  418. name: "foo",
  419. data: "foobarbaz",
  420. },
  421. {
  422. name: "dir/blah",
  423. data: "bazblahfoo",
  424. },
  425. {
  426. name: "some/other/directory",
  427. data: "with more data here",
  428. },
  429. {
  430. name: "blah",
  431. data: "same file name different data",
  432. },
  433. }
  434. // ensure files exist on disk
  435. for _, file := range files {
  436. filepath := path.Join(dir, file.name)
  437. if err := os.MkdirAll(path.Dir(filepath), 0755); err != nil {
  438. t.Errorf("unexpected error: %v", err)
  439. t.FailNow()
  440. }
  441. createTmpFile(t, filepath, file.data)
  442. }
  443. reader, writer := io.Pipe()
  444. go func() {
  445. if err := makeTar(dir, dir2, writer); err != nil {
  446. t.Errorf("unexpected error: %v", err)
  447. }
  448. }()
  449. tarReader := tar.NewReader(reader)
  450. for {
  451. hdr, err := tarReader.Next()
  452. if err == io.EOF {
  453. break
  454. } else if err != nil {
  455. t.Errorf("unexpected error: %v", err)
  456. t.FailNow()
  457. }
  458. if !strings.HasPrefix(hdr.Name, path.Base(dir2)) {
  459. t.Errorf("expected %q as destination filename prefix, saw: %q", path.Base(dir2), hdr.Name)
  460. }
  461. }
  462. }
  463. func TestBadTar(t *testing.T) {
  464. dir, err := ioutil.TempDir(os.TempDir(), "dest")
  465. if err != nil {
  466. t.Errorf("unexpected error: %v ", err)
  467. t.FailNow()
  468. }
  469. defer os.RemoveAll(dir)
  470. // More or less cribbed from https://golang.org/pkg/archive/tar/#example__minimal
  471. var buf bytes.Buffer
  472. tw := tar.NewWriter(&buf)
  473. var files = []struct {
  474. name string
  475. body string
  476. }{
  477. {"/prefix/foo/bar/../../home/bburns/names.txt", "Down and back"},
  478. }
  479. for _, file := range files {
  480. hdr := &tar.Header{
  481. Name: file.name,
  482. Mode: 0600,
  483. Size: int64(len(file.body)),
  484. }
  485. if err := tw.WriteHeader(hdr); err != nil {
  486. t.Errorf("unexpected error: %v ", err)
  487. t.FailNow()
  488. }
  489. if _, err := tw.Write([]byte(file.body)); err != nil {
  490. t.Errorf("unexpected error: %v ", err)
  491. t.FailNow()
  492. }
  493. }
  494. if err := tw.Close(); err != nil {
  495. t.Errorf("unexpected error: %v ", err)
  496. t.FailNow()
  497. }
  498. opts := NewCopyOptions(genericclioptions.NewTestIOStreamsDiscard())
  499. if err := opts.untarAll(fileSpec{}, &buf, dir, "/prefix"); err != nil {
  500. t.Errorf("unexpected error: %v ", err)
  501. t.FailNow()
  502. }
  503. for _, file := range files {
  504. _, err := os.Stat(path.Join(dir, path.Clean(file.name[len("/prefix"):])))
  505. if err != nil {
  506. t.Errorf("Error finding file: %v", err)
  507. }
  508. }
  509. }
  510. func TestCopyToPod(t *testing.T) {
  511. tf := cmdtesting.NewTestFactory().WithNamespace("test")
  512. ns := scheme.Codecs.WithoutConversion()
  513. codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
  514. tf.Client = &fake.RESTClient{
  515. GroupVersion: schema.GroupVersion{Group: "", Version: "v1"},
  516. NegotiatedSerializer: ns,
  517. Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
  518. responsePod := &v1.Pod{}
  519. return &http.Response{StatusCode: http.StatusNotFound, Header: cmdtesting.DefaultHeader(), Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(codec, responsePod))))}, nil
  520. }),
  521. }
  522. tf.ClientConfigVal = cmdtesting.DefaultClientConfig()
  523. ioStreams, _, _, _ := genericclioptions.NewTestIOStreams()
  524. cmd := NewCmdCp(tf, ioStreams)
  525. srcFile, err := ioutil.TempDir("", "test")
  526. if err != nil {
  527. t.Errorf("unexpected error: %v", err)
  528. t.FailNow()
  529. }
  530. defer os.RemoveAll(srcFile)
  531. tests := map[string]struct {
  532. dest string
  533. expectedErr bool
  534. }{
  535. "copy to directory": {
  536. dest: "/tmp/",
  537. expectedErr: false,
  538. },
  539. "copy to root": {
  540. dest: "/",
  541. expectedErr: false,
  542. },
  543. "copy to empty file name": {
  544. dest: "",
  545. expectedErr: true,
  546. },
  547. }
  548. for name, test := range tests {
  549. opts := NewCopyOptions(ioStreams)
  550. src := fileSpec{
  551. File: srcFile,
  552. }
  553. dest := fileSpec{
  554. PodNamespace: "pod-ns",
  555. PodName: "pod-name",
  556. File: test.dest,
  557. }
  558. opts.Complete(tf, cmd)
  559. t.Run(name, func(t *testing.T) {
  560. err = opts.copyToPod(src, dest, &kexec.ExecOptions{})
  561. //If error is NotFound error , it indicates that the
  562. //request has been sent correctly.
  563. //Treat this as no error.
  564. if test.expectedErr && errors.IsNotFound(err) {
  565. t.Errorf("expected error but didn't get one")
  566. }
  567. if !test.expectedErr && !errors.IsNotFound(err) {
  568. t.Errorf("unexpected error: %v", err)
  569. }
  570. })
  571. }
  572. }
  573. func TestCopyToPodNoPreserve(t *testing.T) {
  574. tf := cmdtesting.NewTestFactory().WithNamespace("test")
  575. ns := scheme.Codecs.WithoutConversion()
  576. codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
  577. tf.Client = &fake.RESTClient{
  578. GroupVersion: schema.GroupVersion{Group: "", Version: "v1"},
  579. NegotiatedSerializer: ns,
  580. Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
  581. responsePod := &v1.Pod{}
  582. return &http.Response{StatusCode: http.StatusNotFound, Header: cmdtesting.DefaultHeader(), Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(codec, responsePod))))}, nil
  583. }),
  584. }
  585. tf.ClientConfigVal = cmdtesting.DefaultClientConfig()
  586. ioStreams, _, _, _ := genericclioptions.NewTestIOStreams()
  587. cmd := NewCmdCp(tf, ioStreams)
  588. srcFile, err := ioutil.TempDir("", "test")
  589. if err != nil {
  590. t.Errorf("unexpected error: %v", err)
  591. t.FailNow()
  592. }
  593. defer os.RemoveAll(srcFile)
  594. tests := map[string]struct {
  595. expectedCmd []string
  596. nopreserve bool
  597. }{
  598. "copy to pod no preserve user and permissions": {
  599. expectedCmd: []string{"tar", "--no-same-permissions", "--no-same-owner", "-xmf", "-", "-C", "."},
  600. nopreserve: true,
  601. },
  602. "copy to pod preserve user and permissions": {
  603. expectedCmd: []string{"tar", "-xmf", "-", "-C", "."},
  604. nopreserve: false,
  605. },
  606. }
  607. opts := NewCopyOptions(ioStreams)
  608. src := fileSpec{
  609. File: srcFile,
  610. }
  611. dest := fileSpec{
  612. PodNamespace: "pod-ns",
  613. PodName: "pod-name",
  614. File: "foo",
  615. }
  616. opts.Complete(tf, cmd)
  617. for name, test := range tests {
  618. t.Run(name, func(t *testing.T) {
  619. options := &kexec.ExecOptions{}
  620. opts.NoPreserve = test.nopreserve
  621. err = opts.copyToPod(src, dest, options)
  622. if !(reflect.DeepEqual(test.expectedCmd, options.Command)) {
  623. t.Errorf("expected cmd: %v, got: %v", test.expectedCmd, options.Command)
  624. }
  625. })
  626. }
  627. }
  628. func TestValidate(t *testing.T) {
  629. tests := []struct {
  630. name string
  631. args []string
  632. expectedErr bool
  633. }{
  634. {
  635. name: "Validate Succeed",
  636. args: []string{"1", "2"},
  637. expectedErr: false,
  638. },
  639. {
  640. name: "Validate Fail",
  641. args: []string{"1", "2", "3"},
  642. expectedErr: true,
  643. },
  644. }
  645. tf := cmdtesting.NewTestFactory()
  646. ioStreams, _, _, _ := genericclioptions.NewTestIOStreams()
  647. opts := NewCopyOptions(ioStreams)
  648. cmd := NewCmdCp(tf, ioStreams)
  649. for _, test := range tests {
  650. t.Run(test.name, func(t *testing.T) {
  651. err := opts.Validate(cmd, test.args)
  652. if (err != nil) != test.expectedErr {
  653. t.Errorf("expected error: %v, saw: %v, error: %v", test.expectedErr, err != nil, err)
  654. }
  655. })
  656. }
  657. }
  658. func TestUntar(t *testing.T) {
  659. testdir, err := ioutil.TempDir("", "test-untar")
  660. require.NoError(t, err)
  661. defer os.RemoveAll(testdir)
  662. t.Logf("Test base: %s", testdir)
  663. basedir := filepath.Join(testdir, "base")
  664. type file struct {
  665. path string
  666. linkTarget string // For link types
  667. expected string // Expect to find the file here (or not, if empty)
  668. }
  669. files := []file{{
  670. // Absolute file within dest
  671. path: filepath.Join(basedir, "abs"),
  672. expected: filepath.Join(basedir, basedir, "abs"),
  673. }, { // Absolute file outside dest
  674. path: filepath.Join(testdir, "abs-out"),
  675. expected: filepath.Join(basedir, testdir, "abs-out"),
  676. }, { // Absolute nested file within dest
  677. path: filepath.Join(basedir, "nested/nest-abs"),
  678. expected: filepath.Join(basedir, basedir, "nested/nest-abs"),
  679. }, { // Absolute nested file outside dest
  680. path: filepath.Join(basedir, "nested/../../nest-abs-out"),
  681. expected: filepath.Join(basedir, testdir, "nest-abs-out"),
  682. }, { // Relative file inside dest
  683. path: "relative",
  684. expected: filepath.Join(basedir, "relative"),
  685. }, { // Relative file outside dest
  686. path: "../unrelative",
  687. expected: "",
  688. }, { // Nested relative file inside dest
  689. path: "nested/nest-rel",
  690. expected: filepath.Join(basedir, "nested/nest-rel"),
  691. }, { // Nested relative file outside dest
  692. path: "nested/../../nest-unrelative",
  693. expected: "",
  694. }}
  695. links := []file{}
  696. for _, f := range files {
  697. links = append(links, file{
  698. path: f.path + "-innerlink",
  699. linkTarget: "link-target",
  700. expected: "",
  701. }, file{
  702. path: f.path + "-innerlink-abs",
  703. linkTarget: filepath.Join(basedir, "link-target"),
  704. expected: "",
  705. }, file{
  706. path: f.path + "-backlink",
  707. linkTarget: filepath.Join("..", "link-target"),
  708. expected: "",
  709. }, file{
  710. path: f.path + "-outerlink-abs",
  711. linkTarget: filepath.Join(testdir, "link-target"),
  712. expected: "",
  713. })
  714. if f.expected != "" {
  715. // outerlink is the number of backticks to escape to testdir
  716. outerlink, _ := filepath.Rel(f.expected, testdir)
  717. links = append(links, file{
  718. path: f.path + "outerlink",
  719. linkTarget: filepath.Join(outerlink, "link-target"),
  720. expected: "",
  721. })
  722. }
  723. }
  724. files = append(files, links...)
  725. // Test back-tick escaping through a symlink.
  726. files = append(files,
  727. file{
  728. path: "nested/again/back-link",
  729. linkTarget: "../../nested",
  730. expected: "",
  731. },
  732. file{
  733. path: "nested/again/back-link/../../../back-link-file",
  734. expected: filepath.Join(basedir, "back-link-file"),
  735. })
  736. // Test chaining back-tick symlinks.
  737. files = append(files,
  738. file{
  739. path: "nested/back-link-first",
  740. linkTarget: "../",
  741. expected: "",
  742. },
  743. file{
  744. path: "nested/back-link-first/back-link-second",
  745. linkTarget: "../",
  746. expected: "",
  747. })
  748. files = append(files,
  749. file{ // Relative directory path with terminating /
  750. path: "direct/dir/",
  751. expected: "",
  752. })
  753. buf := &bytes.Buffer{}
  754. tw := tar.NewWriter(buf)
  755. expectations := map[string]bool{}
  756. for _, f := range files {
  757. if f.expected != "" {
  758. expectations[f.expected] = false
  759. }
  760. if f.linkTarget == "" {
  761. hdr := &tar.Header{
  762. Name: f.path,
  763. Mode: 0666,
  764. Size: int64(len(f.path)),
  765. }
  766. require.NoError(t, tw.WriteHeader(hdr), f.path)
  767. if !strings.HasSuffix(f.path, "/") {
  768. _, err := tw.Write([]byte(f.path))
  769. require.NoError(t, err, f.path)
  770. }
  771. } else {
  772. hdr := &tar.Header{
  773. Name: f.path,
  774. Mode: int64(0777 | os.ModeSymlink),
  775. Typeflag: tar.TypeSymlink,
  776. Linkname: f.linkTarget,
  777. }
  778. require.NoError(t, tw.WriteHeader(hdr), f.path)
  779. }
  780. }
  781. tw.Close()
  782. // Capture warnings to stderr for debugging.
  783. output := (*testWriter)(t)
  784. opts := NewCopyOptions(genericclioptions.IOStreams{In: &bytes.Buffer{}, Out: output, ErrOut: output})
  785. require.NoError(t, opts.untarAll(fileSpec{}, buf, filepath.Join(basedir), ""))
  786. filepath.Walk(testdir, func(path string, info os.FileInfo, err error) error {
  787. if err != nil {
  788. return err
  789. }
  790. if info.IsDir() {
  791. return nil // Ignore directories.
  792. }
  793. if _, ok := expectations[path]; !ok {
  794. t.Errorf("Unexpected file at %s", path)
  795. } else {
  796. expectations[path] = true
  797. }
  798. return nil
  799. })
  800. for path, found := range expectations {
  801. if !found {
  802. t.Errorf("Missing expected file %s", path)
  803. }
  804. }
  805. }
  806. func TestUntar_SingleFile(t *testing.T) {
  807. testdir, err := ioutil.TempDir("", "test-untar")
  808. require.NoError(t, err)
  809. defer os.RemoveAll(testdir)
  810. dest := filepath.Join(testdir, "target")
  811. buf := &bytes.Buffer{}
  812. tw := tar.NewWriter(buf)
  813. const (
  814. srcName = "source"
  815. content = "file contents"
  816. )
  817. hdr := &tar.Header{
  818. Name: srcName,
  819. Mode: 0666,
  820. Size: int64(len(content)),
  821. }
  822. require.NoError(t, tw.WriteHeader(hdr))
  823. _, err = tw.Write([]byte(content))
  824. require.NoError(t, err)
  825. tw.Close()
  826. // Capture warnings to stderr for debugging.
  827. output := (*testWriter)(t)
  828. opts := NewCopyOptions(genericclioptions.IOStreams{In: &bytes.Buffer{}, Out: output, ErrOut: output})
  829. require.NoError(t, opts.untarAll(fileSpec{}, buf, filepath.Join(dest), srcName))
  830. cmpFileData(t, dest, content)
  831. }
  832. func createTmpFile(t *testing.T, filepath, data string) {
  833. f, err := os.Create(filepath)
  834. if err != nil {
  835. t.Fatalf("unexpected error: %v", err)
  836. }
  837. defer f.Close()
  838. if _, err := io.Copy(f, bytes.NewBuffer([]byte(data))); err != nil {
  839. t.Fatalf("unexpected error: %v", err)
  840. }
  841. if err := f.Close(); err != nil {
  842. t.Fatal(err)
  843. }
  844. }
  845. func cmpFileData(t *testing.T, filePath, data string) {
  846. actual, err := ioutil.ReadFile(filePath)
  847. require.NoError(t, err)
  848. assert.EqualValues(t, data, actual)
  849. }
  850. type testWriter testing.T
  851. func (t *testWriter) Write(p []byte) (n int, err error) {
  852. t.Logf(string(p))
  853. return len(p), nil
  854. }