Verified Commit 8cca17db authored by Tomasz Maczukin's avatar Tomasz Maczukin
Browse files

Make saving more elastic

This change makes saving more elastic by:
- using `filapth.Join()` which should be more OS independent
- saving the data in a path relative to working directory, which is
  more "natural" for the user and also OS independent.
parent f23f4056
.tests/
.tmp/
build/
data/
\ No newline at end of file
......@@ -7,14 +7,20 @@ import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
"gitlab.com/gitlab-org/gitlab-runner/helpers/tls/ca_chain"
)
var outDir = "/tmp/tlsctl"
var (
baseDir = filepath.Join(".", "data")
outDir string
)
func makeSaveCMD() cli.Command {
return cli.Command{
......@@ -33,6 +39,11 @@ func saveAction(c *cli.Context) error {
return errors.New("--url not defined")
}
err := prepareOutputDirectory(URL)
if err != nil {
return fmt.Errorf("preparing output directory: %w", err)
}
response, err := http.Head(URL)
if err != nil {
return fmt.Errorf("sending request for TLS: %w", err)
......@@ -71,18 +82,41 @@ func saveAction(c *cli.Context) error {
return nil
}
func savePemBlock(block *pem.Block) error {
err := mkdirIfNotExists(outDir)
func prepareOutputDirectory(URL string) error {
u, err := url.Parse(URL)
if err != nil {
return fmt.Errorf("parsing URL %q: %w", URL, err)
}
outDir = filepath.Join(baseDir, u.Hostname())
err = mkdirIfNotExists(outDir)
if err != nil {
return fmt.Errorf("creating directory: %w", err)
return fmt.Errorf("creating output directory %q: %w", outDir, err)
}
return nil
}
func mkdirIfNotExists(path string) error {
_, err := os.Stat(path)
if os.IsNotExist(err) {
err := os.MkdirAll(path, 0700)
if err != nil {
return err
}
}
return nil
}
func savePemBlock(block *pem.Block) error {
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return fmt.Errorf("parsing certificate: %w", err)
}
filePath := fmt.Sprintf("%s/%s", outDir, cert.SerialNumber)
filePath := filepath.Join(outDir, cert.SerialNumber.String())
f, err := os.Create(filePath)
if err != nil {
......@@ -104,25 +138,9 @@ func savePemBlock(block *pem.Block) error {
}
func saveCAChain(chain []byte) error {
err := mkdirIfNotExists(outDir)
if err != nil {
return err
}
path := fmt.Sprintf("%s/CAChain.crt", outDir)
path := filepath.Join(outDir, "CAChain.crt")
logrus.WithField("path", path).Info("Save CAChain")
return ioutil.WriteFile("/tmp/tlsctl/CAChain.crt", chain, 0600)
}
func mkdirIfNotExists(path string) error {
if _, err := os.Stat(path); os.IsNotExist(err) {
err := os.MkdirAll(path, 0700)
if err != nil {
return fmt.Errorf("creating directory %q: %w", path, err)
}
}
return nil
return ioutil.WriteFile(path, chain, 0600)
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment