Skip to content

Caddy API PUT array insertion doesn't allow inserting at the end of the array #6822

@johnbartholomew

Description

@johnbartholomew

The Caddy API supports inserting an element at an index in an existing array. However, this fails if the provided index would place the item at the end of the array (ie, append the item).

There is a range check on the index here:

caddy/admin.go

Lines 1135 to 1145 in 9996d6a

if method != http.MethodPost {
idxStr := parts[len(parts)-1]
idx, err = strconv.Atoi(idxStr)
if err != nil {
return fmt.Errorf("[%s] invalid array index '%s': %v",
path, idxStr, err)
}
if idx < 0 || idx >= len(arr) {
return fmt.Errorf("[%s] array index out of bounds: %s", path, idxStr)
}
}

The range check makes sense for GET/DELETE/PATCH, but for PUT it would be useful to allow idx to be equal to len(arr). That allows for fewer special cases when using the API.

Example use case:

I have a base config which contains

              "handle": [
                {
                  "@id": "dynamic_routes",
                  "handler": "subroute",
                  "routes": []
                },
              ],

I would like to insert dynamic routes at the start of the routes array inside @dynamic_routes. I think natural way to do this is PUT /id/dynamic_routes/routes/0. But this fails when the array starts out empty. So to always insert at the front of the array I need to first retrieve the current content, check if the array is empty, and if it is then use a POST to append the new item, but if it's not empty then use PUT to item index 0.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions