Exemple #1
0
// Key adds a new secret key to the vault
func Key(w http.ResponseWriter, r *http.Request) {
	api := newAPI(w, r)
	defer api.req.Body.Close()

	if !api.auth() || !api.admin {
		api.error("Unauthorized", 401)
		return
	}

	request, err := api.read()
	if err != nil {
		log.Debug(err)
		api.error("Bad request", 400)
		return
	}

	if request.Name == "" {
		request.Name = uuid.New()
	}

	if !secretIDRegex.MatchString(request.Name) {
		api.error("Invalid key ID", 400)
	}

	key := new(secrets.Key)

	err = key.New(request.Name)
	if err != nil {
		log.Error(err)
		api.error("Server error", 500)
		return
	}

	if request.Admin {
		key.ReadOnly = false
	} else {
		key.ReadOnly = true
	}

	err = database.AddKey(key)
	if err != nil {
		log.Error(err)
		api.error("Database error", 500)
		return
	}

	log.Info("New key added: ", key.Name)

	api.reply(secrets.Key{
		Name:     key.Name,
		Key:      key.Display(),
		ReadOnly: key.ReadOnly,
	},
		201)
}
// ListKeys returns an iterator function that walks through all keys in the database.
// The iterator takes an integer argument, which is the maximum number of results to return per iteration.
// If a secret name is specified, the results are limited to keys with access to that secret.
func (p *DB) ListKeys(secret *string) func(int) ([]secrets.Key, error) {
	pos := 0

	return func(n int) (res []secrets.Key, err error) {
		if err := p.refresh(); err != nil {
			return nil, err
		}

		var rows *sql.Rows

		if secret != nil {
			rows, err = p.conn.Table("keys").Select(
				"keys.id, keys.name, keys.key, keys.nonce, keys.public, keys.read_only").Joins(
				"left join secrets on keys.id = secrets.key_id").Where(
				"secrets.name = ?", *secret).Order("id asc").Limit(n).Offset(pos).Rows()
		} else {
			rows, err = p.conn.Table("keys").Select("id, name, key, nonce, public, read_only").Order("id asc").Limit(n).Offset(pos).Rows()
		}

		for rows.Next() {
			out := new(secrets.Key)
			var ro sql.NullBool
			err = rows.Scan(&out.ID, &out.Name, &out.Key, &out.Nonce, &out.Public, &ro)
			if err != nil {
				return
			}
			if ro.Valid {
				out.ReadOnly = ro.Bool
			} else {
				out.ReadOnly = false
			}
			res = append(res, *out)
		}
		err = rows.Close()
		pos += len(res)
		return
	}
}