gateway: HTTPS for other computers, from magpie's CA or an imported certificate (zhangly1 on X)
zhangly1 on X: Claude on another computer on the LAN needed magpie at https://. Settings → Network and sharing → HTTPS (magpie https on) serves other computers TLS on the gateway's own port, with a certificate magpie's CA (the mTLS one, in ~/.config/magpie/mtls) signs for this computer's names and addresses; this computer keeps plain http://. The switch is read per connection, so no restart. - Certificate row: Import… takes the user's own PEM certificate (with chain) and unencrypted key, in any files and order; a pair that can't be served (no key, no cert, a stranger key, a passphrase, run out, nothing PEM) is refused with the reason in the page's language and leaves nothing behind. Remove goes back to magpie's CA. --tls-cert still comes first. - magpie's CA row: SHA-256 shown, Save puts magpie-ca.crt in Downloads; the gateway serves it without a key at /magpie-ca.crt to any address the share lets in. Rows under it give curl -kO, macOS, Windows, Linux and NODE_EXTRA_CA_CERTS steps with Copy. - A page open from another computer can't turn HTTPS on or off under itself (it would lose its own address). - magpie https status|on|off|import|remove|ca --out; the serve banner names magpie's CA or the imported file instead of "(mTLS)". - docs/reference.md and gateway-routing.md say all of it, and that Windows' curl.exe needs --ssl-no-revoke for any private CA. Run: - gofmt -l clean; go vet linux -tags nogui ./internal/..., GOOS=windows and GOOS=darwin -tags nogui vet of the touched packages (WSL, mote refused ssh all evening). - WSL: go test -tags nogui gateway -run HTTPS|MTLS|ClientCert|CAFile|TLS|LAN ok; gui -run HTTPS|MTLS|Keep ok; settings, settingsapi, mtls ok; cli -run Help|HTTPS|TLS|Serve|Banner|Flag|Unknown ok. The whole cli package hit its 40m timeout in TestEveryAgentFieldNameWritesNothing (#5234, #4247, not this change). - GUI (WSL Playwright, chromium + webkit): https-settings (en, zh, 390px, strings in all four languages) ok, plus mtls-settings, allow-ips, browser-access, cors-origins, gui-de/ja/zh-tw, i18n-keys, i18n-en-no-cjk, lan-*, public-url*, api-key-theme, connect-address-kept, gateway-connect-keys, gateway-caller-keys, side-gateway-lan, menu-scroll. Reds at load ~130: api-key-theme (#5044), connect-address-kept (#5972), gateway-caller-keys (#2572), gui-ja (#5943), lan-docker (#4692), all red the same at base10bef5fe0run beside it; allow-ips and gateway-connect-keys went red once under that load and pass 18/18 at concurrency 1, base and this change side by side. - Real: a sandbox HOME gateway built from this tree on WSL (MAGPIE_ADDR=0.0.0.0:3593, a gateway key, magpie https on, magpie serve). From the Windows host: curl -k /magpie-ca.crt 200 without a key; Node fetch with NODE_EXTRA_CA_CERTS=magpie-ca.crt 200 on /v1/models, 401 without the key, SELF_SIGNED_CERT_IN_CHAIN without the CA; plain http:// 400; curl.exe --cacert needs --ssl-no-revoke (schannel), then 200. Cert SANs: localhost, the hostname, .local, 127.0.0.1, ::1 and every address. magpie https import of an openssl CA's leaf on the running gateway: Node trusting that CA 200, magpie's CA alone refused. remove + off on the running gateway: plain http:// from Windows 200. This computer's plain http:// 200 throughout. - At the pushed tree (on origin/mainee818e8bc), WSL: gofmt -l clean; go vet -tags nogui linux, GOOS=windows, GOOS=darwin nogui of gateway, gui, cli ok; go test -run 'HTTPS|CAFile|MTLS|LAN' gateway, gui ok. GUI https-settings, mtls-settings, i18n-keys, gui-de/ja/zh-tw, allow-ips, lan-* (both engines): 147/155; reds are gui-ja (#5943), lan-docker (#4692), allow-ips webkit under load, and gui-zh-tw chromium under load (2 of 3 green alone, filed #5983). Broken by hand: - TLSOn without HTTPSOn: TestHTTPSOtherComputer red. - lanGuard without the caFileOpen exemption: TestHTTPSCAFile red. - mtls config without GetCertificate = settingsCert: all three serving tests red. - app.js without renderHTTPS(s): https-settings red in both engines. Not tried: the macOS, Windows and Linux system trust commands on a real store (they change the box's trust); Claude Desktop itself; a darwin GUI run (mote unreachable); the full suite before the tag (started after it).
This commit is contained in:
@@ -962,6 +962,40 @@ since no certificate for the server's name covers loopback. A container or
|
||||
a WSL distro calling through its NAT address is another computer, and uses
|
||||
`https://`. Gateway keys, sharing and allowed addresses work as over HTTP.
|
||||
|
||||
**HTTPS on the local network.** Without a certificate of your own, turn
|
||||
on Settings → Network and sharing → HTTPS (or `magpie https on`; zhangly1
|
||||
on X: Claude on another computer needed magpie at `https://`). magpie
|
||||
serves other computers `https://` with a certificate its own CA (the mTLS
|
||||
one, in `~/.config/magpie/mtls`) signs for this computer's names, its
|
||||
addresses and the name the client dialled; this computer keeps plain
|
||||
`http://`. Each computer that calls magpie trusts the CA once: Save under
|
||||
magpie's CA puts `magpie-ca.crt` in Downloads, and the gateway serves it
|
||||
to any address the share lets in, without a key, at
|
||||
`https://<this computer>:<port>/magpie-ca.crt` (`curl -kO`, then check its
|
||||
SHA-256 against the one Settings and `magpie https` show). Then:
|
||||
|
||||
```sh
|
||||
# macOS
|
||||
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain magpie-ca.crt
|
||||
# Windows, as administrator
|
||||
certutil -addstore -f Root magpie-ca.crt
|
||||
# Debian, Ubuntu
|
||||
sudo cp magpie-ca.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates
|
||||
# Claude Code and other Node apps, which keep their own list
|
||||
export NODE_EXTRA_CA_CERTS=/path/to/magpie-ca.crt
|
||||
```
|
||||
|
||||
Windows' own `curl.exe` checks revocation, which a private CA has none
|
||||
of, so it needs `--ssl-no-revoke`; Node, browsers and Claude Code don't.
|
||||
|
||||
To serve a certificate of your own instead (one your network's CA, or a
|
||||
public one, signed), Import… under Certificate (or `magpie https import
|
||||
cert.pem key.pem`): PEM, the certificate with its chain and an
|
||||
unencrypted key, in one file or several. It is kept in
|
||||
`~/.config/magpie/https` and read again when it changes; Remove goes back
|
||||
to magpie's CA. `--tls-cert` comes before both. A page open from another
|
||||
computer can't turn HTTPS on or off under itself.
|
||||
|
||||
**Client certificates (mTLS).** A magpie open to the internet can also
|
||||
ask every other computer for a client certificate it issued itself
|
||||
(hhdaxia on X, #5596), so a stolen gateway key alone gets nowhere. Turn on
|
||||
@@ -3531,6 +3565,7 @@ magpie web # the app's window in a browser (WSL, a server o
|
||||
# (behind a reverse proxy, MAGPIE_WEB_URL=https://<the page there> prints the link through it)
|
||||
magpie serve # the gateway alone, no window; --web[=host:port] serves the page too, from the same process
|
||||
# --tls-cert <file> --tls-key <file>: https:// for other computers (see HTTPS under sharing)
|
||||
magpie https # https:// for other computers: on, off, import <files>, remove, ca [--out]
|
||||
magpie mtls # other computers need a client certificate magpie issued: on, off, issue <device>, revoke <device>, list
|
||||
magpie daemon install # run magpie serve as a service (systemd, launchd); --web, --lan, --addr serve the page too; --tls-cert/--tls-key, --no-tls
|
||||
magpie ls # list every agent and its current settings
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -56,6 +56,8 @@ func helpFor(args []string) string {
|
||||
return statuslineUsage
|
||||
case "mtls":
|
||||
return mtlsUsage
|
||||
case "https":
|
||||
return httpsUsage
|
||||
case "heap":
|
||||
return heapUsage
|
||||
case "cpu":
|
||||
|
||||
@@ -129,7 +129,7 @@ func runCommands(t *testing.T) []string {
|
||||
if len(cmds) < 40 {
|
||||
t.Fatalf("read %d commands from run's switch: %v", len(cmds), cmds)
|
||||
}
|
||||
return append(cmds, "healthcheck", "heap", "cpu", "goroutines", "mtls")
|
||||
return append(cmds, "healthcheck", "heap", "cpu", "goroutines", "mtls", "https")
|
||||
}
|
||||
|
||||
func types(ix *ast.IndexExpr) string {
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/mtls"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
const httpsUsage = `usage: magpie https [on|off|import <cert.pem> [<key.pem>…]|remove|ca [--out <folder>]]
|
||||
other computers reach this magpie's gateway, and magpie web's page, at https://
|
||||
(zhangly1 on X: Claude on another computer on the LAN). This computer, and a WSL
|
||||
distro's agent, may still call plain http://.
|
||||
magpie https whether it is on, the certificate served and magpie's CA
|
||||
magpie https on|off serve other computers over https://, or plain http:// again
|
||||
magpie https import <files> serve your own certificate (its chain after it) and key,
|
||||
PEM, in one file or several; kept in magpie's folder
|
||||
magpie https remove back to a certificate magpie's own CA signs for this
|
||||
computer's names and addresses
|
||||
magpie https ca save magpie's CA as magpie-ca.crt in Downloads (or --out)
|
||||
Without a certificate of your own, each computer that calls magpie trusts its CA once.
|
||||
Get it from Settings, or on that computer from https://<this computer>:<port>/magpie-ca.crt
|
||||
(check its SHA-256 against the one magpie https prints), then:
|
||||
macOS sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain magpie-ca.crt
|
||||
Windows certutil -addstore -f Root magpie-ca.crt (as administrator)
|
||||
Linux sudo cp magpie-ca.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates
|
||||
Node apps such as Claude Code: NODE_EXTRA_CA_CERTS=/path/to/magpie-ca.crt`
|
||||
|
||||
func httpsCmd(args []string) error {
|
||||
if len(args) == 0 || args[0] == "status" {
|
||||
return httpsStatus()
|
||||
}
|
||||
switch args[0] {
|
||||
case "on", "off":
|
||||
on := args[0] == "on"
|
||||
if on {
|
||||
if c, _ := gateway.ImportedFiles(); c == "" {
|
||||
if _, _, err := gateway.CA(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := settings.SetHTTPS(on); err != nil {
|
||||
return err
|
||||
}
|
||||
if !on {
|
||||
fmt.Println("HTTPS off: other computers call magpie at http:// again")
|
||||
if gateway.TLSOn() {
|
||||
fmt.Println("(still served over https://: --tls-cert or mTLS is on)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
fmt.Println("HTTPS on: other computers call magpie at https://; this computer may still call http://")
|
||||
return httpsStatus()
|
||||
case "import":
|
||||
if len(args) < 2 {
|
||||
return errors.New("usage: magpie https import <cert.pem> [<key.pem>…]")
|
||||
}
|
||||
var files [][]byte
|
||||
for _, f := range args[1:] {
|
||||
b, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
files = append(files, b)
|
||||
}
|
||||
if err := gateway.ImportCert(files...); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("imported: other computers are served this certificate over https://")
|
||||
if !gateway.HTTPSOn() && !gateway.TLSOn() {
|
||||
fmt.Println("HTTPS is off: magpie https on to serve it")
|
||||
}
|
||||
return httpsStatus()
|
||||
case "remove":
|
||||
if err := gateway.RemoveImportedCert(); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("removed: magpie's CA signs the certificate served")
|
||||
return nil
|
||||
case "ca":
|
||||
rest, out, err := outFlag(args[1:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rest) != 0 {
|
||||
return errors.New("usage: magpie https ca [--out <folder>]")
|
||||
}
|
||||
b, fp, err := gateway.CA()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if out == "" {
|
||||
out = downloadsDir()
|
||||
}
|
||||
p := filepath.Join(out, "magpie-ca.crt")
|
||||
if err := mtls.WriteFile(p, b, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(p)
|
||||
fmt.Println(" SHA-256 " + fp)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("magpie https: unknown %q\n%s", args[0], httpsUsage)
|
||||
}
|
||||
|
||||
func httpsStatus() error {
|
||||
state := "off"
|
||||
if gateway.HTTPSOn() {
|
||||
state = "on"
|
||||
}
|
||||
fmt.Println("HTTPS " + state)
|
||||
if !gateway.TLSOn() {
|
||||
return nil
|
||||
}
|
||||
c, err := gateway.ServedCert()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
from := map[string]string{"files": "--tls-cert " + c.File, "imported": "imported", "magpie": "magpie's CA"}[c.From]
|
||||
fmt.Printf(" certificate %s · %s · until %s\n", from, strings.Join(c.Names, ", "), c.Until.Format("2006-01-02"))
|
||||
if c.From == "magpie" {
|
||||
_, fp, err := gateway.CA()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(" CA " + gateway.MTLSStore().CAFile())
|
||||
fmt.Println(" SHA-256 " + fp)
|
||||
fmt.Println(" trust it on each computer that calls magpie: magpie https --help")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -133,6 +133,8 @@ const usage = `magpie — one place to pick every agent's model
|
||||
magpie healthcheck exit 0 when the gateway answers (a container's HEALTHCHECK)
|
||||
magpie mtls [on|off|issue <device>|list|revoke <device>]
|
||||
require a client certificate magpie issued from other computers (mTLS)
|
||||
magpie https [on|off|import <files>|remove|ca]
|
||||
other computers call magpie at https://, with your certificate or one magpie's own CA signs
|
||||
magpie heap [<file>] a Go heap profile of the running magpie, with its memory numbers, for a report of it using too much memory
|
||||
magpie cpu [<file>] [--seconds N] a Go CPU profile of the running magpie over 30s (5..120) while you use it, for a report of it using too much CPU
|
||||
magpie goroutines [<file>] every goroutine of the running magpie, its stack and how long it waited, for a report of it stuck at something
|
||||
@@ -356,6 +358,11 @@ func run(args []string) error {
|
||||
// else is read or moved
|
||||
return mtlsCmd(args[1:])
|
||||
}
|
||||
if len(args) > 0 && args[0] == "https" {
|
||||
// HTTPS for other computers: the setting, the certificate and
|
||||
// magpie's CA, nothing else
|
||||
return httpsCmd(args[1:])
|
||||
}
|
||||
if len(args) > 0 && args[0] == "cpu" {
|
||||
// the running magpie's CPU profile: asks it, and moves nothing here
|
||||
return cpuCmd(args[1:])
|
||||
|
||||
@@ -44,7 +44,10 @@ func tlsLine() string {
|
||||
}
|
||||
cert, _ := gateway.TLSFiles()
|
||||
if cert == "" {
|
||||
cert = "magpie's own CA (mTLS)"
|
||||
cert = "magpie's own CA"
|
||||
if c, _ := gateway.ImportedFiles(); c != "" {
|
||||
cert = c
|
||||
}
|
||||
}
|
||||
s := muted.Render(" TLS ") + " " + cert
|
||||
if sum := gateway.TLSSummary(); sum != "" {
|
||||
|
||||
@@ -1045,6 +1045,7 @@ func (s *Server) routes() *routeMux {
|
||||
// another magpie looking for it at a new address (remote_prove.go)
|
||||
mux.HandleFunc("POST "+provider.RemoteProvePath, s.prove)
|
||||
mux.HandleFunc("GET "+KeyPagePath, s.keyPage)
|
||||
mux.HandleFunc("GET "+CAPath, s.caFile)
|
||||
mux.HandleFunc("GET "+keyPageData, s.keyInfo)
|
||||
// the join page, where another computer that knows the join password
|
||||
// gets a gateway key of its own (join.go)
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/mtls"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// HTTPS for other computers without a certificate of a server's own
|
||||
// (zhangly1 on X: Claude on another computer on the LAN needed magpie at
|
||||
// https://). With Settings → Network and sharing → HTTPS on (settings
|
||||
// HTTPS, `magpie https on`) the listener serves other computers TLS as it
|
||||
// does with --tls-cert or mTLS (tlsListener), with:
|
||||
//
|
||||
// - the certificate and key imported in Settings or by `magpie https
|
||||
// import` (kept in <dir>/https, read again when they change), else
|
||||
// - one magpie's own CA (the mTLS one, made on first use) signs in
|
||||
// memory for this computer's names, its addresses and the name the
|
||||
// client dialled (ownServerCert).
|
||||
//
|
||||
// --tls-cert comes before both. Another computer trusts magpie's CA once:
|
||||
// Settings saves it to Downloads, and the gateway serves it at CAPath to
|
||||
// any address it lets in, without a key (a CA's certificate is public;
|
||||
// its fingerprint is shown beside it to check the copy by). This computer,
|
||||
// and a WSL distro's agent, may still call plain http://.
|
||||
|
||||
// HTTPSOn: other computers reach magpie over https:// (the setting).
|
||||
func HTTPSOn() bool { return settings.Shared().HTTPS }
|
||||
|
||||
// CAPath is where the gateway serves magpie's CA, for another computer to
|
||||
// trust: .crt, which Windows opens to install and Debian's
|
||||
// update-ca-certificates reads, as PEM, which every system takes.
|
||||
const CAPath = "/magpie-ca.crt"
|
||||
|
||||
// FromThisComputer: r came from this computer, over loopback or to one of
|
||||
// its own addresses, not through a proxy.
|
||||
func FromThisComputer(r *http.Request) bool { return local(r) || ownAddress(r) }
|
||||
|
||||
func httpsDir() string { return filepath.Join(settings.Dir(), "https") }
|
||||
|
||||
// ImportedFiles are the certificate and key Settings imported, "" for
|
||||
// none (both must be there).
|
||||
func ImportedFiles() (cert, key string) {
|
||||
cert, key = filepath.Join(httpsDir(), "cert.pem"), filepath.Join(httpsDir(), "key.pem")
|
||||
if _, err := os.Stat(cert); err != nil {
|
||||
return "", ""
|
||||
}
|
||||
if _, err := os.Stat(key); err != nil {
|
||||
return "", ""
|
||||
}
|
||||
return cert, key
|
||||
}
|
||||
|
||||
var imported struct {
|
||||
sync.Mutex
|
||||
files *certFiles
|
||||
}
|
||||
|
||||
// importedCert serves the imported pair, read again when it changes; nil
|
||||
// with none imported.
|
||||
func importedCert() *certFiles {
|
||||
c, k := ImportedFiles()
|
||||
if c == "" {
|
||||
return nil
|
||||
}
|
||||
imported.Lock()
|
||||
defer imported.Unlock()
|
||||
if imported.files == nil || imported.files.cert != c || imported.files.key != k {
|
||||
imported.files = &certFiles{cert: c, key: k}
|
||||
}
|
||||
return imported.files
|
||||
}
|
||||
|
||||
// settingsCert is the server certificate without --tls-cert: the one
|
||||
// imported, else one magpie's CA signs. An imported pair that doesn't
|
||||
// load (its files removed by hand, say) gives way to magpie's own rather
|
||||
// than ending every handshake.
|
||||
func settingsCert(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
if f := importedCert(); f != nil {
|
||||
c, err := f.get(hello)
|
||||
if err == nil {
|
||||
return c, nil
|
||||
}
|
||||
log.Printf("TLS: the imported certificate in %s doesn't load (%v): serving one magpie's CA signs", httpsDir(), err)
|
||||
}
|
||||
return ownServerCert(hello)
|
||||
}
|
||||
|
||||
// ImportCert keeps a certificate (its chain after it) and its key for
|
||||
// HTTPS, from PEM files given in any order and split any way: one file
|
||||
// holding both, or a certificate, a chain and a key apart. The
|
||||
// certificate the key belongs to goes first. Refused: no certificate, no
|
||||
// key, an encrypted key, a key that belongs to none of them, or a
|
||||
// certificate that has run out.
|
||||
func ImportCert(files ...[]byte) error {
|
||||
var certs [][]byte
|
||||
var key *pem.Block
|
||||
for _, b := range files {
|
||||
for {
|
||||
var blk *pem.Block
|
||||
blk, b = pem.Decode(b)
|
||||
if blk == nil {
|
||||
break
|
||||
}
|
||||
switch {
|
||||
case blk.Type == "CERTIFICATE":
|
||||
certs = append(certs, blk.Bytes)
|
||||
case blk.Type == "ENCRYPTED PRIVATE KEY" || blk.Headers["Proc-Type"] != "":
|
||||
return errors.New("the private key has a passphrase: give it without one (openssl pkey -in key.pem -out key-open.pem)")
|
||||
case strings.HasSuffix(blk.Type, "PRIVATE KEY"):
|
||||
if key == nil {
|
||||
key = blk
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case len(certs) == 0 && key == nil:
|
||||
return errors.New("no PEM certificate or key in the files given")
|
||||
case len(certs) == 0:
|
||||
return errors.New("a private key but no certificate: give the certificate's file too")
|
||||
case key == nil:
|
||||
return errors.New("a certificate but no private key: give the key's file too")
|
||||
}
|
||||
keyPEM := pem.EncodeToMemory(key)
|
||||
leaf := -1
|
||||
for i, der := range certs {
|
||||
if _, err := tls.X509KeyPair(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), keyPEM); err == nil {
|
||||
leaf = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if leaf < 0 {
|
||||
return errors.New("the private key belongs to none of the certificates given")
|
||||
}
|
||||
certs[0], certs[leaf] = certs[leaf], certs[0]
|
||||
var chain []byte
|
||||
for _, der := range certs {
|
||||
chain = append(chain, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})...)
|
||||
}
|
||||
pair, err := tls.X509KeyPair(chain, keyPEM)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the certificate and key can't be served: %w", err)
|
||||
}
|
||||
if pair.Leaf == nil {
|
||||
if pair.Leaf, err = x509.ParseCertificate(pair.Certificate[0]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if time.Now().After(pair.Leaf.NotAfter) {
|
||||
return fmt.Errorf("the certificate ran out on %s", pair.Leaf.NotAfter.Format("2006-01-02"))
|
||||
}
|
||||
if err := os.MkdirAll(httpsDir(), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := mtls.WriteFile(filepath.Join(httpsDir(), "key.pem"), keyPEM, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return mtls.WriteFile(filepath.Join(httpsDir(), "cert.pem"), chain, 0o644)
|
||||
}
|
||||
|
||||
// RemoveImportedCert goes back to the certificate magpie's CA signs.
|
||||
func RemoveImportedCert() error {
|
||||
for _, f := range []string{"cert.pem", "key.pem"} {
|
||||
if err := os.Remove(filepath.Join(httpsDir(), f)); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CertInfo is what the certificate other computers are served says.
|
||||
type CertInfo struct {
|
||||
// From: "files" (--tls-cert, File naming it), "imported" or "magpie"
|
||||
// (its CA's)
|
||||
From string `json:"from"`
|
||||
File string `json:"file,omitempty"`
|
||||
Names []string `json:"names,omitempty"`
|
||||
Issuer string `json:"issuer,omitempty"`
|
||||
Until time.Time `json:"until"`
|
||||
}
|
||||
|
||||
// ServedCert says which certificate other computers get over https://.
|
||||
func ServedCert() (CertInfo, error) {
|
||||
var c *tls.Certificate
|
||||
var info CertInfo
|
||||
var err error
|
||||
if cf, kf := TLSFiles(); cf != "" && kf != "" {
|
||||
info.From, info.File = "files", cf
|
||||
var pair tls.Certificate
|
||||
pair, err = tls.LoadX509KeyPair(cf, kf)
|
||||
c = &pair
|
||||
} else if f := importedCert(); f != nil {
|
||||
info.From = "imported"
|
||||
c, err = f.get(nil)
|
||||
} else {
|
||||
info.From = "magpie"
|
||||
c, err = ownServerCert(nil)
|
||||
}
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
if c == nil || len(c.Certificate) == 0 {
|
||||
return info, errors.New("no certificate")
|
||||
}
|
||||
leaf, err := x509.ParseCertificate(c.Certificate[0])
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
info.Names = append(info.Names, leaf.DNSNames...)
|
||||
for _, ip := range leaf.IPAddresses {
|
||||
info.Names = append(info.Names, ip.String())
|
||||
}
|
||||
if len(info.Names) == 0 && leaf.Subject.CommonName != "" {
|
||||
info.Names = []string{leaf.Subject.CommonName}
|
||||
}
|
||||
info.Issuer, info.Until = leaf.Issuer.CommonName, leaf.NotAfter
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// CA is magpie's CA certificate as PEM, made on first use, and its
|
||||
// SHA-256 fingerprint (AB:CD:…), which a copy fetched over the network
|
||||
// is checked by.
|
||||
func CA() (pemBytes []byte, fingerprint string, err error) {
|
||||
ca, _, err := MTLSStore().CA()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca.Raw}), Fingerprint(ca.Raw), nil
|
||||
}
|
||||
|
||||
// Fingerprint is der's SHA-256 as colon-separated hex pairs, as Keychain
|
||||
// Access, certmgr and openssl x509 -fingerprint show it.
|
||||
func Fingerprint(der []byte) string {
|
||||
sum := sha256.Sum256(der)
|
||||
parts := make([]string, len(sum))
|
||||
for i, b := range sum {
|
||||
parts[i] = fmt.Sprintf("%02X", b)
|
||||
}
|
||||
return strings.Join(parts, ":")
|
||||
}
|
||||
|
||||
// caFileOpen: r asks for magpie's CA, which is answered without a key.
|
||||
func caFileOpen(r *http.Request) bool {
|
||||
return r.URL.Path == CAPath && r.URL.RawPath == "" && (r.Method == http.MethodGet || r.Method == http.MethodHead)
|
||||
}
|
||||
|
||||
// caFile serves magpie's CA. One isn't made for a request: until HTTPS or
|
||||
// mTLS made it, there is none to trust.
|
||||
func (s *Server) caFile(w http.ResponseWriter, r *http.Request) {
|
||||
st := MTLSStore()
|
||||
if !st.HasCA() {
|
||||
http.Error(w, "this magpie has no CA yet: turn on HTTPS in Settings → Network and sharing (magpie https on)", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
b, err := os.ReadFile(st.CAFile())
|
||||
if err != nil {
|
||||
http.Error(w, "magpie's CA can't be read: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "application/x-x509-ca-cert")
|
||||
h.Set("Content-Disposition", `attachment; filename="magpie-ca.crt"`)
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("Cache-Control", "no-cache")
|
||||
w.Write(b)
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
func setHTTPS(t *testing.T, on bool) {
|
||||
t.Helper()
|
||||
if err := settings.SetHTTPS(on); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if HTTPSOn() != on {
|
||||
t.Fatalf("HTTPSOn() = %v after SetHTTPS(%v)", !on, on)
|
||||
}
|
||||
}
|
||||
|
||||
// trusting is an HTTPS client that trusts only roots' certificates.
|
||||
func trusting(t *testing.T, roots ...*x509.Certificate) *http.Client {
|
||||
t.Helper()
|
||||
pool := x509.NewCertPool()
|
||||
for _, c := range roots {
|
||||
pool.AddCert(c)
|
||||
}
|
||||
tr := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}, DisableKeepAlives: true}
|
||||
t.Cleanup(tr.CloseIdleConnections)
|
||||
return &http.Client{Timeout: 5 * time.Second, Transport: tr}
|
||||
}
|
||||
|
||||
func magpieCA(t *testing.T) *x509.Certificate {
|
||||
t.Helper()
|
||||
b, fp, err := CA()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
blk, _ := pem.Decode(b)
|
||||
if blk == nil {
|
||||
t.Fatalf("CA() isn't PEM: %q", b)
|
||||
}
|
||||
c, err := x509.ParseCertificate(blk.Bytes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fp != Fingerprint(c.Raw) || len(fp) != 32*3-1 {
|
||||
t.Fatalf("fingerprint %q", fp)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// zhangly1 on X: Claude on another computer on the LAN needed magpie at
|
||||
// https://. With HTTPS on, another computer is served TLS with a
|
||||
// certificate magpie's CA signs, which a client trusting that CA alone
|
||||
// verifies, plain http:// from it is refused, and the switch takes
|
||||
// effect at the next connection; off, it is plain http:// again.
|
||||
func TestHTTPSOtherComputer(t *testing.T) {
|
||||
key := mtlsHome(t, false)
|
||||
addr := serveMTLSGateway(t, true, "")
|
||||
if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err != nil || code != 200 {
|
||||
t.Fatalf("off: %d %q %v", code, body, err)
|
||||
}
|
||||
setHTTPS(t, true)
|
||||
if !TLSOn() || Scheme() != "https" {
|
||||
t.Fatalf("TLSOn %v, Scheme %q with HTTPS on", TLSOn(), Scheme())
|
||||
}
|
||||
c := trusting(t, magpieCA(t))
|
||||
for _, rt := range mtlsRoutes {
|
||||
code, body, err := mcall(t, c, rt[0], "https://"+addr+rt[1], key)
|
||||
if err != nil || code != 200 || body != "served "+rt[1] {
|
||||
t.Errorf("on, %s %s: %d %q %v", rt[0], rt[1], code, body, err)
|
||||
}
|
||||
}
|
||||
if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err == nil && code < 400 {
|
||||
t.Errorf("on, plain from another computer: %d %q, want it refused", code, body)
|
||||
}
|
||||
if _, _, err := mcall(t, trusting(t), "GET", "https://"+addr+"/v1/models", key); err == nil {
|
||||
t.Error("a client that doesn't trust magpie's CA verified its certificate")
|
||||
}
|
||||
info, err := ServedCert()
|
||||
if err != nil || info.From != "magpie" || info.Issuer == "" || !info.Until.After(time.Now()) {
|
||||
t.Errorf("ServedCert: %+v %v", info, err)
|
||||
}
|
||||
setHTTPS(t, false)
|
||||
if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err != nil || code != 200 {
|
||||
t.Fatalf("off again: %d %q %v", code, body, err)
|
||||
}
|
||||
}
|
||||
|
||||
// This computer's own agents keep plain http:// with HTTPS on.
|
||||
func TestHTTPSThisComputerPlain(t *testing.T) {
|
||||
key := mtlsHome(t, false)
|
||||
setHTTPS(t, true)
|
||||
addr := serveMTLSGateway(t, false, "")
|
||||
if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err != nil || code != 200 {
|
||||
t.Fatalf("this computer, plain: %d %q %v", code, body, err)
|
||||
}
|
||||
if code, body, err := mcall(t, trusting(t, magpieCA(t)), "GET", "https://"+addr+"/v1/models", key); err != nil || code != 200 {
|
||||
t.Fatalf("this computer, https: %d %q %v", code, body, err)
|
||||
}
|
||||
}
|
||||
|
||||
// testPKI is a CA of the test's own and a server certificate it signs
|
||||
// for 127.0.0.1, valid until notAfter.
|
||||
type testPKI struct {
|
||||
ca *x509.Certificate
|
||||
caPEM, cert, key []byte
|
||||
otherKey, encKey []byte
|
||||
expiredC, expiredK []byte
|
||||
}
|
||||
|
||||
func newTestPKI(t *testing.T) testPKI {
|
||||
t.Helper()
|
||||
var p testPKI
|
||||
caKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
caTpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "Test Root"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign}
|
||||
der, err := x509.CreateCertificate(rand.Reader, caTpl, caTpl, &caKey.PublicKey, caKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.ca, _ = x509.ParseCertificate(der)
|
||||
p.caPEM = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
leaf := func(serial int64, until time.Time) ([]byte, []byte) {
|
||||
k, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
tpl := &x509.Certificate{SerialNumber: big.NewInt(serial), Subject: pkix.Name{CommonName: "nas.home"}, DNSNames: []string{"nas.home"}, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, NotBefore: until.Add(-48 * time.Hour), NotAfter: until, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature}
|
||||
d, err := x509.CreateCertificate(rand.Reader, tpl, p.ca, &k.PublicKey, caKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kd, _ := x509.MarshalPKCS8PrivateKey(k)
|
||||
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: d}), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: kd})
|
||||
}
|
||||
p.cert, p.key = leaf(2, time.Now().Add(12*time.Hour))
|
||||
_, p.otherKey = leaf(3, time.Now().Add(12*time.Hour))
|
||||
p.expiredC, p.expiredK = leaf(4, time.Now().Add(-time.Hour))
|
||||
p.encKey = pem.EncodeToMemory(&pem.Block{Type: "ENCRYPTED PRIVATE KEY", Bytes: []byte{1, 2, 3}})
|
||||
return p
|
||||
}
|
||||
|
||||
// The user's own certificate and key, imported (a chain and a key apart,
|
||||
// in any order), are served instead of one magpie's CA signs; a pair
|
||||
// that can't be served is refused and leaves nothing behind; removed,
|
||||
// magpie's CA signs again.
|
||||
func TestHTTPSImportedCert(t *testing.T) {
|
||||
key := mtlsHome(t, false)
|
||||
setHTTPS(t, true)
|
||||
p := newTestPKI(t)
|
||||
for name, files := range map[string][][]byte{
|
||||
"no key": {p.cert},
|
||||
"no certificate": {p.key},
|
||||
"a stranger key": {p.cert, p.otherKey},
|
||||
"a passphrase": {p.cert, p.encKey},
|
||||
"run out": {p.expiredC, p.expiredK},
|
||||
"nothing in them": {[]byte("hello")},
|
||||
} {
|
||||
if err := ImportCert(files...); err == nil {
|
||||
t.Errorf("%s: imported", name)
|
||||
}
|
||||
if c, _ := ImportedFiles(); c != "" {
|
||||
t.Fatalf("%s: left %s behind", name, c)
|
||||
}
|
||||
}
|
||||
// the key first, the CA's certificate before the leaf: the leaf the
|
||||
// key belongs to goes first
|
||||
if err := ImportCert(p.key, append(append([]byte{}, p.caPEM...), p.cert...)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c, k := ImportedFiles(); c == "" || k == "" {
|
||||
t.Fatal("nothing kept")
|
||||
} else if fi, err := os.Stat(k); err == nil && fi.Mode().Perm()&0o077 != 0 && os.PathSeparator == '/' {
|
||||
t.Errorf("key.pem mode %v", fi.Mode().Perm())
|
||||
}
|
||||
addr := serveMTLSGateway(t, true, "")
|
||||
if code, body, err := mcall(t, trusting(t, p.ca), "GET", "https://"+addr+"/v1/models", key); err != nil || code != 200 {
|
||||
t.Fatalf("imported: %d %q %v", code, body, err)
|
||||
}
|
||||
if _, _, err := mcall(t, trusting(t, magpieCA(t)), "GET", "https://"+addr+"/v1/models", key); err == nil {
|
||||
t.Error("magpie's CA's certificate was served over the imported one")
|
||||
}
|
||||
if info, err := ServedCert(); err != nil || info.From != "imported" || info.Issuer != "Test Root" || !strings.Contains(strings.Join(info.Names, ","), "nas.home") {
|
||||
t.Errorf("ServedCert: %+v %v", info, err)
|
||||
}
|
||||
if err := RemoveImportedCert(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, body, err := mcall(t, trusting(t, magpieCA(t)), "GET", "https://"+addr+"/v1/models", key); err != nil || code != 200 {
|
||||
t.Fatalf("removed: %d %q %v", code, body, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Another computer fetches magpie's CA without a key, from an address
|
||||
// the share lets in, before it trusts magpie's https://; every other
|
||||
// route still asks for the key. With no CA made yet there is none.
|
||||
func TestHTTPSCAFile(t *testing.T) {
|
||||
mtlsHome(t, false)
|
||||
var s Server
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET "+CAPath, s.caFile)
|
||||
mux.HandleFunc("GET /v1/models", func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "models") })
|
||||
h := lanGuard(mux)
|
||||
get := func(path string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest("GET", path, nil)
|
||||
r.RemoteAddr = "192.168.1.9:5000"
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
w := get(CAPath)
|
||||
want, _, _ := CA()
|
||||
if w.Code != 200 || w.Body.String() != string(want) || w.Header().Get("Content-Type") != "application/x-x509-ca-cert" {
|
||||
t.Fatalf("CA: %d %q %q", w.Code, w.Header().Get("Content-Type"), w.Body.String())
|
||||
}
|
||||
if w := get("/v1/models"); w.Code != http.StatusUnauthorized && w.Code != http.StatusForbidden {
|
||||
t.Errorf("/v1/models without a key: %d", w.Code)
|
||||
}
|
||||
if w := get(CAPath + "x"); w.Code < 400 {
|
||||
t.Errorf("%sx without a key: %d", CAPath, w.Code)
|
||||
}
|
||||
if err := os.RemoveAll(filepath.Dir(MTLSStore().CAFile())); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := get(CAPath); w.Code != http.StatusNotFound {
|
||||
t.Errorf("no CA: %d", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -616,7 +616,9 @@ func lanGuard(next http.Handler) http.Handler {
|
||||
}
|
||||
// the key page itself is the same bytes for everyone, so it is
|
||||
// opened before the key it asks for is typed; its data isn't
|
||||
if remote && keyPageOpen(r) {
|
||||
// magpie's CA, too: public, and fetched before the computer
|
||||
// asking trusts magpie's https:// (https.go)
|
||||
if remote && (keyPageOpen(r) || caFileOpen(r)) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -135,12 +135,12 @@ type tlsServer struct {
|
||||
}
|
||||
|
||||
// config is the TLS config for a connection, nil to serve it plain HTTP
|
||||
// (no --tls-cert and mTLS off). strict asks for a client certificate and
|
||||
// (no --tls-cert, mTLS off and HTTPS off). strict asks for a client certificate and
|
||||
// ends a handshake without one, for a peer that isn't this computer or a
|
||||
// WSL distro.
|
||||
func (t *tlsServer) config(strict bool) *tls.Config {
|
||||
on := MTLSOn()
|
||||
if t == nil || (t.files == nil && !on) {
|
||||
if t == nil || (t.files == nil && !on && !HTTPSOn()) {
|
||||
return nil
|
||||
}
|
||||
cfg := &tls.Config{
|
||||
@@ -152,7 +152,7 @@ func (t *tlsServer) config(strict bool) *tls.Config {
|
||||
if t.files != nil {
|
||||
cfg.GetCertificate = t.files.get
|
||||
} else {
|
||||
cfg.GetCertificate = ownServerCert
|
||||
cfg.GetCertificate = settingsCert
|
||||
}
|
||||
if !on {
|
||||
return cfg
|
||||
@@ -249,7 +249,7 @@ func ownServerCert(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
}
|
||||
c, err := st.ServerCert(names, ips)
|
||||
if err != nil {
|
||||
return nil, errors.New("mTLS: magpie's CA can't sign a server certificate: " + err.Error())
|
||||
return nil, errors.New("TLS: magpie's CA can't sign a server certificate: " + err.Error())
|
||||
}
|
||||
ownCerts.key, ownCerts.stamp, ownCerts.made, ownCerts.cert = key.String(), stampOf(st.CAFile()), time.Now(), &c
|
||||
return &c, nil
|
||||
|
||||
@@ -40,10 +40,10 @@ func TLSFiles() (cert, key string) {
|
||||
}
|
||||
|
||||
// TLSOn: the gateway serves other computers over HTTPS: with the files
|
||||
// set, or with mTLS on (mtls.go).
|
||||
// set, with mTLS on (mtls.go), or with HTTPS on (https.go).
|
||||
func TLSOn() bool {
|
||||
c, k := TLSFiles()
|
||||
return c != "" && k != "" || MTLSOn()
|
||||
return c != "" && k != "" || MTLSOn() || HTTPSOn()
|
||||
}
|
||||
|
||||
// Scheme is the gateway's scheme for other computers: https with TLS on.
|
||||
@@ -109,7 +109,7 @@ func TLSSummary() string {
|
||||
c, err = tls.LoadX509KeyPair(cf, kf)
|
||||
} else {
|
||||
var own *tls.Certificate
|
||||
if own, err = ownServerCert(nil); own != nil {
|
||||
if own, err = settingsCert(nil); own != nil {
|
||||
c = *own
|
||||
}
|
||||
}
|
||||
@@ -288,7 +288,7 @@ func (l *tlsListener) accept() {
|
||||
switch {
|
||||
case cfg == nil:
|
||||
l.taken(c)
|
||||
case wsl && MTLSOn():
|
||||
case wsl && (MTLSOn() || HTTPSOn()):
|
||||
go l.sniff(c, cfg)
|
||||
default:
|
||||
l.taken(tls.Server(c, cfg))
|
||||
|
||||
@@ -1541,6 +1541,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
dataFolderRoutes(mux, w)
|
||||
mtlsRoutes(mux, w)
|
||||
joinRoutes(mux)
|
||||
httpsRoutes(mux, w)
|
||||
uninstallRoutes(mux, w)
|
||||
archiveRoutes(mux)
|
||||
libraryRoutes(mux, w)
|
||||
|
||||
@@ -4134,6 +4134,7 @@ input.words.remote-key { width: 160px; }
|
||||
.warm-at .warm-rm, .warm-at .warm-add { min-width: 24px; height: 27px; padding: 0 6px; font-size: 14px; line-height: 1; }
|
||||
.row.pref .sub .warn { color: var(--amber); }
|
||||
.row.pref .sub.wraps { white-space: normal; }
|
||||
.row.pref code.sub.https-cmd { display: block; font-size: 11px; user-select: text; -webkit-user-select: text; overflow-wrap: anywhere; }
|
||||
.row.pref .login-allow-open { font: inherit; color: var(--accent); padding: 0; background: none; border: 0; cursor: pointer; }
|
||||
.row.pref .login-allow-open:hover { text-decoration: underline; }
|
||||
/* the field's clock and picker in the page's own palette */
|
||||
|
||||
@@ -20043,6 +20043,7 @@ function renderSettings() {
|
||||
renderLAN(s);
|
||||
renderAllow(s);
|
||||
renderMTLS(s);
|
||||
renderHTTPS(s);
|
||||
renderCORS(s);
|
||||
renderSync();
|
||||
|
||||
|
||||
@@ -2749,6 +2749,19 @@ const I18N = {
|
||||
"Join link": "加入链接",
|
||||
"Use a password of at least 8 characters": "请使用至少 8 个字符的密码",
|
||||
"Use a password of at most 1024 bytes": "请使用不超过 1024 字节的密码",
|
||||
"Other computers call magpie at https://; this computer can still use http://": "其他电脑通过 https:// 访问 magpie;本机仍可用 http://",
|
||||
"Already served over https:// by Require a client certificate or --tls-cert": "已通过“要求客户端证书”或 --tls-cert 以 https:// 提供",
|
||||
"Your certificate": "你的证书",
|
||||
"Signed by magpie’s CA": "由 magpie 的 CA 签发",
|
||||
"magpie’s CA": "magpie 的 CA",
|
||||
"Trust it once on each computer that calls magpie · SHA-256 {fp}": "在每台访问 magpie 的电脑上信任一次 · SHA-256 {fp}",
|
||||
"This page is open from another computer: turn HTTPS on or off from the computer magpie runs on": "此页面是从其他电脑打开的:请在运行 magpie 的电脑上开关 HTTPS",
|
||||
"Claude Code and other Node apps": "Claude Code 等 Node 应用",
|
||||
"A certificate but no private key: choose the key’s file too": "有证书但没有私钥:请同时选择私钥文件",
|
||||
"A private key but no certificate: choose the certificate’s file too": "有私钥但没有证书:请同时选择证书文件",
|
||||
"The private key belongs to none of the certificates": "私钥与所选证书都不匹配",
|
||||
"The private key has a passphrase: choose one without": "私钥设有密码:请选择无密码的私钥",
|
||||
"No PEM certificate or key in the files chosen": "所选文件中没有 PEM 证书或私钥",
|
||||
"Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "其他电脑只能经 HTTPS、凭这里签发的证书连到 magpie,有网关密钥也不行;本机始终可以",
|
||||
"Client certificates": "客户端证书",
|
||||
"Saved to Downloads for the device: the certificate, its key and magpie’s CA": "为设备保存到「下载」:证书、私钥和 magpie 的 CA",
|
||||
@@ -7691,6 +7704,19 @@ const I18N = {
|
||||
"Join link": "加入連結",
|
||||
"Use a password of at least 8 characters": "請使用至少 8 個字元的密碼",
|
||||
"Use a password of at most 1024 bytes": "請使用不超過 1024 位元組的密碼",
|
||||
"Other computers call magpie at https://; this computer can still use http://": "其他電腦透過 https:// 存取 magpie;本機仍可用 http://",
|
||||
"Already served over https:// by Require a client certificate or --tls-cert": "已透過「要求用戶端憑證」或 --tls-cert 以 https:// 提供",
|
||||
"Your certificate": "你的憑證",
|
||||
"Signed by magpie’s CA": "由 magpie 的 CA 簽發",
|
||||
"magpie’s CA": "magpie 的 CA",
|
||||
"Trust it once on each computer that calls magpie · SHA-256 {fp}": "在每台存取 magpie 的電腦上信任一次 · SHA-256 {fp}",
|
||||
"This page is open from another computer: turn HTTPS on or off from the computer magpie runs on": "此頁面是從其他電腦開啟的:請在執行 magpie 的電腦上開關 HTTPS",
|
||||
"Claude Code and other Node apps": "Claude Code 等 Node 應用程式",
|
||||
"A certificate but no private key: choose the key’s file too": "有憑證但沒有私鑰:請同時選擇私鑰檔案",
|
||||
"A private key but no certificate: choose the certificate’s file too": "有私鑰但沒有憑證:請同時選擇憑證檔案",
|
||||
"The private key belongs to none of the certificates": "私鑰與所選憑證都不相符",
|
||||
"The private key has a passphrase: choose one without": "私鑰設有密碼:請選擇無密碼的私鑰",
|
||||
"No PEM certificate or key in the files chosen": "所選檔案中沒有 PEM 憑證或私鑰",
|
||||
"Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "其他電腦只能經 HTTPS、憑這裡簽發的憑證連到 magpie,有閘道金鑰也不行;本機始終可以",
|
||||
"Client certificates": "用戶端憑證",
|
||||
"Saved to Downloads for the device: the certificate, its key and magpie’s CA": "為裝置儲存到「下載」:憑證、私鑰和 magpie 的 CA",
|
||||
@@ -12611,6 +12637,19 @@ const I18N = {
|
||||
"Join link": "参加リンク",
|
||||
"Use a password of at least 8 characters": "8 文字以上のパスワードにしてください",
|
||||
"Use a password of at most 1024 bytes": "1024 バイト以下のパスワードにしてください",
|
||||
"Other computers call magpie at https://; this computer can still use http://": "他のコンピューターは https:// で magpie に接続します。このコンピューターは http:// も使えます",
|
||||
"Already served over https:// by Require a client certificate or --tls-cert": "「クライアント証明書を必須にする」または --tls-cert により https:// で提供中",
|
||||
"Your certificate": "独自の証明書",
|
||||
"Signed by magpie’s CA": "magpie の CA が署名",
|
||||
"magpie’s CA": "magpie の CA",
|
||||
"Trust it once on each computer that calls magpie · SHA-256 {fp}": "magpie に接続する各コンピューターで一度信頼してください · SHA-256 {fp}",
|
||||
"This page is open from another computer: turn HTTPS on or off from the computer magpie runs on": "このページは別のコンピューターから開かれています。HTTPS のオン・オフは magpie を実行しているコンピューターで行ってください",
|
||||
"Claude Code and other Node apps": "Claude Code などの Node アプリ",
|
||||
"A certificate but no private key: choose the key’s file too": "証明書はありますが秘密鍵がありません。秘密鍵のファイルも選んでください",
|
||||
"A private key but no certificate: choose the certificate’s file too": "秘密鍵はありますが証明書がありません。証明書のファイルも選んでください",
|
||||
"The private key belongs to none of the certificates": "秘密鍵がどの証明書とも一致しません",
|
||||
"The private key has a passphrase: choose one without": "秘密鍵にパスフレーズがあります。パスフレーズのないものを選んでください",
|
||||
"No PEM certificate or key in the files chosen": "選んだファイルに PEM の証明書も秘密鍵もありません",
|
||||
"Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "他のコンピューターは、ここで発行した証明書を持って HTTPS でのみ magpie に接続できます。ゲートウェイキーがあっても同じです。このコンピューターは常に接続できます",
|
||||
"Client certificates": "クライアント証明書",
|
||||
"Saved to Downloads for the device: the certificate, its key and magpie’s CA": "デバイス用に「ダウンロード」へ保存:証明書、その鍵、magpie の CA",
|
||||
@@ -17562,6 +17601,19 @@ const I18N = {
|
||||
"Join link": "Beitrittslink",
|
||||
"Use a password of at least 8 characters": "Verwenden Sie ein Passwort mit mindestens 8 Zeichen",
|
||||
"Use a password of at most 1024 bytes": "Verwenden Sie ein Passwort mit höchstens 1024 Bytes",
|
||||
"Other computers call magpie at https://; this computer can still use http://": "Andere Computer rufen magpie über https:// auf; dieser Computer kann weiter http:// nutzen",
|
||||
"Already served over https:// by Require a client certificate or --tls-cert": "Wird bereits über https:// bereitgestellt (Client-Zertifikat verlangen oder --tls-cert)",
|
||||
"Your certificate": "Eigenes Zertifikat",
|
||||
"Signed by magpie’s CA": "Von magpies CA signiert",
|
||||
"magpie’s CA": "magpies CA",
|
||||
"Trust it once on each computer that calls magpie · SHA-256 {fp}": "Einmal auf jedem Computer vertrauen, der magpie aufruft · SHA-256 {fp}",
|
||||
"This page is open from another computer: turn HTTPS on or off from the computer magpie runs on": "Diese Seite ist von einem anderen Computer geöffnet: HTTPS auf dem Computer ein- oder ausschalten, auf dem magpie läuft",
|
||||
"Claude Code and other Node apps": "Claude Code und andere Node-Apps",
|
||||
"A certificate but no private key: choose the key’s file too": "Ein Zertifikat, aber kein privater Schlüssel: auch die Schlüsseldatei wählen",
|
||||
"A private key but no certificate: choose the certificate’s file too": "Ein privater Schlüssel, aber kein Zertifikat: auch die Zertifikatsdatei wählen",
|
||||
"The private key belongs to none of the certificates": "Der private Schlüssel gehört zu keinem der Zertifikate",
|
||||
"The private key has a passphrase: choose one without": "Der private Schlüssel hat eine Passphrase: einen ohne wählen",
|
||||
"No PEM certificate or key in the files chosen": "Keine PEM-Zertifikate oder -Schlüssel in den gewählten Dateien",
|
||||
"Other computers reach magpie over HTTPS only with a certificate issued here, even with a gateway key; this computer always can": "Andere Computer erreichen magpie nur über HTTPS mit einem hier ausgestellten Zertifikat, auch mit Gateway-Schlüssel; dieser Computer immer",
|
||||
"Client certificates": "Client-Zertifikate",
|
||||
"Saved to Downloads for the device: the certificate, its key and magpie’s CA": "Für das Gerät in „Downloads“ gespeichert: das Zertifikat, sein Schlüssel und magpies CA",
|
||||
|
||||
@@ -362,6 +362,7 @@
|
||||
<div class="list prefs" id="lanList"></div>
|
||||
<div class="list prefs" id="allowList"></div>
|
||||
<div class="list prefs" id="mtlsList"></div>
|
||||
<div class="list prefs" id="httpsList"></div>
|
||||
<div class="row-head"><span class="label" data-t>Web pages</span></div>
|
||||
<div class="list prefs" id="corsList"></div>
|
||||
<div class="row-head" id="webPageHead"><span class="label" data-t>Browser access</span></div>
|
||||
|
||||
@@ -346,6 +346,106 @@ function renderMTLS(s) {
|
||||
}
|
||||
}
|
||||
|
||||
// renderHTTPS: HTTPS for other computers (zhangly1 on X: Claude on another
|
||||
// computer on the LAN needed magpie at https://), under Share on local
|
||||
// network. On, other computers get the certificate imported here, or one
|
||||
// magpie's own CA signs; then the CA's row saves it to Downloads, and the
|
||||
// rows under it say how another computer fetches and trusts it. Asked of
|
||||
// its own route (https.go), as Browser access is; drawn while magpie
|
||||
// answers other computers or the switch is on.
|
||||
let httpsState = null;
|
||||
function httpsSays(m) {
|
||||
if (/^this page is open from another computer/.test(m)) return t("This page is open from another computer: turn HTTPS on or off from the computer magpie runs on");
|
||||
if (/^a certificate but no private key/.test(m)) return t("A certificate but no private key: choose the key’s file too");
|
||||
if (/^a private key but no certificate/.test(m)) return t("A private key but no certificate: choose the certificate’s file too");
|
||||
if (/^the private key belongs to none/.test(m)) return t("The private key belongs to none of the certificates");
|
||||
if (/^the private key has a passphrase/.test(m)) return t("The private key has a passphrase: choose one without");
|
||||
if (/^no PEM certificate or key/.test(m)) return t("No PEM certificate or key in the files chosen");
|
||||
return t(m);
|
||||
}
|
||||
function renderHTTPS(s, asked) {
|
||||
const box = $("#httpsList");
|
||||
if (!box) return;
|
||||
if (!asked) api("settings/https").then((h) => { httpsState = h; renderHTTPS(prefs, true); }).catch(() => {});
|
||||
const h = httpsState;
|
||||
if (!s || !h || (!s.lan && !s.onNetwork && !h.on)) return void box.replaceChildren();
|
||||
const post = (what, body) => writingPrefs(api("settings/https" + what, body))
|
||||
.then((nh) => {
|
||||
httpsState = nh; renderHTTPS(prefs, true);
|
||||
if (nh.saved) status(t("Saved to {path}", { path: nh.saved }), "ok", 4000);
|
||||
})
|
||||
.catch((e) => { status(httpsSays(e.message), "err"); renderHTTPS(prefs, true); });
|
||||
const rows = [];
|
||||
const row = (cls, name, sub, ...tools) => {
|
||||
const r = el("div", "row pref " + cls);
|
||||
const who = el("div", "who");
|
||||
who.append(el("div", "name", name));
|
||||
if (sub) who.append(sub instanceof Node ? sub : el("div", "sub", sub));
|
||||
const val = el("div", "val");
|
||||
val.append(...tools);
|
||||
r.append(who, val);
|
||||
rows.push(r);
|
||||
return r;
|
||||
};
|
||||
row("https-row", "HTTPS",
|
||||
h.served && !h.on ? t("Already served over https:// by Require a client certificate or --tls-cert") : t("Other computers call magpie at https://; this computer can still use http://"),
|
||||
segs([["off", t("Off")], ["on", t("On")]], h.on ? "on" : "off", (v) => post("", { on: v === "on" })));
|
||||
if (h.served) {
|
||||
const c = h.cert;
|
||||
const until = c && new Date(c.until).toLocaleDateString(intlLang(), { year: "numeric", month: "short", day: "numeric" });
|
||||
const from = !c ? "" : c.from === "files" ? "--tls-cert " + c.file : c.from === "imported" ? t("Your certificate") : t("Signed by magpie’s CA");
|
||||
const sub = h.certError ? el("div", "sub err", t(h.certError))
|
||||
: el("div", "sub", [from, (c.names || []).join(", "), t("Until {date}", { date: until })].filter(Boolean).join(" · "));
|
||||
sub.title = sub.textContent;
|
||||
const tools = [];
|
||||
if (!h.files) {
|
||||
const file = el("input");
|
||||
file.type = "file";
|
||||
file.multiple = true;
|
||||
file.accept = ".pem,.crt,.cer,.key,application/x-pem-file,application/x-x509-ca-cert";
|
||||
file.hidden = true;
|
||||
file.onchange = async () => {
|
||||
const files = await Promise.all([...file.files].map((f) => f.text()));
|
||||
file.value = "";
|
||||
if (files.length) post("/import", { files });
|
||||
};
|
||||
const pick = el("button", "text", t("Import…"));
|
||||
pick.type = "button";
|
||||
pick.onclick = () => file.click();
|
||||
tools.push(file, pick);
|
||||
if (c?.from === "imported") {
|
||||
const x = el("button", "text", t("Remove"));
|
||||
x.type = "button";
|
||||
x.onclick = () => post("/remove", {});
|
||||
tools.push(x);
|
||||
}
|
||||
}
|
||||
row("https-cert", t("Certificate"), sub, ...tools);
|
||||
}
|
||||
if (h.ca) {
|
||||
const save = el("button", "text", t("Save"));
|
||||
save.type = "button";
|
||||
save.onclick = () => post("/ca", {});
|
||||
const sub = el("div", "sub wraps", t("Trust it once on each computer that calls magpie · SHA-256 {fp}", { fp: h.ca }));
|
||||
row("https-ca", t("magpie’s CA"), sub, save);
|
||||
// the address picked under Share on local network, else the first
|
||||
const at = (h.caURLs || []).find((u) => u.startsWith(lanSelectedURL + "/")) || h.caURLs?.[0];
|
||||
const steps = [
|
||||
at && [t("Download"), "curl -kO " + at],
|
||||
["macOS", "sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain magpie-ca.crt"],
|
||||
["Windows", "certutil -addstore -f Root magpie-ca.crt"],
|
||||
["Linux", "sudo cp magpie-ca.crt /usr/local/share/ca-certificates/ && sudo update-ca-certificates"],
|
||||
[t("Claude Code and other Node apps"), "NODE_EXTRA_CA_CERTS=/path/to/magpie-ca.crt"],
|
||||
];
|
||||
for (const [name, cmd] of steps.filter(Boolean)) {
|
||||
const code = el("code", "sub https-cmd", cmd);
|
||||
code.title = cmd;
|
||||
row("https-step", name, code, copyBtn(cmd, name, t("Copied")));
|
||||
}
|
||||
}
|
||||
box.replaceChildren(...rows);
|
||||
}
|
||||
|
||||
// renderLAN: the gateway shared on the local network, for agents on other
|
||||
// machines. Gateway keys and connection examples live together in Gateway.
|
||||
let lanSelectedURL = "", lanProtocol = "openai";
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/mtls"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// httpsState is Settings → Network and sharing's HTTPS rows (zhangly1 on
|
||||
// X: Claude on another computer on the LAN needed magpie at https://).
|
||||
type httpsState struct {
|
||||
On bool `json:"on"`
|
||||
// Served: other computers are served https:// now, by this switch,
|
||||
// --tls-cert (Files) or mTLS
|
||||
Served bool `json:"served"`
|
||||
Files bool `json:"files,omitempty"`
|
||||
MTLS bool `json:"mtls,omitempty"`
|
||||
// Cert: the certificate served, while Served
|
||||
Cert *gateway.CertInfo `json:"cert,omitempty"`
|
||||
CertErr string `json:"certError,omitempty"`
|
||||
// CA: magpie's CA's SHA-256 while it signs the certificate served,
|
||||
// and CAURLs where other computers download it
|
||||
CA string `json:"ca,omitempty"`
|
||||
CAURLs []string `json:"caURLs,omitempty"`
|
||||
// Saved: where the CA was just saved
|
||||
Saved string `json:"saved,omitempty"`
|
||||
}
|
||||
|
||||
func httpsNow() httpsState {
|
||||
s := httpsState{On: gateway.HTTPSOn(), Served: gateway.TLSOn(), MTLS: gateway.MTLSOn()}
|
||||
c, k := gateway.TLSFiles()
|
||||
s.Files = c != "" && k != ""
|
||||
if !s.Served {
|
||||
return s
|
||||
}
|
||||
info, err := gateway.ServedCert()
|
||||
if err != nil {
|
||||
s.CertErr = err.Error()
|
||||
return s
|
||||
}
|
||||
s.Cert = &info
|
||||
if info.From == "magpie" {
|
||||
if _, fp, err := gateway.CA(); err == nil {
|
||||
s.CA = fp
|
||||
}
|
||||
for _, u := range gateway.LANURLs() {
|
||||
s.CAURLs = append(s.CAURLs, u+gateway.CAPath)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
var errFarPage = errors.New("this page is open from another computer, and HTTPS changes how it is reached: turn it on or off from the computer magpie runs on")
|
||||
|
||||
func httpsRoutes(mux *http.ServeMux, w Windows) {
|
||||
mux.HandleFunc("GET /api/settings/https", func(rw http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(rw, httpsNow())
|
||||
})
|
||||
// on or off: on makes magpie's CA first, unless a certificate was
|
||||
// imported. A page open from another computer can't flip it under
|
||||
// itself: its next request would come in the other scheme.
|
||||
mux.HandleFunc("POST /api/settings/https", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ On bool }
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
if isWeb(w) && !gateway.FromThisComputer(r) && in.On != gateway.HTTPSOn() {
|
||||
fail(rw, errFarPage)
|
||||
return
|
||||
}
|
||||
if in.On {
|
||||
if c, _ := gateway.ImportedFiles(); c == "" {
|
||||
if _, _, err := gateway.CA(); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := settings.SetHTTPS(in.On); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, httpsNow())
|
||||
})
|
||||
// the user's own certificate and key: the PEM files' text, any split
|
||||
mux.HandleFunc("POST /api/settings/https/import", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Files []string }
|
||||
if err := json.NewDecoder(http.MaxBytesReader(rw, r.Body, 1<<20)).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
files := make([][]byte, len(in.Files))
|
||||
for i, f := range in.Files {
|
||||
files[i] = []byte(f)
|
||||
}
|
||||
if err := gateway.ImportCert(files...); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, httpsNow())
|
||||
})
|
||||
mux.HandleFunc("POST /api/settings/https/remove", func(rw http.ResponseWriter, r *http.Request) {
|
||||
if err := gateway.RemoveImportedCert(); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, httpsNow())
|
||||
})
|
||||
// magpie's CA, saved to Downloads as magpie-ca.crt for another computer
|
||||
mux.HandleFunc("POST /api/settings/https/ca", func(rw http.ResponseWriter, r *http.Request) {
|
||||
b, _, err := gateway.CA()
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
p := filepath.Join(downloads(), "magpie-ca.crt")
|
||||
if err := mtls.WriteFile(p, b, 0o644); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
_ = w.OpenFolder(filepath.Dir(p))
|
||||
s := httpsNow()
|
||||
s.Saved = tilde(p)
|
||||
writeJSON(rw, s)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// webTab is the page served to a browser (magpie web).
|
||||
type webTab struct{ folderOnly }
|
||||
|
||||
func (webTab) browserTab() {}
|
||||
|
||||
func httpsMux(t *testing.T, w Windows) func(method, path, body, from string) (int, httpsState, string) {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
httpsRoutes(mux, w)
|
||||
return func(method, path, body, from string) (int, httpsState, string) {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if from != "" {
|
||||
r.RemoteAddr = from
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, r)
|
||||
var s httpsState
|
||||
json.Unmarshal(rec.Body.Bytes(), &s)
|
||||
return rec.Code, s, rec.Body.String()
|
||||
}
|
||||
}
|
||||
|
||||
// Settings → Network and sharing → HTTPS (zhangly1 on X): on makes
|
||||
// magpie's CA and serves a certificate it signs, its fingerprint shown;
|
||||
// Save puts magpie-ca.crt in Downloads; off goes back to plain http://.
|
||||
func TestSettingsHTTPSOnSaveOff(t *testing.T) {
|
||||
h := sandboxHome(t)
|
||||
t.Setenv("MAGPIE_ADDR", "0.0.0.0:3499")
|
||||
t.Setenv(gateway.TLSCertEnv, "")
|
||||
t.Setenv(gateway.TLSKeyEnv, "")
|
||||
os.MkdirAll(filepath.Join(h, "Downloads"), 0o755)
|
||||
call := httpsMux(t, folderOnly{})
|
||||
|
||||
if code, s, out := call("GET", "/api/settings/https", "", ""); code != 200 || s.On || s.Served {
|
||||
t.Fatalf("at first: %d %s", code, out)
|
||||
}
|
||||
code, s, out := call("POST", "/api/settings/https", `{"on":true}`, "")
|
||||
if code != 200 || !s.On || !s.Served || !settings.Shared().HTTPS || s.Cert == nil || s.Cert.From != "magpie" || s.CA == "" {
|
||||
t.Fatalf("on: %d %s", code, out)
|
||||
}
|
||||
for _, u := range s.CAURLs {
|
||||
if !strings.HasPrefix(u, "https://") || !strings.HasSuffix(u, gateway.CAPath) {
|
||||
t.Errorf("CA's address %q", u)
|
||||
}
|
||||
}
|
||||
code, s, out = call("POST", "/api/settings/https/ca", `{}`, "")
|
||||
if code != 200 || s.Saved == "" {
|
||||
t.Fatalf("save: %d %s", code, out)
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(h, "Downloads", "magpie-ca.crt"))
|
||||
want, fp, _ := gateway.CA()
|
||||
if err != nil || string(b) != string(want) || fp != s.CA {
|
||||
t.Fatalf("saved CA: %v %q", err, b)
|
||||
}
|
||||
code, s, out = call("POST", "/api/settings/https", `{"on":false}`, "")
|
||||
if code != 200 || s.On || s.Served || settings.Shared().HTTPS {
|
||||
t.Fatalf("off: %d %s", code, out)
|
||||
}
|
||||
}
|
||||
|
||||
// A page open in a browser on another computer can't turn HTTPS on or
|
||||
// off under itself; one on this computer can, and the app's window can.
|
||||
func TestSettingsHTTPSFarPage(t *testing.T) {
|
||||
sandboxHome(t)
|
||||
t.Setenv("MAGPIE_ADDR", "0.0.0.0:3499")
|
||||
call := httpsMux(t, webTab{})
|
||||
if code, _, out := call("POST", "/api/settings/https", `{"on":true}`, "192.168.1.9:5000"); code < 400 || settings.Shared().HTTPS {
|
||||
t.Fatalf("far page turned it on: %d %s", code, out)
|
||||
}
|
||||
if code, s, out := call("POST", "/api/settings/https", `{"on":true}`, "127.0.0.1:5000"); code != 200 || !s.On {
|
||||
t.Fatalf("this computer's page: %d %s", code, out)
|
||||
}
|
||||
// the same value again changes nothing, and is answered
|
||||
if code, s, out := call("POST", "/api/settings/https", `{"on":true}`, "192.168.1.9:5000"); code != 200 || !s.On {
|
||||
t.Fatalf("far page, unchanged: %d %s", code, out)
|
||||
}
|
||||
}
|
||||
|
||||
// An import that doesn't parse is refused with the reason, and nothing is
|
||||
// kept.
|
||||
func TestSettingsHTTPSImportRefused(t *testing.T) {
|
||||
sandboxHome(t)
|
||||
call := httpsMux(t, folderOnly{})
|
||||
code, _, out := call("POST", "/api/settings/https/import", `{"files":["not a certificate"]}`, "")
|
||||
if code < 400 || !strings.Contains(out, "no PEM certificate or key") {
|
||||
t.Fatalf("import: %d %s", code, out)
|
||||
}
|
||||
if c, _ := gateway.ImportedFiles(); c != "" {
|
||||
t.Fatalf("kept %s", c)
|
||||
}
|
||||
}
|
||||
@@ -217,6 +217,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
|
||||
was.RouterAllTools = true // the Library's servers/hub-tools
|
||||
was.BusyLoad = 150 // the Routing page's busy-load
|
||||
was.MTLS = true // Network and sharing's settings/mtls
|
||||
was.HTTPS = true // Network and sharing's settings/https
|
||||
// the Routing groups page's defaults for every group (groups/defaults)
|
||||
was.GroupSink, was.GroupFirstToken, was.GroupPatience = true, 30, 120
|
||||
if err := settings.Save(was); err != nil {
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// HTTPS for other computers (zhangly1 on X: Claude on another computer on
|
||||
// the LAN needed magpie at https://): Settings › Network, under Require a
|
||||
// client certificate, turns HTTPS on; the Certificate row says which is
|
||||
// served and imports the user's own PEM files (or removes them); magpie's
|
||||
// CA row shows its SHA-256 and saves it to Downloads, the path said; the
|
||||
// rows under it give the download and each system's trust command with a
|
||||
// Copy button. A refused import or a far page's switch is told in the
|
||||
// page's language. Hidden while magpie answers only this computer.
|
||||
// English and Chinese, Chromium and WebKit, 390px; the strings in all
|
||||
// four languages; no backend, the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
const { watchSettingsReads, settingsDrawn, reach } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const file = async (route, url) => {
|
||||
const f = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(f)];
|
||||
await route.fulfill({ body: await fs.readFile(f), contentType });
|
||||
};
|
||||
const boot = (route, lang) => route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
|
||||
const FP = Array.from({ length: 32 }, (_, i) => (i * 7 + 16).toString(16).toUpperCase().padStart(2, "0")).join(":");
|
||||
const FAR = "this page is open from another computer, and HTTPS changes how it is reached: turn it on or off from the computer magpie runs on";
|
||||
const NOKEY = "a certificate but no private key: give the key's file too";
|
||||
|
||||
function server(lang, posts, over = {}) {
|
||||
const s = {
|
||||
theme: "light", lang, tray: "panel", currency: "usd", version: "0.1.400", dir: "/config/magpie",
|
||||
gateway: "http://127.0.0.1:3425", proxyNow: "none", proxySource: "none", login: false,
|
||||
visionModels: [], imageGenModels: [], allowIPs: [],
|
||||
lan: true, lanURLs: ["http://192.168.1.20:3425"], mtls: false, mtlsCerts: [],
|
||||
fx: { rate: 7.2, at: new Date().toISOString(), stale: false }, ...over.settings,
|
||||
};
|
||||
let h = { on: false, served: false };
|
||||
const served = (from) => ({
|
||||
on: true, served: true,
|
||||
cert: { from, names: from === "magpie" ? ["mac.local", "192.168.1.20"] : ["nas.home"], issuer: from === "magpie" ? "magpie CA" : "Test Root", until: "2027-11-10T00:00:00Z" },
|
||||
...(from === "magpie" ? { ca: FP, caURLs: ["https://192.168.1.20:3425/magpie-ca.crt"] } : {}),
|
||||
});
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data, status = 200) => route.fulfill({ json: data, status });
|
||||
if (url.pathname === "/boot.js") return boot(route, lang);
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: s.fx });
|
||||
if (url.pathname === "/api/settings") return json(s);
|
||||
if (url.pathname === "/api/settings/https" && route.request().method() === "GET") return json(h);
|
||||
if (url.pathname.startsWith("/api/settings/https")) {
|
||||
const body = route.request().postDataJSON();
|
||||
posts.push({ path: url.pathname, body });
|
||||
if (url.pathname === "/api/settings/https") {
|
||||
if (over.farPage) return json({ error: FAR }, 400);
|
||||
h = body.on ? served("magpie") : { on: false, served: false };
|
||||
} else if (url.pathname.endsWith("/import")) {
|
||||
if (body.files.length < 2) return json({ error: NOKEY }, 400);
|
||||
h = served("imported");
|
||||
} else if (url.pathname.endsWith("/remove")) {
|
||||
h = served("magpie");
|
||||
} else if (url.pathname.endsWith("/ca")) {
|
||||
return json({ ...h, saved: "~/Downloads/magpie-ca.crt" });
|
||||
}
|
||||
return json(h);
|
||||
}
|
||||
if (url.pathname === "/api/copy") { posts.push({ path: url.pathname, body: route.request().postDataJSON() }); return json({}); }
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
await file(route, url);
|
||||
};
|
||||
}
|
||||
|
||||
const en = {
|
||||
sub: "Other computers call magpie at https://; this computer can still use http://",
|
||||
mine: "Your certificate",
|
||||
signed: "Signed by magpie’s CA",
|
||||
ca: "magpie’s CA",
|
||||
node: "Claude Code and other Node apps",
|
||||
far: "This page is open from another computer: turn HTTPS on or off from the computer magpie runs on",
|
||||
nokey: "A certificate but no private key: choose the key’s file too",
|
||||
};
|
||||
const zh = { sub: "其他电脑通过 https:// 访问 magpie;本机仍可用 http://", ca: "magpie 的 CA" };
|
||||
const others = [
|
||||
"Already served over https:// by Require a client certificate or --tls-cert",
|
||||
"Trust it once on each computer that calls magpie · SHA-256 {fp}",
|
||||
"A private key but no certificate: choose the certificate’s file too",
|
||||
"The private key belongs to none of the certificates",
|
||||
"The private key has a passphrase: choose one without",
|
||||
"No PEM certificate or key in the files chosen",
|
||||
];
|
||||
|
||||
async function open(browser, lang, posts, over) {
|
||||
const page = await (await browser.newContext({ viewport: { width: 390, height: 640 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, posts, over));
|
||||
await watchSettingsReads(page);
|
||||
await page.goto("http://127.0.0.1:4999/?view=settings&tab=network");
|
||||
await settingsDrawn(page);
|
||||
return { page, errors };
|
||||
}
|
||||
|
||||
async function fits(box) {
|
||||
const bad = await box.evaluate((b) => {
|
||||
const out = [];
|
||||
const right = b.getBoundingClientRect().right + 0.5;
|
||||
for (const e of b.querySelectorAll(".row, button, .name, code")) {
|
||||
const r = e.getBoundingClientRect();
|
||||
if (r.right > right || r.width === 0) out.push(e.className + " " + r.right + ">" + right);
|
||||
if (e.matches("button, .name") && e.scrollWidth > e.clientWidth + 1) out.push("cut: " + e.textContent);
|
||||
}
|
||||
if (document.documentElement.scrollWidth > innerWidth) out.push("page scrolls sideways");
|
||||
return out;
|
||||
});
|
||||
assert.deepEqual(bad, []);
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": HTTPS in Settings (zhangly1 on X)", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
|
||||
await t.test("every language has the strings", async () => {
|
||||
const { page } = await open(browser, "en", []);
|
||||
for (const lang of ["zh", "zh-TW", "ja", "de"]) {
|
||||
const missing = await page.evaluate(([lang, keys]) => keys.filter((k) => !I18N[lang]?.[k] || I18N[lang][k] === k),
|
||||
[lang, [...Object.values(en), ...others]]);
|
||||
assert.deepEqual(missing, [], lang);
|
||||
}
|
||||
await page.context().close();
|
||||
});
|
||||
|
||||
await t.test("hidden while magpie answers only this computer", async () => {
|
||||
const { page, errors } = await open(browser, "en", [], { settings: { lan: false, lanURLs: [] } });
|
||||
await page.locator("#lanList .row").first().waitFor();
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await page.locator("#httpsList .row").count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
await page.context().close();
|
||||
});
|
||||
|
||||
for (const lang of ["en", "zh"]) {
|
||||
await t.test(lang + ": on, the CA and its steps, import, remove, off", async () => {
|
||||
const posts = [];
|
||||
const { page, errors } = await open(browser, lang, posts);
|
||||
const w = {};
|
||||
for (const [k, s] of Object.entries(en)) {
|
||||
w[k] = await page.evaluate((s) => t(s), s);
|
||||
if (lang !== "en") assert.notEqual(w[k], s, `"${s}" has no ${lang} translation`);
|
||||
if (lang === "zh" && zh[k]) assert.equal(w[k], zh[k]);
|
||||
}
|
||||
const box = page.locator("#httpsList");
|
||||
const toggle = box.locator(".https-row");
|
||||
await toggle.waitFor();
|
||||
assert.equal((await toggle.locator(".name").textContent()).trim(), "HTTPS");
|
||||
assert.equal((await toggle.locator(".sub").textContent()).trim(), w.sub);
|
||||
assert.equal(await box.locator(".https-cert").count(), 0, "no certificate row while off");
|
||||
await fits(box);
|
||||
|
||||
const on = toggle.locator("button.opt").last();
|
||||
await reach(page, on);
|
||||
await on.click();
|
||||
await box.locator(".https-ca").waitFor();
|
||||
assert.deepEqual(posts.at(-1), { path: "/api/settings/https", body: { on: true } });
|
||||
const certSub = (await box.locator(".https-cert .sub").textContent()).trim();
|
||||
assert.ok(certSub.startsWith(w.signed + " · mac.local, 192.168.1.20 · "), certSub);
|
||||
assert.ok((await box.locator(".https-ca .sub").textContent()).includes("SHA-256 " + FP));
|
||||
const steps = await box.locator(".https-step").evaluateAll((rs) => rs.map((r) => [r.querySelector(".name").textContent, r.querySelector("code").textContent]));
|
||||
assert.deepEqual(steps.map((s) => s[0]).slice(1), ["macOS", "Windows", "Linux", w.node]);
|
||||
assert.equal(steps[0][1], "curl -kO https://192.168.1.20:3425/magpie-ca.crt");
|
||||
assert.match(steps[1][1], /add-trusted-cert .* magpie-ca\.crt$/);
|
||||
assert.equal(steps[2][1], "certutil -addstore -f Root magpie-ca.crt");
|
||||
await fits(box);
|
||||
|
||||
// Copy sends the command itself
|
||||
const copy = box.locator(".https-step").nth(2).locator("button.copy");
|
||||
await reach(page, copy);
|
||||
await copy.click();
|
||||
await page.waitForFunction(() => document.querySelector("#status")?.textContent);
|
||||
assert.deepEqual(posts.at(-1), { path: "/api/copy", body: { text: "certutil -addstore -f Root magpie-ca.crt" } });
|
||||
|
||||
const save = box.locator(".https-ca button");
|
||||
await reach(page, save);
|
||||
await save.click();
|
||||
const savedSays = await page.evaluate(() => t("Saved to {path}", { path: "~/Downloads/magpie-ca.crt" }));
|
||||
await page.waitForFunction((s) => document.querySelector("#status")?.textContent.includes(s), savedSays);
|
||||
assert.deepEqual(posts.at(-1), { path: "/api/settings/https/ca", body: {} });
|
||||
|
||||
// a certificate without its key is refused, in the page's language
|
||||
const input = box.locator(".https-cert input[type=file]");
|
||||
await input.setInputFiles([{ name: "cert.pem", mimeType: "application/x-pem-file", buffer: Buffer.from("-----BEGIN CERTIFICATE-----\nAA==\n-----END CERTIFICATE-----\n") }]);
|
||||
await page.waitForFunction((s) => document.querySelector("#status")?.textContent.includes(s), w.nokey);
|
||||
assert.equal(posts.at(-1).path, "/api/settings/https/import");
|
||||
await input.setInputFiles([
|
||||
{ name: "cert.pem", mimeType: "application/x-pem-file", buffer: Buffer.from("CERT") },
|
||||
{ name: "key.pem", mimeType: "application/x-pem-file", buffer: Buffer.from("KEY") },
|
||||
]);
|
||||
await box.locator(".https-cert .sub", { hasText: w.mine }).waitFor();
|
||||
assert.deepEqual(posts.at(-1), { path: "/api/settings/https/import", body: { files: ["CERT", "KEY"] } });
|
||||
assert.equal(await box.locator(".https-ca").count(), 0, "no CA row with the user's own certificate");
|
||||
const remove = box.locator(".https-cert button").last();
|
||||
await reach(page, remove);
|
||||
await remove.click();
|
||||
await box.locator(".https-ca").waitFor();
|
||||
assert.deepEqual(posts.at(-1), { path: "/api/settings/https/remove", body: {} });
|
||||
|
||||
const off = box.locator(".https-row button.opt").first();
|
||||
await reach(page, off);
|
||||
await off.click();
|
||||
await page.waitForFunction(() => !document.querySelector("#httpsList .https-cert"));
|
||||
assert.deepEqual(posts.at(-1), { path: "/api/settings/https", body: { on: false } });
|
||||
const border = await box.locator(".row").first().evaluate((r) => getComputedStyle(r).borderLeftWidth);
|
||||
assert(border === "0px" || border === "", "no left border accent: " + border);
|
||||
assert.equal(await box.locator("select").count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
await page.context().close();
|
||||
});
|
||||
}
|
||||
|
||||
await t.test("a page on another computer is told why it can't, in its language", async () => {
|
||||
const posts = [];
|
||||
const { page, errors } = await open(browser, "zh", posts, { farPage: true });
|
||||
const toggle = page.locator("#httpsList .https-row");
|
||||
await toggle.waitFor();
|
||||
const on = toggle.locator("button.opt").last();
|
||||
await reach(page, on);
|
||||
await on.click();
|
||||
const says = await page.evaluate((s) => t(s), en.far);
|
||||
assert.notEqual(says, en.far);
|
||||
await page.waitForFunction((s) => document.querySelector("#status")?.textContent.includes(s), says);
|
||||
await page.waitForFunction(() => document.querySelector("#httpsList .https-row .opt")?.classList.contains("on"));
|
||||
assert.deepEqual(errors, []);
|
||||
await page.context().close();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -431,6 +431,9 @@ func pemOf(typ string, der []byte) []byte {
|
||||
return pem.EncodeToMemory(&pem.Block{Type: typ, Bytes: der})
|
||||
}
|
||||
|
||||
// WriteFile is writeFile, for the certificate Settings imports.
|
||||
func WriteFile(path string, b []byte, mode os.FileMode) error { return writeFile(path, b, mode) }
|
||||
|
||||
// writeFile writes b to path through a temp file renamed over it, so a
|
||||
// reader never sees half of one.
|
||||
func writeFile(path string, b []byte, mode os.FileMode) error {
|
||||
|
||||
@@ -236,6 +236,13 @@ type Settings struct {
|
||||
// without a good certificate is refused. This computer's own
|
||||
// (KeepOwn), as LAN is.
|
||||
MTLS bool `json:"mtls,omitempty"`
|
||||
// HTTPS serves the gateway and magpie web's page to other computers
|
||||
// over https:// (zhangly1 on X: Claude on another computer on the LAN
|
||||
// needed https), with the certificate imported in Settings (kept in
|
||||
// <dir>/https) or else one magpie's own CA signs for this computer's
|
||||
// names and addresses (gateway.ServedCert). This computer may still
|
||||
// call plain http://. This computer's own (KeepOwn), as LAN is.
|
||||
HTTPS bool `json:"https,omitempty"`
|
||||
// FetchPrivate are the private hosts and ranges (a name, name:port, an
|
||||
// IP or a CIDR range) magpie may download a URL from that it didn't
|
||||
// choose itself: an image or video a request names or a vendor answers
|
||||
@@ -1529,7 +1536,7 @@ func (s *Settings) KeepOwn(cur Settings) {
|
||||
s.NoWSLAgents = cur.NoWSLAgents
|
||||
s.QuotaReads = cur.QuotaReads
|
||||
s.NoAccountDiscovery = cur.NoAccountDiscovery
|
||||
s.LAN, s.AllowIPs, s.MTLS = cur.LAN, cur.AllowIPs, cur.MTLS
|
||||
s.LAN, s.AllowIPs, s.MTLS, s.HTTPS = cur.LAN, cur.AllowIPs, cur.MTLS, cur.HTTPS
|
||||
s.RouterNote, s.RouterAllTools = cur.RouterNote, cur.RouterAllTools
|
||||
s.FetchPrivate = cur.FetchPrivate
|
||||
s.SessionTerminal = cur.SessionTerminal
|
||||
@@ -2032,6 +2039,18 @@ func SetMTLS(on bool) error {
|
||||
return save(s, false)
|
||||
}
|
||||
|
||||
// SetHTTPS sets HTTPS alone, from what the file holds now. A settings
|
||||
// file that can't be read is left as it is, with the error.
|
||||
func SetHTTPS(on bool) error {
|
||||
defer lockFile()()
|
||||
s, err := loadChecked()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.HTTPS = on
|
||||
return save(s, false)
|
||||
}
|
||||
|
||||
// SetQuitNoAsk sets QuitNoAsk alone, from what the file holds now (the
|
||||
// Quit question's "Don't ask again"). A settings file that can't be read
|
||||
// is left as it is, with the error.
|
||||
|
||||
@@ -287,6 +287,7 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err
|
||||
in.CORSOrigins = cur.CORSOrigins // set on its own (cors)
|
||||
in.AllowIPs = cur.AllowIPs // set on its own (allowips)
|
||||
in.MTLS = cur.MTLS // set on its own (mtls)
|
||||
in.HTTPS = cur.HTTPS // set on its own (https)
|
||||
in.FetchPrivate = cur.FetchPrivate // in settings.json only
|
||||
in.RouterNote = cur.RouterNote // set on its own (the Library's servers/hub-note)
|
||||
in.RouterAllTools = cur.RouterAllTools // set on its own (the Library's servers/hub-tools)
|
||||
|
||||
Reference in New Issue
Block a user