feat: SSL wildcard certificate picker from NPM

- NPM client: ListCertificates endpoint
- API: GET /api/settings/npm-certificates (wildcard-only filter)
- Settings UI: EntityPicker for selecting wildcard certs
- Deployer: applies certificate_id + ssl_forced to proxy hosts
- Uses HTTPS subdomain URLs when SSL cert is configured
This commit is contained in:
2026-03-29 13:07:58 +03:00
parent e94c4f9116
commit 9f284932a1
13 changed files with 253 additions and 21 deletions
+1
View File
@@ -131,6 +131,7 @@ func (s *Server) Router() chi.Router {
r.Get("/images", s.listRegistryImages)
})
r.Get("/settings", s.getSettings)
r.Get("/settings/npm-certificates", s.listNpmCertificates)
// Admin-only routes: require admin role.
r.Group(func(r chi.Router) {
+74 -10
View File
@@ -3,8 +3,10 @@ package api
import (
"fmt"
"net/http"
"strings"
"github.com/alexei/docker-watcher/internal/crypto"
"github.com/alexei/docker-watcher/internal/npm"
"github.com/alexei/docker-watcher/internal/webhook"
)
@@ -19,6 +21,7 @@ type settingsRequest struct {
NpmEmail string `json:"npm_email"`
NpmPassword string `json:"npm_password"`
PollingInterval string `json:"polling_interval"`
SSLCertificateID *int `json:"ssl_certificate_id,omitempty"`
}
// getSettings handles GET /api/settings.
@@ -31,16 +34,17 @@ func (s *Server) getSettings(w http.ResponseWriter, r *http.Request) {
// Return settings without sensitive fields.
respondJSON(w, http.StatusOK, map[string]any{
"domain": settings.Domain,
"server_ip": settings.ServerIP,
"network": settings.Network,
"subdomain_pattern": settings.SubdomainPattern,
"notification_url": settings.NotificationURL,
"npm_url": settings.NpmURL,
"npm_email": settings.NpmEmail,
"has_npm_password": settings.NpmPassword != "",
"polling_interval": settings.PollingInterval,
"updated_at": settings.UpdatedAt,
"domain": settings.Domain,
"server_ip": settings.ServerIP,
"network": settings.Network,
"subdomain_pattern": settings.SubdomainPattern,
"notification_url": settings.NotificationURL,
"npm_url": settings.NpmURL,
"npm_email": settings.NpmEmail,
"has_npm_password": settings.NpmPassword != "",
"polling_interval": settings.PollingInterval,
"ssl_certificate_id": settings.SSLCertificateID,
"updated_at": settings.UpdatedAt,
})
}
@@ -89,6 +93,9 @@ func (s *Server) updateSettings(w http.ResponseWriter, r *http.Request) {
if req.PollingInterval != "" {
updated.PollingInterval = req.PollingInterval
}
if req.SSLCertificateID != nil {
updated.SSLCertificateID = *req.SSLCertificateID
}
if err := s.store.UpdateSettings(updated); err != nil {
respondError(w, http.StatusInternalServerError, "failed to update settings: "+err.Error())
@@ -140,3 +147,60 @@ func (s *Server) regenerateWebhookSecret(w http.ResponseWriter, r *http.Request)
})
}
// listNpmCertificates handles GET /api/settings/npm-certificates.
// It authenticates to NPM using the stored credentials and returns only wildcard certificates.
func (s *Server) listNpmCertificates(w http.ResponseWriter, r *http.Request) {
settings, err := s.store.GetSettings()
if err != nil {
respondError(w, http.StatusInternalServerError, "failed to get settings: "+err.Error())
return
}
if settings.NpmURL == "" || settings.NpmEmail == "" || settings.NpmPassword == "" {
respondError(w, http.StatusBadRequest, "NPM credentials not configured")
return
}
npmPassword, err := crypto.Decrypt(s.encKey, settings.NpmPassword)
if err != nil {
respondError(w, http.StatusInternalServerError, "failed to decrypt npm password: "+err.Error())
return
}
client := npm.New(settings.NpmURL)
if err := client.Authenticate(r.Context(), settings.NpmEmail, npmPassword); err != nil {
respondError(w, http.StatusBadGateway, "failed to authenticate to NPM: "+err.Error())
return
}
certs, err := client.ListCertificates(r.Context())
if err != nil {
respondError(w, http.StatusBadGateway, "failed to list certificates: "+err.Error())
return
}
// Filter to wildcard certificates only.
var wildcards []npm.Certificate
for _, cert := range certs {
if isWildcardCert(cert) {
wildcards = append(wildcards, cert)
}
}
if wildcards == nil {
wildcards = []npm.Certificate{}
}
respondJSON(w, http.StatusOK, wildcards)
}
// isWildcardCert returns true if any of the certificate's domain names contains "*".
func isWildcardCert(cert npm.Certificate) bool {
for _, d := range cert.DomainNames {
if strings.Contains(d, "*") {
return true
}
}
return false
}
+9
View File
@@ -425,6 +425,15 @@ func (d *Deployer) configureProxy(
Locations: []any{},
}
// Apply SSL certificate if configured in settings.
if settings.SSLCertificateID > 0 {
proxyConfig.CertificateID = settings.SSLCertificateID
proxyConfig.SSLForced = true
proxyConfig.HSTSEnabled = true
proxyConfig.HTTP2Support = true
d.logDeploy(deployID, fmt.Sprintf("Using SSL certificate ID %d", settings.SSLCertificateID), "info")
}
if found {
d.logDeploy(deployID, fmt.Sprintf("Updating existing proxy host %d for %s", existing.ID, fqdn), "info")
host, err := d.npm.UpdateProxyHost(ctx, existing.ID, proxyConfig)
+9
View File
@@ -154,6 +154,15 @@ func (c *Client) FindProxyHostByDomain(ctx context.Context, domain string) (Prox
return ProxyHost{}, false, nil
}
// ListCertificates returns all SSL certificates from NPM.
func (c *Client) ListCertificates(ctx context.Context) ([]Certificate, error) {
var certs []Certificate
if err := c.doJSON(ctx, http.MethodGet, "/nginx/certificates", nil, &certs); err != nil {
return nil, fmt.Errorf("list certificates: %w", err)
}
return certs, nil
}
// doJSON performs an authenticated JSON API request. If the token is expired or a 401
// is received, it automatically re-authenticates and retries the request once.
func (c *Client) doJSON(ctx context.Context, method, path string, reqBody any, result any) error {
+9
View File
@@ -50,6 +50,15 @@ type ProxyHost struct {
ModifiedOn string `json:"modified_on"`
}
// Certificate represents an SSL certificate as returned by the NPM API.
type Certificate struct {
ID int `json:"id"`
NiceName string `json:"nice_name"`
DomainNames []string `json:"domain_names"`
ExpiresOn string `json:"expires_on"`
Provider string `json:"provider"`
}
// boolInt handles the NPM API's inconsistent use of 0/1 integers for boolean fields.
type boolInt bool
+1
View File
@@ -55,6 +55,7 @@ type Settings struct {
WebhookSecret string `json:"webhook_secret"`
PollingInterval string `json:"polling_interval"`
BaseVolumePath string `json:"base_volume_path"`
SSLCertificateID int `json:"ssl_certificate_id"`
UpdatedAt string `json:"updated_at"`
}
+4 -4
View File
@@ -9,10 +9,10 @@ func (s *Store) GetSettings() (Settings, error) {
var st Settings
err := s.db.QueryRow(
`SELECT domain, server_ip, network, subdomain_pattern, notification_url,
npm_url, npm_email, npm_password, webhook_secret, polling_interval, base_volume_path, updated_at
npm_url, npm_email, npm_password, webhook_secret, polling_interval, base_volume_path, ssl_certificate_id, updated_at
FROM settings WHERE id = 1`,
).Scan(&st.Domain, &st.ServerIP, &st.Network, &st.SubdomainPattern, &st.NotificationURL,
&st.NpmURL, &st.NpmEmail, &st.NpmPassword, &st.WebhookSecret, &st.PollingInterval, &st.BaseVolumePath, &st.UpdatedAt)
&st.NpmURL, &st.NpmEmail, &st.NpmPassword, &st.WebhookSecret, &st.PollingInterval, &st.BaseVolumePath, &st.SSLCertificateID, &st.UpdatedAt)
if err != nil {
return Settings{}, fmt.Errorf("query settings: %w", err)
}
@@ -25,10 +25,10 @@ func (s *Store) UpdateSettings(st Settings) error {
_, err := s.db.Exec(
`UPDATE settings SET
domain=?, server_ip=?, network=?, subdomain_pattern=?, notification_url=?,
npm_url=?, npm_email=?, npm_password=?, webhook_secret=?, polling_interval=?, base_volume_path=?, updated_at=?
npm_url=?, npm_email=?, npm_password=?, webhook_secret=?, polling_interval=?, base_volume_path=?, ssl_certificate_id=?, updated_at=?
WHERE id = 1`,
st.Domain, st.ServerIP, st.Network, st.SubdomainPattern, st.NotificationURL,
st.NpmURL, st.NpmEmail, st.NpmPassword, st.WebhookSecret, st.PollingInterval, st.BaseVolumePath, st.UpdatedAt,
st.NpmURL, st.NpmEmail, st.NpmPassword, st.WebhookSecret, st.PollingInterval, st.BaseVolumePath, st.SSLCertificateID, st.UpdatedAt,
)
if err != nil {
return fmt.Errorf("update settings: %w", err)
+3
View File
@@ -79,6 +79,8 @@ func (s *Store) runMigrations() error {
`ALTER TABLE settings ADD COLUMN base_volume_path TEXT NOT NULL DEFAULT ''`,
// Add enable_proxy to stages (2026-03-29). Default true for backwards compat.
`ALTER TABLE stages ADD COLUMN enable_proxy INTEGER NOT NULL DEFAULT 1`,
// Add ssl_certificate_id to settings (2026-03-29).
`ALTER TABLE settings ADD COLUMN ssl_certificate_id INTEGER NOT NULL DEFAULT 0`,
}
for _, m := range migrations {
@@ -159,6 +161,7 @@ CREATE TABLE IF NOT EXISTS settings (
webhook_secret TEXT NOT NULL DEFAULT '',
polling_interval TEXT NOT NULL DEFAULT '5m',
base_volume_path TEXT NOT NULL DEFAULT '',
ssl_certificate_id INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);