Something went wrong. Try again.
A Tangled spindle that runs CI on other providers, including ephemeral DigitalOcean droplets.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291package main
// Repository secrets, managed from Tangled's repository settings through// sh.tangled.repo.addSecret, removeSecret and listSecrets, and handed to// providers that know how to deliver them to a run.//// Values are encrypted at rest with AES-256-GCM under TACK_SECRETS_KEY, so the// database, and the backups of it, never hold a secret in the clear. Each// value's repository and key are bound in as additional data, so a ciphertext// copied onto another row does not decrypt.//// Secrets follow the stock spindle's rule for who receives them: never a run// whose code comes from a different repository than the one the secrets// belong to, which is what a pull request from a fork is.
import ( "context" "crypto/aes" "crypto/cipher" "crypto/rand" "database/sql" "encoding/base64" "errors" "fmt" "regexp" "sort" "strings" "time"
"tangled.org/core/api/tangled")
// secretKeyPattern is the stock spindle's rule: a key is an environment// variable name.var secretKeyPattern = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
// maxSecretValueBytes bounds one secret value. It arrives from the appview// in a JSON body and ends up in a process environment, so anything larger is// a mistake rather than a secret.const maxSecretValueBytes = 64 << 10
// ErrSecretsDisabled means no TACK_SECRETS_KEY is configured.var ErrSecretsDisabled = errors.New("secrets are not enabled on this spindle (TACK_SECRETS_KEY is unset)")
// secretMeta is a secret without its value, as listSecrets reports it.type secretMeta struct { Key string CreatedAt time.Time CreatedBy string}
// secretVault stores repository secrets encrypted. A nil vault means secrets// are disabled; its methods say so rather than panicking.type secretVault struct { st *store aead cipher.AEAD}
// newSecretVault returns a vault keyed by encodedKey, 32 bytes in standard// base64 (e.g. from `openssl rand -base64 32`), or nil if encodedKey is empty.func newSecretVault(st *store, encodedKey string) (*secretVault, error) { if encodedKey == "" { return nil, nil } key, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encodedKey)) if err != nil || len(key) != 32 { return nil, errors.New("TACK_SECRETS_KEY must be 32 bytes, base64 encoded") } block, err := aes.NewCipher(key) if err != nil { return nil, err } aead, err := cipher.NewGCM(block) if err != nil { return nil, err } return &secretVault{st: st, aead: aead}, nil}
func secretAAD(repoDID, key string) []byte { return []byte(repoDID + "\x00" + key)}
// Put stores or replaces a secret.func (v *secretVault) Put(ctx context.Context, repoDID, key, value, createdBy string) error { if v == nil { return ErrSecretsDisabled } if !secretKeyPattern.MatchString(key) { return fmt.Errorf("secret key %q must be a letter or underscore followed by letters, digits and underscores", key) } if value == "" { return errors.New("secret value is empty") } if len(value) > maxSecretValueBytes { return fmt.Errorf("secret value is larger than %d bytes", maxSecretValueBytes) } nonce := make([]byte, v.aead.NonceSize()) if _, err := rand.Read(nonce); err != nil { return err } sealed := v.aead.Seal(nil, nonce, []byte(value), secretAAD(repoDID, key)) return v.st.PutRepoSecret(ctx, repoDID, key, nonce, sealed, createdBy, time.Now())}
// Delete removes a secret. Removing one that does not exist is not an error.func (v *secretVault) Delete(ctx context.Context, repoDID, key string) error { if v == nil { return ErrSecretsDisabled } return v.st.DeleteRepoSecret(ctx, repoDID, key)}
// List returns a repository's secrets without their values.func (v *secretVault) List(ctx context.Context, repoDID string) ([]secretMeta, error) { if v == nil { return nil, ErrSecretsDisabled } rows, err := v.st.RepoSecrets(ctx, repoDID) if err != nil { return nil, err } out := make([]secretMeta, 0, len(rows)) for _, r := range rows { out = append(out, secretMeta{Key: r.Key, CreatedAt: r.CreatedAt, CreatedBy: r.CreatedBy}) } return out, nil}
// Unlocked returns a repository's secrets as key → value. A disabled vault// has none to give, which is not an error: runs simply get no secrets.func (v *secretVault) Unlocked(ctx context.Context, repoDID string) (map[string]string, error) { out := map[string]string{} if v == nil { return out, nil } rows, err := v.st.RepoSecrets(ctx, repoDID) if err != nil { return nil, err } for _, r := range rows { plain, err := v.aead.Open(nil, r.Nonce, r.Sealed, secretAAD(repoDID, r.Key)) if err != nil { // Wrong TACK_SECRETS_KEY, or a tampered row. Either way the // run must not start with a secret silently missing. return nil, fmt.Errorf("decrypt secret %q: %w", r.Key, err) } out[r.Key] = string(plain) } return out, nil}
// secretsTrusted reports whether a run of this trigger may receive the// repository's secrets. A run building another repository's code (a fork)// may not; everything else may.func secretsTrusted(trigger *tangled.Pipeline_TriggerMetadata) bool { if trigger == nil || trigger.SourceRepo == nil || *trigger.SourceRepo == "" { return true } return trigger.Repo != nil && trigger.Repo.RepoDid != nil && *trigger.SourceRepo == *trigger.Repo.RepoDid}
// secretMask replaces secret values in log output with "***", along with// their base64 forms, which is how a value most often leaks by accident// (an Authorization header, a config file echoed back). It is the stock// spindle's masking rule.type secretMask struct { replacer *strings.Replacer}
// newSecretMask returns a mask for values, or nil if there is nothing to mask.func newSecretMask(values map[string]string) *secretMask { var variants []string for _, value := range values { if value == "" { continue } variants = append(variants, value) encoded := base64.StdEncoding.EncodeToString([]byte(value)) variants = append(variants, encoded, strings.TrimRight(encoded, "=")) } if len(variants) == 0 { return nil } // strings.Replacer tries patterns in argument order at each position, so // longer ones go first: a value that contains another must be masked // whole, not left with its tail showing. sort.Slice(variants, func(i, j int) bool { return len(variants[i]) > len(variants[j]) }) pairs := make([]string, 0, 2*len(variants)) seen := map[string]bool{} for _, v := range variants { if v == "" || seen[v] { continue } seen[v] = true pairs = append(pairs, v, "***") } return &secretMask{replacer: strings.NewReplacer(pairs...)}}
// Mask applies the mask. A nil mask returns input unchanged.func (m *secretMask) Mask(input string) string { if m == nil { return input } return m.replacer.Replace(input)}
// repoSecretRow is one stored, still-encrypted secret.type repoSecretRow struct { Key string Nonce []byte Sealed []byte CreatedAt time.Time CreatedBy string}
// PutRepoSecret stores or replaces one encrypted secret.func (s *store) PutRepoSecret( ctx context.Context, repoDID, key string, nonce, sealed []byte, createdBy string, at time.Time,) error { _, err := s.db.ExecContext(ctx, `INSERT INTO repo_secrets (repo_did, key, nonce, sealed, created_by, created_unix_ns) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(repo_did, key) DO UPDATE SET nonce = excluded.nonce, sealed = excluded.sealed, created_by = excluded.created_by, created_unix_ns = excluded.created_unix_ns`, repoDID, key, nonce, sealed, createdBy, at.UnixNano()) if err != nil { return fmt.Errorf("store secret: %w", err) } return nil}
// DeleteRepoSecret removes one secret.func (s *store) DeleteRepoSecret(ctx context.Context, repoDID, key string) error { if _, err := s.db.ExecContext(ctx, `DELETE FROM repo_secrets WHERE repo_did = ? AND key = ?`, repoDID, key); err != nil { return fmt.Errorf("delete secret: %w", err) } return nil}
// RepoSecrets returns a repository's encrypted secrets, ordered by key.func (s *store) RepoSecrets(ctx context.Context, repoDID string) ([]repoSecretRow, error) { rows, err := s.db.QueryContext(ctx, `SELECT key, nonce, sealed, created_by, created_unix_ns FROM repo_secrets WHERE repo_did = ? ORDER BY key`, repoDID) if err != nil { return nil, fmt.Errorf("list secrets: %w", err) } defer rows.Close() var out []repoSecretRow for rows.Next() { var r repoSecretRow var created int64 if err := rows.Scan(&r.Key, &r.Nonce, &r.Sealed, &r.CreatedBy, &created); err != nil { return nil, fmt.Errorf("scan secret: %w", err) } r.CreatedAt = time.Unix(0, created) out = append(out, r) } return out, rows.Err()}
// RepoByRecord resolves a sh.tangled.repo record (its owner DID and record// key) to the repository it describes, from tack's mirror of those records.func (s *store) RepoByRecord(ctx context.Context, ownerDID, rkey string) (*RepoRef, error) { var repo RepoRef var spindle, repoDID sql.NullString err := s.db.QueryRowContext(ctx, `SELECT did, rkey, knot, name, spindle, repo_did FROM repos WHERE did = ? AND rkey = ?`, ownerDID, rkey, ).Scan(&repo.OwnerDID, &repo.Rkey, &repo.Knot, &repo.Name, &spindle, &repoDID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } if err != nil { return nil, fmt.Errorf("look up repo record: %w", err) } repo.Spindle, repo.RepoDID = spindle.String, repoDID.String return &repo, nil}