Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 68 additions & 9 deletions internal/caddy/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package caddy
import (
"encoding/json"
"fmt"
"log"
"reflect"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -68,21 +70,29 @@ func (c *Client) AddRoute(domain, target string) error {
Upstreams: []upstream{{Dial: target}},
}},
}
return c.postRoute(route)
return c.postRoute(route, c.currentRoute(route.ID))
}

func (c *Client) AddRouteWithAuth(domain, target, user, pass string) error {
route, err := authRoute(domain, target, user, pass)
current := c.currentRoute(sanitizeID(domain))
route, err := authRoute(domain, target, user, pass, current)
if err != nil {
return err
}
return c.postRoute(route)
return c.postRoute(route, current)
}

func authRoute(domain, target, user, pass string) (Route, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(pass), 14)
if err != nil {
return Route{}, fmt.Errorf("bcrypt hash: %w", err)
// authRoute keeps the bcrypt hash from current (the route Caddy already holds)
// when it still matches user and pass: a fresh hash has a new salt, so the route
// would never compare equal and every deploy would reload Caddy.
func authRoute(domain, target, user, pass string, current []byte) (Route, error) {
hash := reusableHash(current, user, pass)
if hash == "" {
h, err := bcrypt.GenerateFromPassword([]byte(pass), 14)
if err != nil {
return Route{}, fmt.Errorf("bcrypt hash: %w", err)
}
hash = string(h)
}
return Route{
ID: sanitizeID(domain),
Expand All @@ -92,7 +102,7 @@ func authRoute(domain, target, user, pass string) (Route, error) {
Handler: "authentication",
Providers: &providers{HTTPBasic: httpBasic{
Hash: hashConfig{Algorithm: "bcrypt"},
Accounts: []account{{Username: user, Password: string(hash)}},
Accounts: []account{{Username: user, Password: hash}},
}},
},
{
Expand All @@ -103,7 +113,56 @@ func authRoute(domain, target, user, pass string) (Route, error) {
}, nil
}

func (c *Client) postRoute(route Route) error {
func reusableHash(current []byte, user, pass string) string {
var r Route
if json.Unmarshal(current, &r) != nil {
return ""
}
for _, h := range r.Handle {
if h.Providers == nil {
continue
}
for _, a := range h.Providers.HTTPBasic.Accounts {
if a.Username == user && bcrypt.CompareHashAndPassword([]byte(a.Password), []byte(pass)) == nil {
return a.Password
}
}
}
return ""
}

// currentRoute returns the JSON Caddy holds for route id, or nil if it has none.
func (c *Client) currentRoute(id string) []byte {
out, err := c.ssh.Exec(fmt.Sprintf(`docker exec caddy curl -sf http://localhost:2019/id/%s`, id))
if err != nil {
return nil
}
return []byte(out)
}

// sameRoute compares as decoded JSON: Caddy echoes the route back with its keys
// sorted, so the bytes differ even when nothing changed.
func sameRoute(current []byte, route Route) bool {
want, err := json.Marshal(route)
if err != nil {
return false
}
var a, b any
if json.Unmarshal(current, &a) != nil || json.Unmarshal(want, &b) != nil {
return false
}
return reflect.DeepEqual(a, b)
}

// postRoute replaces the route unless current already equals it. Every admin API
// write reloads Caddy, which closes all proxied websockets (code 1001) on the
// server, so a deploy that does not change the route must not write at all.
func (c *Client) postRoute(route Route, current []byte) error {
if current != nil && sameRoute(current, route) {
log.Printf("Caddy route unchanged: %s", route.Match[0].Host[0])
return nil
}

// Remove old route with same ID (if any, ignore error)
c.ssh.Exec(fmt.Sprintf(
`docker exec caddy curl -s -o /dev/null -X DELETE http://localhost:2019/id/%s`,
Expand Down
60 changes: 59 additions & 1 deletion internal/caddy/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@ package caddy

import (
"encoding/json"
"errors"
"strings"
"testing"

"github.com/coderbuzz/dockify/internal/ssh"
"golang.org/x/crypto/bcrypt"
)

// TestAuthRouteJSON checks the route against Caddy's module ids:
// http.handlers.authentication with provider http.authentication.providers.http_basic.
func TestAuthRouteJSON(t *testing.T) {
route, err := authRoute("app.example.com", "app-1-web:80", "admin", "secret")
route, err := authRoute("app.example.com", "app-1-web:80", "admin", "secret", nil)
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -83,3 +85,59 @@ func TestConfigPath(t *testing.T) {
}
}
}

// fakeCaddy answers the GET of /id/<route> with current (404 when empty) and
// records every admin API write.
type fakeCaddy struct {
ssh.Connector
current string
writes []string
}

func (f *fakeCaddy) Exec(cmd string) (string, error) {
if strings.Contains(cmd, "curl -sf http://localhost:2019/id/") {
if f.current == "" {
return "", errors.New("exit status 22")
}
return f.current, nil
}
if strings.Contains(cmd, " -X ") {
f.writes = append(f.writes, cmd)
}
return "200\n", nil
}

// TestPostRouteSkipsUnchanged: every admin API write reloads Caddy and closes all
// websockets on the server with 1001, so an unchanged route must not be written.
// current is shaped like Caddy's GET /id/ output (keys sorted).
func TestPostRouteSkipsUnchanged(t *testing.T) {
plain := `{"@id":"dockify-a-example-com","handle":[{"handler":"reverse_proxy","upstreams":[{"dial":"web:80"}]}],"match":[{"host":["a.example.com"]}]}` + "\n"
h, _ := bcrypt.GenerateFromPassword([]byte("p"), bcrypt.MinCost)
auth := `{"@id":"dockify-a-example-com","handle":[{"handler":"authentication","providers":{"http_basic":{"accounts":[{"password":"` + string(h) + `","username":"u"}],"hash":{"algorithm":"bcrypt"},"hash_cache":{}}}},{"handler":"reverse_proxy","upstreams":[{"dial":"web:80"}]}],"match":[{"host":["a.example.com"]}]}`

cases := []struct {
name, current string
add func(*Client) error
wantWrites bool
}{
{"unchanged", plain, func(c *Client) error { return c.AddRoute("a.example.com", "web:80") }, false},
{"changed target", plain, func(c *Client) error { return c.AddRoute("a.example.com", "web:81") }, true},
{"missing", "", func(c *Client) error { return c.AddRoute("a.example.com", "web:80") }, true},
{"auth added", plain, func(c *Client) error { return c.AddRouteWithAuth("a.example.com", "web:80", "u", "p") }, true},
{"auth unchanged", auth, func(c *Client) error { return c.AddRouteWithAuth("a.example.com", "web:80", "u", "p") }, false},
{"auth new password", auth, func(c *Client) error { return c.AddRouteWithAuth("a.example.com", "web:80", "u", "p2") }, true},
{"auth removed", auth, func(c *Client) error { return c.AddRoute("a.example.com", "web:80") }, true},
}
for _, tc := range cases {
f := &fakeCaddy{current: tc.current}
if err := tc.add(NewClient(f)); err != nil {
t.Fatalf("%s: %v", tc.name, err)
}
if !tc.wantWrites && len(f.writes) > 0 {
t.Errorf("%s: wrote to Caddy: %q", tc.name, f.writes)
}
if tc.wantWrites && (len(f.writes) != 3 || !strings.Contains(f.writes[0], "-X DELETE") || !strings.Contains(f.writes[2], "-X POST")) {
t.Errorf("%s: want DELETE, POST [], POST route; got %q", tc.name, f.writes)
}
}
}
Loading