| Giorgi Lekveishvili | 12850ee | 2023-06-22 13:11:17 +0400 | [diff] [blame^] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "golang.org/x/crypto/ssh" |
| 6 | "net" |
| 7 | "os" |
| 8 | |
| 9 | "github.com/go-git/go-billy/v5/memfs" |
| 10 | "github.com/go-git/go-git/v5" |
| 11 | gitssh "github.com/go-git/go-git/v5/plumbing/transport/ssh" |
| 12 | "github.com/go-git/go-git/v5/storage/memory" |
| 13 | "github.com/spf13/cobra" |
| 14 | |
| 15 | "github.com/giolekva/pcloud/core/installer" |
| 16 | "github.com/giolekva/pcloud/core/installer/welcome" |
| 17 | ) |
| 18 | |
| 19 | var welcomeFlags struct { |
| 20 | repo string |
| 21 | sshKey string |
| 22 | port int |
| 23 | } |
| 24 | |
| 25 | func welcomeCmd() *cobra.Command { |
| 26 | cmd := &cobra.Command{ |
| 27 | Use: "welcome", |
| 28 | RunE: welcomeCmdRun, |
| 29 | } |
| 30 | cmd.Flags().StringVar( |
| 31 | &welcomeFlags.repo, |
| 32 | "repo-addr", |
| 33 | "", |
| 34 | "", |
| 35 | ) |
| 36 | cmd.Flags().StringVar( |
| 37 | &welcomeFlags.sshKey, |
| 38 | "ssh-key", |
| 39 | "", |
| 40 | "", |
| 41 | ) |
| 42 | cmd.Flags().IntVar( |
| 43 | &welcomeFlags.port, |
| 44 | "port", |
| 45 | 8080, |
| 46 | "", |
| 47 | ) |
| 48 | return cmd |
| 49 | } |
| 50 | |
| 51 | func welcomeCmdRun(cmd *cobra.Command, args []string) error { |
| 52 | sshKey, err := os.ReadFile(welcomeFlags.sshKey) |
| 53 | if err != nil { |
| 54 | return err |
| 55 | } |
| 56 | auth := authSSH(sshKey) |
| 57 | repo, err := git.Clone(memory.NewStorage(), memfs.New(), &git.CloneOptions{ |
| 58 | URL: welcomeFlags.repo, |
| 59 | Auth: auth, |
| 60 | RemoteName: "origin", |
| 61 | ReferenceName: "refs/heads/master", |
| 62 | Depth: 1, |
| 63 | InsecureSkipTLS: true, |
| 64 | Progress: os.Stdout, |
| 65 | }) |
| 66 | s := welcome.NewServer( |
| 67 | welcomeFlags.port, |
| 68 | installer.NewRepoIO(repo, auth.Signer), |
| 69 | ) |
| 70 | s.Start() |
| 71 | return nil |
| 72 | } |
| 73 | |
| 74 | func authSSH(pemBytes []byte) *gitssh.PublicKeys { |
| 75 | a, err := gitssh.NewPublicKeys("git", pemBytes, "") |
| 76 | if err != nil { |
| 77 | panic(err) |
| 78 | } |
| 79 | a.HostKeyCallback = func(hostname string, remote net.Addr, key ssh.PublicKey) error { |
| 80 | // TODO(giolekva): verify server public key |
| 81 | fmt.Printf("--- %+v\n", ssh.MarshalAuthorizedKey(key)) |
| 82 | return nil |
| 83 | } |
| 84 | return a |
| 85 | } |