Skip to content

Handling Binary Data #5069

Closed
Closed

Description

@grouville

Background

While trying to implement examples for issue Allow directories to be mounted as secrets, it became apparent that there are limitations when dealing with binary data in GraphQL using strings. This is relevant for the purpose of mounting directories as secrets, where binary data needs to be handled.

I encountered a problem when attempting to handle GPG files. The goal was to create and GPG-sign a built binary with Dagger by mounting the ~/.gnupg directory into the container and running gpg --detach-sign --armor binary-name.

This required the following files:

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

Handling binary data like GPG files in GraphQL led to errors due to improper escaping:

go run .                
Connected to engine c01f0fd17590
panic: input:1: Syntax Error GraphQL request (1:49) Invalid character escape sequence: \\x.

The initial idea was to implement a union type SecretData = String | Bytes in the setSecret query. However, according to the discussion, using unions as input values in GraphQL is not feasible.

Issue

The main issue is finding a solution to handle both string and binary data when setting secrets in GraphQL, as the initial proposal of using a union type is not possible. This is important for mounting directories as secrets and handling binary data efficiently.

Proposed Solution

Based on the comments and limitations mentioned in the discussion, the best solution seems to be to create a new function that accepts binary data as Base64 encoded string as input. This function would be a variation of withSecretVariable and handle binary data separately.

Advantages

  • No character encoding issues: By using Base64 encoding, we can ensure that all binary data is properly serialized and deserialized without any issues related to character encoding.
  • Efficient data transfer: Base64-encoded binary data is more compact than a string representation, reducing the overhead associated with transferring binary data in GraphQL queries or mutations.
  • Clear type information: Defining a custom type allows us to be explicit regarding the expected encoded format

Steps to implement the solution:

  1. Create a new custom type Base64 in the GraphQL schema to handle binary data.
type Base64 string
  1. Define a new function in the client SDK called WithSecretBytes that accepts an environment variable name and Base64 data as input.
func (c *Container) setSecretBytes(name string, data Base64) *Container
  1. Update the GraphQL schema to include the new function setSecretBytes.
extend type Query {
  "Sets a secret given a user-defined name to its binary data and returns the secret."
  setSecretBytes(
    """
    The user-defined name for this secret
    """
    name: String!

    """
    The binary data of the secret
    """
    data: Base64!
  ): Secret!
}
  1. Implement deserialization functions for the Base64 setSecretBytes, handling the decoding of binary from Base64.
  2. Update the SDK example to show how to convert binary data to Base64-encoded strings before sending them as secret arguments.

By implementing this new function, we can effectively handle binary data in GraphQL, making it possible to mount directories as secrets in a more convenient and efficient manner.

cc @vikram-dagger @helderco @vito

Activity

  1. helderco commented on May 2, 2023

    @helderco
    Contributor

    Have you considered doing something like Host.Directory()? So instead of data: Base64!, you'd use path: String!.

  2. grouville commented on May 2, 2023

    @grouville
    MemberAuthor

    We can also introduce a new parameter to the setSecret query that specifies the encoding format. This would allow us to handle different encoding formats more explicitly:

    enum EncodingFormat {
      STRING
      BASE64
    }
    
    extend type Query {
      """
      Sets a secret given a user-defined name to its data (either binary data or plaintext) and returns the secret.
      """
      setSecret(
        """
        The user-defined name for this secret
        """
        name: String!
    
        """
        The data of the secret (either binary data or plaintext)
        """
        data: String!
    
        """
        The encoding format of the secret data (defaults to STRING)
        """
        encoding: EncodingFormat = STRING
      ): Secret!
    }

    (defaults do not seem to work though)

  3. vito commented on May 2, 2023

    @vito
    Contributor
    panic: input:1: Syntax Error GraphQL request (1:49) Invalid character escape sequence: \\x.

    I think this is just because we took a shortcut in our query builder by assuming GraphQL strings follow the same rules as Go: #5008 (comment)

    We should probably update the query builders to follow the GraphQL spec instead. I think with that change we shouldn't need to support alternative encodings, but I'm still in support of the approach in #5069 (comment) if we want to go that route.

    Worth noting GraphQL string escaping is something that would have to be implemented properly for every SDK. I'm not sure if this issue applies to the other SDKs.

  4. grouville commented on May 2, 2023

    @grouville
    MemberAuthor

    We should probably update the query builders to follow the GraphQL spec instead.

    Totally agree, thanks for the insight 🙏

    Worth noting GraphQL string escaping is something that would have to be implemented properly for every SDK. I'm not sure if this issue applies to the other SDKs.

    Tested on Node SDK, it seems to work for one of the file on which the Go SDK breaks. I still have an issue on another file (bigger binary data), don't know if it is related or not. But I presume that the implementation is somewhat similar: invalid secret size 514282. The escaping might be the root cause here too:

    node --loader ts-node/esm test.mts
    (node:25831) ExperimentalWarning: Custom ESM Loaders is an experimental feature. This feature could change at any time
    (Use `node --trace-warnings ...` to show where the warning was created)
    file:///private/tmp/repro_mount_dir/node_modules/@dagger.io/dagger/dist/api/utils.js:5
            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
                                                                    ^
    GraphQLRequestError: Error message
        at file:///private/tmp/repro_mount_dir/node_modules/@dagger.io/dagger/dist/api/utils.js:144:23
        at Generator.throw (<anonymous>)
        at rejected (file:///private/tmp/repro_mount_dir/node_modules/@dagger.io/dagger/dist/api/utils.js:5:65)
        at processTicksAndRejections (node:internal/process/task_queues:95:5) {
      cause: ClientError: invalid secret size 514282: {"response":{"data":null,"errors":[{"message":"invalid secret size 514282","locations":[{"line":2,"column":208}],"path":["container","from","withMountedSecret","withExec","stdout"]}],"status":200,"headers":{}},"request":{"query":"\n        { container  { from (address: \"alpine:3.17\") { withMountedSecret (path: \"/root/.gnupg/pubring.kbx\",source: \"foo\") { withExec (args: [\"apk\",\"add\",\"--no-cache\",\"gnupg\"]) { stdout  }}}} }\n      "}}
          at makeRequest (file:///private/tmp/repro_mount_dir/node_modules/graphql-request/src/index.ts:441:11)
          at processTicksAndRejections (node:internal/process/task_queues:95:5) {
        response: { data: null, errors: [Array], status: 200, headers: [Headers] },
        request: {
          query: '\n' +
            '        { container  { from (address: "alpine:3.17") { withMountedSecret (path: "/root/.gnupg/pubring.kbx",source: "foo") { withExec (args: ["apk","add","--no-cache","gnupg"]) { stdout  }}}} }\n' +
            '      ',
          variables: undefined
        }
      },
      code: 'D100',
      requestContext: {
        query: '\n' +
          '        { container  { from (address: "alpine:3.17") { withMountedSecret (path: "/root/.gnupg/pubring.kbx",source: "foo") { withExec (args: ["apk","add","--no-cache","gnupg"]) { stdout  }}}} }\n' +
          '      ',
        variables: undefined
      },
      response: {
        data: null,
        errors: [ [Object] ],
        status: 200,
        headers: Headers { [Symbol(map)]: [Object: null prototype] }
      }
    }
  5. grouville commented on May 4, 2023

    @grouville
    MemberAuthor

    I have explored our graphQL implementation. Currently only have a partial implementation of the spec, still some issues on non-printable unicode chars. All the experiments are available here.

    In theory, what Alex proposes is possible, still haven't found the implementation yet.

    Next step:

    => https://pkg.go.dev/github.com/wundergraph/[email protected]/pkg/astprinter
    Alex: curious what this does if you build up a *ast.Document containing a binary string and then print the generated query
    we depend on a fork of this package already
    

    Gist/experiment with links

  6. self-assigned this
    on May 4, 2023
  7. grouville commented on May 22, 2023

    @grouville
    MemberAuthor

    Here is a quick overview of where the issue lies, what the arbitrages are and potential next steps to its resolution.

    Global problem

    When trying to mount binary files into Dagger, we encounter encoding issues on invalid UTF-8 sequences.
    Repro: https://gist.github.com/grouville/df32b261dcf8bf1a9c7d140f5c18a09b
    This gives us the issue:

    Please visit https://dagger.io/help#go for troubleshooting guidance.|
    panic: input:1: Syntax Error GraphQL request (1:49) Invalid character escape sequence: \\x.

    1. Isolating the root issue

    It turns out that the issue lies in the dagger/graphql lib that we forked. My first attempt was to follow Alex’s advice to try understanding how / if we could manage this issue at the level of the library.

    1. The issue arises at the library level

    This is the repro showing that the library doesn’t handle properly the unicodes. Here, I create a new scalar, with a corresponding query handle, but we don’t even get at the resolve level. We get the same error as the one we get from the Dagger Go SDK:

    go run ./main_broken.go
    2023/05/19 00:34:30 failed to execute graphql operation, errors: [Syntax Error GraphQL request (3:17) Invalid character "\\u0001"
    
    exit status 1

    2. Implementing the GraphQL spec

    As @vito suggested, we explored if there was a way to implement the graphQL’s spec on unicode management. It could theoretically work, but I haven’t found a sustainable way to retrieve the exact data I sent that way:

    1. gqlgen strings marshalling

    gqlgen implemented a marshalling / unmarshalling of strings compliant with the graphQL specs.

    2. Testing gqlgen strings marshalling as a solution

    The idea here is to marshal the binary data and see if we have the exact same bytes data at the server level, and as a response. The test string can be one of the following breaking test:

    // ASCII control characters
    {"\b"},
    {"\f"},
    {"\n"},
    {"\r"},
    {"\t"},
    
    // Escaped character
    {"\""},
    {"\\"},
    {"/"},
    
    // Unicode characters
    {"\U0001F4A9"}, // Emoji
    {"\u2764"},     // Heart
    
    // Mixed input
    {"Hello, \nWorld!\r\nYours,\t\"GraphQL\""},
    {" # This comment has a \u0A0A multi-byte character."},
    {"\"unicode \\u1234\\u5678\\u90AB\\uCDEF\""},
    {"こんにちは, 世界!\n \U0001F4A9"},
    {"\"Has a фы世界 multi-byte character.\""},

    Let’s take: "\u2764" as an example.

    The two repros show that:

    First run, with no_escape.go:
    $ go run ./no_escape.go
    2023/05/22 16:03:21 failed to execute graphql operation, errors: [Syntax Error GraphQL request (3:17) Unexpected character "\\u2764".
    
    2: \u0009{
    3: \u0009\u0009echo(message: ❤)
                       ^
    4: \u0009}
    ]
    exit status 1
    Second run, with string_escape.go:
    $ go run ./string_escape.go
    ParseLiteral: |"❤"|
    ParseLiteral: |"❤"|
    Incoming data matches original data
    OUTPUT data matches original data
    1. the gqlgen strings escape works: it escapes all unicodes properly:
    2. We are able to retrieve from the server the original data

    3. JSON Unmarshalling is not unicode safe, in Go

    However, JSON unmarshalling of some unicode bytes break in Go, and we do rely on that to unmarshall the server response.

    Let's take the almost the same code as above (with gqlgen strings escape), and let's try to load my binary gpg key and see if my output data is equivalent to my input data: code here.

    go run ./main.go
    Incoming data matches original data
    OUTPUT data does not match original data!

    What is interesting here is that the 'incoming data', in the server is equivalent to the original data. However, when retrieving it on the response, the response data doesn't match the original data.

    What is happening ?

    It turns out that this all comes from the:

    // echoStr is a JSON string, so it needs to be unmarshaled
    // this breaks the response unicode data
    var unescapedEchoStr string
    if err := json.Unmarshal([]byte(echoStr), &unescapedEchoStr); err != nil { 
    	log.Fatalf("failed to unmarshal string: %v", err)
    }

    Here are the repros: https://gist.github.com/grouville/8d8ac47ba16e7980e9edca797492eeaf

    • The example with the stdlib stdlib_json.go, breaks on my gpg key file:
    go run ./stdlib_json.go
    The original string and the string obtained from the string areNOT equal
    The original bytes and the bytes obtained from the string are not equal
    • Serializing unicodes with json unmarshal:

    The idea was to rely on https://github.com/nspcc-dev/go-ordered-json. This library is being used in several blockchains for two purposes: json unmarshal ordering and serialization of unicode bytes. It should manage this issue.

    However, it doesn't work on my example: my local test doesn't pass either. Check forked_json.go for the repro:

    go run ./forked_json.go
    The original string and the string obtained from the string areNOT equal
    The original bytes and the bytes obtained from the string are not equal

    Now, we are sure that the gqlgen strings escape works, however, there is an issue with the JSON unmarshalling. We do rely on that in our codebase (at least in Go SDK) to process the server's response: https://github.com/dagger/dagger/blob/main/sdk/go/internal/querybuilder/querybuilder.go#L121C10-L148.

    3. A Base64 Bytes scalar

    Now, using base64, JSON unmarshal seems to not only work perfectly, but seems to be easily handling base64 encoded strings. In the base64.go example, I don't decode the base64 string:

    go run ./base64.go 
    The original string and the string obtained from JSON unmarshalling are equal

    With the complete scalar example, relying on a base64 encoding also works perfectly: https://gist.github.com/grouville/ae31ef61a192d9afc55334f220d2db3f.

    We could even go further to automatically decode the base64 response with a custom json umarshaller:

    type Base64Bytes []byte
    
    func (b *Base64Bytes) UnmarshalJSON(data []byte) error {
    	var s string
    	if err := json.Unmarshal(data, &s); err != nil {
    		return err
    	}
    	decoded, err := base64.StdEncoding.DecodeString(s)
    	if err != nil {
    		return err
    	}
    	*b = decoded
    	return nil
    }

    2. Proposal

    Given all this context, and taking into account the fact that I did not miss anything, I see 2 possible implementations, to be defined with you @helderco.

    In this issue, and according to the tests, it can be split in 2 sub-issues:

    1. Properly encoding strings: https://github.com/matiasinsaurralde/dagger/blob/9c7a60429fe2b7f1167b0a0d1ebed52d3123071d/sdk/go/internal/querybuilder/marshal.go#L68

    Basically, this probably only implies to transform the strconv.Quote to the gqlgen strings escape (for the Go SDK only), and do the same for other SDKs. It will make us handle unicodes for 99% of use-cases on our SDKs, and is automatically escaped server-side.

    1. Add a custom bytes scalar, for all the APIs that could contain random binary data. (mostly mount of files)
      I see 2 options, with big implications:
    • A custom Bytes scalar, relying on a base64 encoding to []byte{} server-side
    • Keep the strings scalar, but base64 encode on the SDK side as String. The API would have a encoding field.

    For both cases, this seems to be a breaking change in the API, but following all exploration above, I don't think a retro-compatible solution is doable ... I would love so, but don't think going 100% strings is what we want here 👼

    What do you think @helderco ? What would be the best way to handle both scalar types on the API ?

    cc @matiasinsaurralde @vito @aluzzardi @helderco

  8. changed the title [-]Handling Binary Data as Secrets[/-] [+]Handling Binary Data[/+] on May 22, 2023
  9. helderco commented on May 22, 2023

    @helderco
    Contributor

    @grouville Can you test a repro for the other SDKs failing to properly encode the strings? Python uses a third party library for the query builder while node.js has a custom implementation. Maybe they don't have an issue here?

  10. grouville commented on May 30, 2023

    @grouville
    MemberAuthor

    @grouville Can you test a repro for the other SDKs failing to properly encode the strings? Python uses a third party library for the query builder while node.js has a custom implementation. Maybe they don't have an issue here?

    You're right, other SDKs do not have this issue for UTF-8 unicodes, but the issue remains for binary files with weird sequences, as explained above. Repros are present on PR: #5169


    @sipsma, after talking with @helderco, it seems that we used to have a way to mount secret files inside containers, with a Dagger equivalent to "fsync". If possible, this would enable us to create a new API endpoint to mount a secret file from a path, instead of reading its content as text. Do you believe this is possible ?

    Otherwise, the base64 approach will have to be followed

  11. helderco commented on May 30, 2023

    @helderco
    Contributor

    @grouville To be clear, when I mentioned fsync I believe it's a fork we use to sync files between the client and the engine (don't know internals, just remember bits of discussions).

    That's different from the deprecated secret file implementation which is just using File.secret(), thus getting leaked in the cache via any of the ways you can get a File. When coming from Host.directory, that's using llb.Local.

    What I suggested was that maybe via the lower level fsync, we can send a file from the client to the engine in a way that remains secret to buildkit, so we can add it to the in-memory store.

  12. helderco commented on May 30, 2023

    @helderco
    Contributor

    By the way I don’t think you need to reach for the lower level fsync directly. If your argument is a path to a file, then in the API you just open it in Go, add it to the in-memory secret store and return a SecretID, like a mix of Host.directory and Query.setSecret:

    Host {
      setSecretFile(name: !String, path: !String)
    }
  13. helderco commented on May 30, 2023

    @helderco
    Contributor

    @grouville Fyi, I just tested the above and it works. Basically creating a new api field that receives a path, and reading the content with Go, without going to buildkit. From there, it's just adding to the secret store.

  14. helderco commented on May 30, 2023

    @helderco
    Contributor

    Re: binary files... I suggest changing the store's data type in core/store.go:

    type Store struct {
    -  secrets map[string]string
    +  secrets map[string][]byte
    }

    So that GetSecret returns the original []byte untouched.

    Also adapt AddSecret to receive []byte and do the string conversion where it's actually needed like Query.setSecret() and Secret.plaintext().

  15. 2 remaining items

  16. gerhard commented on Jul 18, 2023

    @gerhard
    Contributor
  17. grouville commented on Jul 18, 2023

    @grouville
    MemberAuthor

    We (+@helderco) would like to get this done for:

    WDYT @grouville?

    Totally agree. Prioritizing it 🙏

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions