...

Source file src/edge-infra.dev/pkg/sds/emergencyaccess/retriever/retriever.go

Documentation: edge-infra.dev/pkg/sds/emergencyaccess/retriever

     1  package retriever
     2  
     3  import (
     4  	"context"
     5  	"database/sql"
     6  	"fmt"
     7  	"slices"
     8  
     9  	"edge-infra.dev/pkg/lib/fog"
    10  	"edge-infra.dev/pkg/sds/emergencyaccess/apierror"
    11  )
    12  
    13  // Client is capable of retrieving operator intervention artifacts. A single
    14  // instance of Client is expected to be used for the duration of the program if
    15  // multiple artifacts are to be retrieved.
    16  type Client struct {
    17  	db *sql.DB
    18  }
    19  
    20  // New creates a new instance of Client.
    21  func New(db *sql.DB) (*Client, error) {
    22  	return &Client{db: db}, nil
    23  }
    24  
    25  // Artifact returns an artifact given a name and type
    26  func (c *Client) Artifact(ctx context.Context, name string, artifactType ArtifactType) (Artifact, error) {
    27  	artifact := Artifact{
    28  		Name: name,
    29  		Type: artifactType,
    30  	}
    31  
    32  	err := verifyArtifactType(artifactType)
    33  	if err != nil {
    34  		return artifact, err
    35  	}
    36  
    37  	row := c.db.QueryRowContext(ctx, sqlStmt, name, artifactType)
    38  	err = row.Scan(&artifact.Artifact, &artifact.SHA)
    39  	switch {
    40  	case err == sql.ErrNoRows:
    41  		return artifact, apierror.E(
    42  			apierror.ErrUnknownCommand,
    43  			fmt.Errorf("unknown artifact: (name: %q), (type: %q)", name, string(artifactType)),
    44  			fmt.Sprintf("Command %q of type %q is unknown", name, userType(artifactType)),
    45  		)
    46  	case err != nil:
    47  		return artifact, fmt.Errorf("error scanning row: %w", err)
    48  	}
    49  
    50  	fog.FromContext(ctx).Info(
    51  		"Retrieved artifact from the db",
    52  		"artifactName", artifact.Name,
    53  		"artifactType", artifact.Type,
    54  		"artifactSHA", fmt.Sprintf("%x", artifact.SHA),
    55  	)
    56  
    57  	return artifact, nil
    58  }
    59  
    60  // Returns an error if the supplied artifactType is not known to this package
    61  func verifyArtifactType(artifactType ArtifactType) error {
    62  	if !slices.Contains(allArtifactTypes, artifactType) {
    63  		return fmt.Errorf("unknown artifact type: %q", artifactType)
    64  	}
    65  	return nil
    66  }
    67  
    68  // userType returns the user facing name for the given artifactType
    69  func userType(artifactType ArtifactType) string {
    70  	name := ""
    71  	if artifactType == Executable {
    72  		name = "script"
    73  	}
    74  	return name
    75  }
    76  

View as plain text