Skip to content

✨Allow directories to be mounted as secrets #4896

Description

@vikram-dagger

What are you trying to do?

I'm trying to create and GPG-sign a built binary with Dagger.

To do this, I need to mount my ~/.gnupg directory into my container and run gpg --detach-sign --armor binary-name.

The above command requires the following files (keyrings and trustdb) to create the signature:

  • ~/.gnupg/pubring.kbx
  • ~/.gnupg/trustdb.gpg
  • ~/.gnupg/private-keys-v1.d/*

Currently Dagger only permits mounting files as secrets. It's not possible to mount an entire directory hierarchy as a secret; each file has to be mounted manually.

Can Dagger allow directories to be mounted as secrets, as it does with files?

Why is this important to you?

It will make it simpler to sign binary builds with GPG.

How are you currently working around this?

No response

Activity

  1. dolanor commented on Apr 6, 2023

    @dolanor
    Contributor

    It is not possible on buildkit for now but other use case than GPG exist.
    The best would be to fix upstream, but it might be faster to do it on our side first if we want it soon.

  2. TomChv commented on Apr 6, 2023

    @TomChv
    Member

    @dolanor Can't we just walk through the given directories and transform these files into secrets?

  3. dolanor commented on Apr 7, 2023

    @dolanor
    Contributor

    Yes, that is the initial idea. My fear is that creating the folder structure on the container might leave trace in the cache/image. (the file would be considered secrets, ok, but the folder would have to be created in the container first and wouldn't be considered secrets, so they would linger).
    Also, I don't have any idea how to pass the rights as well.
    I think it's more complex than it looks.

  4. grouville commented on Apr 17, 2023

    @grouville
    Member

    Currently stuck by #4739. Could be actionable when related PR gets merged #4932

  5. self-assigned this
    on Apr 25, 2023
  6. grouville commented on May 2, 2023

    @grouville
    Member

    Stuck by #5069, which would need to be implemented first, if we agree on having a client-side implementation.

    Client-side implementation of above example, using with()

    Go SDK

    package main
    
    import (
    	"context"
    	"fmt"
    	"os"
    	"path/filepath"
    	"io/ioutil"
    	"dagger.io/dagger"
    )
    
    func main() {
    	// initialize Dagger client
    	ctx := context.Background()
    	client, err := dagger.Connect(ctx, dagger.WithLogOutput(os.Stderr))
    	if err != nil {
    		panic(err)
    	}
    	defer client.Close()
    
    	// GPG files needed for signing
    	gpgFiles := []string{
    		"/home/USER/.gnupg/pubring.kbx",
    		"/home/USER/.gnupg/trustdb.gpg",
    	}
    
    	// Container setup
    	container := client.Container().From("alpine:3.17")
    
    	// Mount GPG files
    	for _, filePath := range gpgFiles {
    		content, err := ioutil.ReadFile(filePath)
    		if err != nil {
    			panic(err)
    		}
    		secret := client.SetSecret(filepath.Base(filePath), string(content))
    		container = container.WithMountedSecret("/root/.gnupg/"+filepath.Base(filePath), secret)
    	}
    
    	// Mount private keys directory
    	sourceDir := "/home/USER/.gnupg/private-keys-v1.d/"
    	targetDir := "/root/.gnupg/private-keys-v1.d/"
    	container = container.With(mountDirectoryAsSecret(client, sourceDir, targetDir))
    
    	// Sign the binary
    	binaryName := "binary-name"
    	out, err := container.
    		WithExec([]string{"apk", "add", "--no-cache", "gnupg"}).
    		WithWorkdir("/root").
    		WithExec([]string{"gpg", "--detach-sign", "--armor", binaryName}).
    		Stdout(ctx)
    
    	if err != nil {
    		panic(err)
    	}
    
    	fmt.Println(out)
    }
    
    func mountDirectoryAsSecret(client *dagger.Client, sourceDir, targetDir string) func(*dagger.Container) *dagger.Container {
    	return func(c *dagger.Container) *dagger.Container {
    		err := filepath.Walk(sourceDir, func(path string, info os.FileInfo, err error) error {
    			if err != nil {
    				return err
    			}
    
    			if !info.IsDir() {
    				relativePath, _ := filepath.Rel(sourceDir, path)
    				targetPath := filepath.Join(targetDir, relativePath)
    
    				// Read file
    				content, err := ioutil.ReadFile(path)
    				if err != nil {
    					return err
    				}
    
    				// Set secret to file content
    				secret := client.SetSecret(filepath.Base(path), string(content))
    
    				// Mount secret as file in container
    				c = c.WithMountedSecret(targetPath, secret)
    			}
    
    			return nil
    		})
    
    		if err != nil {
    			panic(err)
    		}
    
    		return c
    	}
    }

    Node SDK

    import Client, { connect } from "@dagger.io/dagger"
    import * as fs from "fs";
    import * as path from "path";
    
    // I failed to:
    // import { Container } from "@dagger.io/dagger/dist/api/client.gen"
    // Workaround:
    type Container = ReturnType<Client["container"]>;
    
    connect(async (client: Client) => {
      const gpgFiles = [
        "/home/USER/.gnupg/pubring.kbx",
        "/home/USER/.gnupg/trustdb.gpg",
      ];
    
      const sourceDir = "/home/USER/.gnupg/private-keys-v1.d/";
      const targetDir = "/root/.gnupg/private-keys-v1.d/";
    
      let container = client.container().from("alpine:3.17");
    
      // Mount GPG files
      for (const filePath of gpgFiles) {
        const content = await fs.promises.readFile(filePath, "utf-8");
        const secret = client.setSecret(filePath.split("/").pop()!, content);
    
        container = container.withMountedSecret(`/root/.gnupg/${filePath.split("/").pop()}`, secret);
      }
    
      // Mount private keys directory
      container = container.with(await mountDirectoryAsSecret(client, sourceDir, targetDir));
    
      // Sign the binary
      const binaryName = "binary-name";
      container = container
        .withExec(["apk", "add", "--no-cache", "gnupg"])
        .withWorkdir("/root")
        .withExec(["gpg", "--detach-sign", "--armor", binaryName]);
    
      console.log(await container.stdout());
    });
    
    async function mountDirectoryAsSecret(client: Client, sourceDir: string, targetDir: string): Promise<(c: Container) => Container> {
      async function processDirectory(dir: string): Promise<(c: Container) => Container> {
        const entries = await fs.promises.readdir(dir);
        const containerUpdates: Array<(c: Container) => Container> = [];
    
        for (const entry of entries) {
          const fullPath = path.join(dir, entry);
          const entryStat = await fs.promises.stat(fullPath);
    
          if (entryStat.isFile()) {
            const content = await fs.promises.readFile(fullPath, "utf-8");
            const secret = client.setSecret(path.basename(fullPath), content);
            const targetPath = path.join(targetDir, path.relative(sourceDir, fullPath));
            containerUpdates.push((c) => c.withMountedSecret(targetPath, secret));
          } else if (entryStat.isDirectory()) {
            containerUpdates.push(await processDirectory(fullPath));
          }
        }
    
        return (c) => containerUpdates.reduce((acc, update) => update(acc), c);
      }
    
      return processDirectory(sourceDir);
    }
  7. grouville commented on Jul 28, 2023

    @grouville
    Member

    Reopening, following the revert

  8. added
    area/documentation
    on Aug 1, 2023
  9. helderco commented on Aug 1, 2023

    @helderco
    Contributor

    Added the documentation label because while there's a native way to mount secret files, mounting secret directories is just an abstraction on top of that. The #5520 cookbook demonstrates an example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area/documentation

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions