Jarl 0.1.0: manage BIND through a web UI, REST API and CLI

Jarl keeps a BIND 9.20 server's whole configuration (views, ACLs, TSIG
keys, zones of every type, records, named.conf options) in SQLite and
renders named.conf, keys.conf and zone files from it.

Every change goes through one changeset pipeline: whole-configuration
validation, named-checkconf -z and named-checkzone in a staging
directory, atomic install, rndc reconfig/reload, serial verification
with rndc zonestatus, and rollback if named does not load the change.
Changes apply one at a time by default or are bundled and applied
together. Applied changesets can be reverted.

- jarld: the daemon with the REST API and an embedded web UI, plus import,
  adopt, check, resync, backup and local user recovery commands
- jarl: the CLI, including ACME DNS-01 hooks for certbot and acme.sh
- users with argon2id passwords and CSRF-protected sessions; hashed API
  tokens with granular grants and roles; an audit log
- systemd unit, sysusers.d/tmpfiles.d files, Makefile
- unit tests, integration tests against a real named, scripts/e2e.sh
- docs/ guides, README and CHANGELOG

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
abrown38andClaude Opus 5.5 committed 2026-10-07 15:03:13 +00:00
commit bd6b8778e4
122 files changed
+29217

No files matched your search

+256
View File
@@ -0,0 +1,256 @@
package main
import (
"context"
"fmt"
"net"
"os"
"strings"
"time"
"github.com/spf13/cobra"
"jarl/internal/api"
"jarl/internal/client"
)
const acmePrefix = "_acme-challenge."
// acmeOptions are the flags shared by the acme subcommands.
type acmeOptions struct {
view string
ttl uint32
exact bool
followCNAME bool
resolver string
}
func (o *acmeOptions) flags(cmd *cobra.Command) {
cmd.Flags().StringVar(&o.view, "view", "", "only the zone in this view (default: every view that has the zone)")
cmd.Flags().BoolVar(&o.exact, "exact", false, "use DOMAIN as the record name as it is, without adding _acme-challenge.")
cmd.Flags().BoolVar(&o.followCNAME, "follow-cname", false, "if the challenge name is a CNAME (e.g. into a dedicated ACME zone), write the record at its target")
cmd.Flags().StringVar(&o.resolver, "resolver", "", "DNS server for --follow-cname, HOST[:PORT] (default: the system's resolvers)")
}
// dnsResolver returns the resolver used to follow CNAMEs.
func (o *acmeOptions) dnsResolver() *net.Resolver {
if o.resolver == "" {
return net.DefaultResolver
}
addr := o.resolver
if _, _, err := net.SplitHostPort(addr); err != nil {
addr = net.JoinHostPort(addr, "53")
}
return &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, network, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, network, addr)
}}
}
// challengeName returns the FQDN of the TXT record for a domain.
func (o *acmeOptions) challengeName(domain string) (string, error) {
d := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(domain), "."))
if d == "" {
return "", fmt.Errorf("no domain given")
}
if !o.exact {
d = strings.TrimPrefix(d, "*.")
if !strings.HasPrefix(d, acmePrefix) {
d = acmePrefix + d
}
}
name := d + "."
if o.followCNAME {
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// A lookup error usually just means there is no CNAME (or no
// record yet), so keep the name.
if target, err := o.dnsResolver().LookupCNAME(c, name); err == nil && !strings.EqualFold(target, name) {
if !flagQuiet {
fmt.Fprintf(os.Stderr, "%s is a CNAME for %s\n", dot(name), dot(target))
}
name = strings.ToLower(target)
}
}
return name, nil
}
// acmeZones finds the primary zones (one per view) that contain name.
func acmeZones(c *client.Client, name, view string) ([]api.Zone, error) {
var zones []api.Zone
if err := c.Get(ctx(), "/zones", q("type", "primary"), &zones); err != nil {
return nil, err
}
best := ""
var out []api.Zone
for _, z := range zones {
if view != "" && !strings.EqualFold(z.View, view) {
continue
}
zn := strings.ToLower(z.Name)
if !(name == zn || zn == "." || strings.HasSuffix(name, "."+zn)) {
continue
}
switch {
case len(zn) > len(best):
best, out = zn, []api.Zone{z}
case zn == best:
out = append(out, z)
}
}
if len(out) == 0 {
where := ""
if view != "" {
where = " in view " + view
}
return nil, fmt.Errorf("no primary zone%s that you can see contains %s", where, dot(name))
}
return out, nil
}
// acmeChange adds (set) or removes the challenge values for domain.
func acmeChange(o *acmeOptions, domain string, values []string, set bool) error {
name, err := o.challengeName(domain)
if err != nil {
return err
}
c, err := newClient()
if err != nil {
return err
}
zones, err := acmeZones(c, name, o.view)
if err != nil {
return err
}
var reqs []api.ChangeRequest
for _, z := range zones {
base := map[string]any{"zone": z.Name, "name": name, "type": "TXT"}
if z.View != "" {
base["view"] = z.View
}
with := func(extra map[string]any) map[string]any {
m := map[string]any{}
for k, v := range base {
m[k] = v
}
for k, v := range extra {
m[k] = v
}
return m
}
if !set && len(values) == 0 {
reqs = append(reqs, api.ChangeRequest{Op: "record.delete", Data: rawJSON(with(map[string]any{"missing_ok": true}))})
continue
}
for _, v := range values {
// Deleting first makes a repeated 'set' (a retried hook)
// succeed instead of failing on a duplicate record.
reqs = append(reqs, api.ChangeRequest{Op: "record.delete", Data: rawJSON(with(map[string]any{"data": v, "missing_ok": true}))})
if set {
reqs = append(reqs, api.ChangeRequest{Op: "record.create", Data: rawJSON(with(map[string]any{"data": v, "ttl": o.ttl, "comment": "ACME DNS-01 challenge"}))})
}
}
}
verb := "remove"
if set {
verb = "set"
}
return submitBatch(c, fmt.Sprintf("ACME: %s challenge for %s", verb, dot(name)), reqs)
}
// envOrError returns an environment variable that a hook needs.
func envOrError(name string) (string, error) {
v := os.Getenv(name)
if v == "" {
return "", fmt.Errorf("%s is not set (run this command as a certbot hook)", name)
}
return v, nil
}
func acmeCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "acme",
Short: "Publish and remove ACME DNS-01 challenge records (Let's Encrypt)",
Long: `Publishes and removes the _acme-challenge TXT records that ACME certificate
authorities such as Let's Encrypt check for DNS-01 challenges. When the
command returns, named is already serving the record: Jarl reloads the zone
and checks its serial before it reports success.
The zone is found automatically (the longest matching primary zone). If the
zone exists in several views, the record goes into each of them, so it is
seen both from inside and from the internet.
Give the hook its own token that can only touch challenge records:
jarl user create certbot --no-password --role acme
jarl token create certbot --user certbot --role acme
certbot:
certbot certonly --manual --preferred-challenges dns \
--manual-auth-hook 'jarl acme certbot-auth' \
--manual-cleanup-hook 'jarl acme certbot-cleanup' \
-d adbraun.lol -d '*.adbraun.lol'
acme.sh: copy contrib/acme.sh/dns_jarl.sh into ~/.acme.sh/dnsapi/ and use
'--dns dns_jarl' (see docs/acme.md).`,
}
o := &acmeOptions{}
set := &cobra.Command{
Use: "set DOMAIN VALUE...",
Short: "Publish challenge values for DOMAIN (at _acme-challenge.DOMAIN)",
Example: ` jarl acme set www.adbraun.lol gfj9Xq...Rg85nM
jarl acme set '*.adbraun.lol' value-for-wildcard value-for-apex`,
Args: cobra.MinimumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
return acmeChange(o, args[0], args[1:], true)
},
}
o.flags(set)
set.Flags().Uint32Var(&o.ttl, "ttl", 60, "TTL of the challenge record")
unset := &cobra.Command{
Use: "unset DOMAIN [VALUE...]",
Short: "Remove challenge values for DOMAIN (all of them when no VALUE is given)",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return acmeChange(o, args[0], args[1:], false)
},
}
o.flags(unset)
auth := &cobra.Command{
Use: "certbot-auth",
Short: "certbot --manual-auth-hook: publish $CERTBOT_VALIDATION for $CERTBOT_DOMAIN",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
domain, err := envOrError("CERTBOT_DOMAIN")
if err != nil {
return err
}
value, err := envOrError("CERTBOT_VALIDATION")
if err != nil {
return err
}
return acmeChange(o, domain, []string{value}, true)
},
}
o.flags(auth)
auth.Flags().Uint32Var(&o.ttl, "ttl", 60, "TTL of the challenge record")
cleanup := &cobra.Command{
Use: "certbot-cleanup",
Short: "certbot --manual-cleanup-hook: remove $CERTBOT_VALIDATION for $CERTBOT_DOMAIN",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
domain, err := envOrError("CERTBOT_DOMAIN")
if err != nil {
return err
}
value, err := envOrError("CERTBOT_VALIDATION")
if err != nil {
return err
}
return acmeChange(o, domain, []string{value}, false)
},
}
o.flags(cleanup)
cmd.AddCommand(set, unset, auth, cleanup)
return cmd
}
+853
View File
@@ -0,0 +1,853 @@
package main
import (
"bufio"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
"golang.org/x/term"
"jarl/internal/api"
"jarl/internal/client"
)
// randomSecret returns a base64 TSIG secret as long as the algorithm's
// hash output.
func randomSecret(alg string) string {
n := map[string]int{"hmac-sha512": 64, "hmac-sha384": 48, "hmac-sha224": 28, "hmac-sha1": 20, "hmac-md5": 16}[strings.ToLower(alg)]
if n == 0 {
n = 32
}
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return base64.StdEncoding.EncodeToString(b)
}
// readSecret reads a password or token from the terminal without echo, or
// a line from standard input when it is not a terminal.
func readSecret(prompt string) (string, error) {
fd := int(os.Stdin.Fd())
if term.IsTerminal(fd) {
fmt.Fprint(os.Stderr, prompt)
b, err := term.ReadPassword(fd)
fmt.Fprintln(os.Stderr)
return strings.TrimSpace(string(b)), err
}
line, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil && err != io.EOF {
return "", err
}
return strings.TrimSpace(line), nil
}
// readNewPassword asks for a password twice on a terminal.
func readNewPassword() (string, error) {
pw, err := readSecret("New password: ")
if err != nil {
return "", err
}
if term.IsTerminal(int(os.Stdin.Fd())) {
again, err := readSecret("Repeat it: ")
if err != nil {
return "", err
}
if again != pw {
return "", fmt.Errorf("the passwords don't match")
}
}
if pw == "" {
return "", fmt.Errorf("empty password")
}
return pw, nil
}
func fmtTime(t *time.Time) string {
if t == nil || t.IsZero() {
return "-"
}
return t.Local().Format("2006-01-02 15:04")
}
// ---- status, whoami, check, resync
func statusCmd() *cobra.Command {
return &cobra.Command{
Use: "status",
Short: "Show the state of Jarl and named",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var resp api.StatusResponse
if err := c.Get(ctx(), "/status", nil, &resp); err != nil {
return err
}
var st struct {
Adopted bool `json:"adopted"`
AdoptError string `json:"adopt_error"`
NamedError string `json:"named_error"`
BINDVersion string `json:"bind_version"`
Named *struct {
Version string `json:"version"`
BootTime string `json:"boot_time"`
LastConfigured string `json:"last_configured"`
Zones string `json:"zones"`
Running bool `json:"running"`
} `json:"named"`
Drift []struct {
Path string `json:"path"`
Reason string `json:"reason"`
} `json:"drift"`
Deployed bool `json:"deployed"`
LastApplied *api.Changeset `json:"last_applied"`
OpenChangesets int `json:"open_changesets"`
Problems []client.Problem `json:"problems"`
Counts map[string]int `json:"counts"`
MainConfig string `json:"main_config"`
}
if err := json.Unmarshal(resp.Engine, &st); err != nil {
return err
}
return output(resp, func(w io.Writer) {
fmt.Fprintf(w, "Jarl:\t%s\n", resp.Version)
switch {
case st.Named != nil && st.Named.Running:
fmt.Fprintf(w, "named:\trunning (%s), up since %s, configured %s\n", firstNonEmpty(st.Named.Version, st.BINDVersion), st.Named.BootTime, st.Named.LastConfigured)
case st.NamedError != "":
fmt.Fprintf(w, "named:\tNOT REACHABLE: %s\n", st.NamedError)
default:
fmt.Fprintf(w, "named:\tnot checked (reloads disabled)\n")
}
adopted := "yes"
if !st.Adopted {
adopted = "NO: named does not load Jarl's configuration yet (run 'jarld adopt')"
if st.AdoptError != "" {
adopted += ": " + st.AdoptError
}
}
if st.MainConfig != "" {
fmt.Fprintf(w, "Adopted:\t%s\n", adopted)
}
if st.Counts != nil {
fmt.Fprintf(w, "Objects:\t%d zones, %d records, %d views, %d ACLs, %d TSIG keys\n", st.Counts["zones"], st.Counts["records"], st.Counts["views"], st.Counts["acls"], st.Counts["tsig_keys"])
}
if st.LastApplied != nil {
fmt.Fprintf(w, "Last change:\t#%d %s by %s (%s)\n", st.LastApplied.ID, fmtTime(st.LastApplied.AppliedAt), st.LastApplied.AppliedBy, st.LastApplied.Description)
}
fmt.Fprintf(w, "Open changesets:\t%d\n", st.OpenChangesets)
if len(st.Drift) == 0 {
fmt.Fprintf(w, "Drift:\tnone\n")
}
for _, d := range st.Drift {
fmt.Fprintf(w, "Drift:\t%s %s (fix with 'jarl resync --force' or apply with --force)\n", d.Path, d.Reason)
}
if len(st.Problems) > 0 {
w.(interface{ Flush() error }).Flush()
fmt.Println("Problems:")
printProblems(os.Stdout, st.Problems)
}
})
},
}
}
func whoamiCmd() *cobra.Command {
return &cobra.Command{
Use: "whoami",
Short: "Show who the token belongs to and what it may do",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var me api.Whoami
if err := c.Get(ctx(), "/auth/whoami", nil, &me); err != nil {
return err
}
return output(me, func(w io.Writer) {
fmt.Fprintf(w, "User:\t%s\n", me.User.Username)
if me.Token != nil {
fmt.Fprintf(w, "Token:\t%s (%s), expires %s\n", me.Token.Name, me.Token.PublicID, fmtTime(me.Token.ExpiresAt))
}
fmt.Fprintf(w, "Server:\t%s\n", me.Version)
for i, p := range me.Permissions {
label := ""
if i == 0 {
label = "Permissions:"
}
fmt.Fprintf(w, "%s\t%s\n", label, p)
}
})
},
}
}
// printResult prints the outcome of a check or resync.
func printResult(r *client.Result, ok string) error {
if r == nil {
return fmt.Errorf("empty response")
}
if flagOutput != "table" {
return output(r, nil)
}
if r.Error != nil {
fmt.Println("error:", r.Error.Message)
}
printProblems(os.Stdout, r.Problems)
for _, m := range r.Check {
obj := ""
if m.Object != "" {
obj = " [" + m.Object + "]"
}
fmt.Printf(" named-checkconf: %s%s\n", m.Text, obj)
}
for _, w := range r.Warnings {
fmt.Println("warning:", w)
}
if r.Diff != "" {
fmt.Print(r.Diff)
}
if !r.Valid || r.Error != nil {
return fmt.Errorf("the configuration has errors")
}
if !flagQuiet {
fmt.Println(ok)
}
return nil
}
func checkCmd() *cobra.Command {
return &cobra.Command{
Use: "check",
Short: "Validate the current configuration and run named-checkconf on it",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var raw json.RawMessage
if err := c.Do(ctx(), "POST", "/system/check", nil, nil, &raw); err != nil {
return err
}
return printResult(client.ParseResult(raw), "ok: the configuration is valid")
},
}
}
func resyncCmd() *cobra.Command {
return &cobra.Command{
Use: "resync",
Short: "Rewrite all BIND files from Jarl's database and reload named (admin)",
Long: `Rewrites every file Jarl manages from the database and reloads named. Use
it after files were changed by hand (drift) or restored from a backup.
Files changed outside Jarl are only overwritten with --force; --dry-run
shows what would change.`,
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var raw json.RawMessage
err = c.Do(ctx(), "POST", "/system/resync", nil, map[string]bool{"dry_run": flagDryRun, "force": flagForce}, &raw)
if err != nil {
return err
}
msg := "resynced"
if flagDryRun {
msg = "dry run: nothing was changed"
}
return printResult(client.ParseResult(raw), msg)
},
}
}
// ---- users and tokens
// userID resolves a username (or numeric ID) to a user ID.
func userID(c *client.Client, name string) (int64, error) {
if id, err := strconv.ParseInt(name, 10, 64); err == nil {
return id, nil
}
var users []api.User
if err := c.Get(ctx(), "/users", nil, &users); err != nil {
return 0, err
}
for _, u := range users {
if strings.EqualFold(u.Username, name) {
return u.ID, nil
}
}
return 0, fmt.Errorf("no user %q", name)
}
func printUser(w io.Writer, u api.User) {
fmt.Fprintf(w, "User:\t%s (id %d)\n", u.Username, u.ID)
role := "user"
if u.Admin {
role = "administrator"
}
if u.Disabled {
role += ", DISABLED"
}
if !u.HasPassword {
role += ", no password (tokens only)"
}
fmt.Fprintf(w, "Role:\t%s\n", role)
for i, g := range u.GrantStrings {
label := ""
if i == 0 {
label = "Grants:"
}
fmt.Fprintf(w, "%s\t%s\n", label, g)
}
if u.Comment != "" {
fmt.Fprintf(w, "Comment:\t%s\n", u.Comment)
}
fmt.Fprintf(w, "Last login:\t%s\n", fmtTime(u.LastLoginAt))
}
const grantHelp = `Grants use the form RESOURCE:ACCESS [zones=..] [views=..] [names=..] [types=..]
where RESOURCE is zones, records, views, acls, tsig, options, audit or *,
ACCESS is read or write, and filters take comma separated glob patterns:
records:write zones=adbraun.lol
records:write zones=adbraun.lol names=_acme-challenge.* types=TXT
*:read
Roles are ready-made grant sets: readonly, dns-editor, operator, acme.`
func userCmd() *cobra.Command {
cmd := &cobra.Command{Use: "user", Aliases: []string{"users"}, Short: "Manage users (admin)", Long: "Manage users (admin).\n\n" + grantHelp}
list := &cobra.Command{
Use: "list",
Short: "List users",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var users []api.User
if err := c.Get(ctx(), "/users", nil, &users); err != nil {
return err
}
return output(users, func(w io.Writer) {
fmt.Fprintln(w, "ID\tUSER\tADMIN\tDISABLED\tGRANTS\tLAST LOGIN")
for _, u := range users {
fmt.Fprintf(w, "%d\t%s\t%v\t%v\t%s\t%s\n", u.ID, u.Username, u.Admin, u.Disabled, strings.Join(u.GrantStrings, "; "), fmtTime(u.LastLoginAt))
}
})
},
}
show := &cobra.Command{
Use: "show USER",
Short: "Show a user",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
id, err := userID(c, args[0])
if err != nil {
return err
}
var u api.User
if err := c.Get(ctx(), fmt.Sprintf("/users/%d", id), nil, &u); err != nil {
return err
}
return output(u, func(w io.Writer) { printUser(w, u) })
},
}
var admin, noPassword, disabled bool
var role, comment, rename string
var grants []string
userBody := func(cmd *cobra.Command) (api.UserInput, error) {
var in api.UserInput
f := cmd.Flags()
if f.Changed("admin") {
in.Admin = &admin
}
if f.Changed("role") {
in.Role = &role
}
if f.Changed("grant") {
in.GrantStrings = &grants
}
if f.Changed("comment") {
in.Comment = &comment
}
if f.Changed("disabled") {
in.Disabled = &disabled
}
if f.Changed("rename") {
in.Username = &rename
}
return in, nil
}
addUserFlags := func(c *cobra.Command) {
c.Flags().BoolVar(&admin, "admin", false, "make the user an administrator (--admin=false to remove)")
c.Flags().StringVar(&role, "role", "", "replace the grants with a role: readonly, dns-editor, operator or acme")
c.Flags().StringArrayVar(&grants, "grant", nil, `grant (repeatable), e.g. "records:write zones=example.com"`)
c.Flags().StringVar(&comment, "comment", "", "comment")
}
create := &cobra.Command{
Use: "create NAME",
Short: "Create a user (asks for a password unless --no-password)",
Example: ` jarl user create alice --role dns-editor
jarl user create certbot --no-password --role acme --comment "Let's Encrypt"
jarl user create bob --grant "records:write zones=lab.adbraun.lol" --grant "zones:read"`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
in, err := userBody(cmd)
if err != nil {
return err
}
name := args[0]
in.Username = &name
pw := ""
if !noPassword {
if pw, err = readNewPassword(); err != nil {
return err
}
}
in.Password = &pw
var u api.User
if err := c.Do(ctx(), "POST", "/users", nil, in, &u); err != nil {
return err
}
return output(u, func(w io.Writer) { printUser(w, u) })
},
}
addUserFlags(create)
create.Flags().BoolVar(&noPassword, "no-password", false, "a service account that can only use API tokens")
var setPassword, clearPassword bool
update := &cobra.Command{
Use: "update USER",
Short: "Change a user",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
id, err := userID(c, args[0])
if err != nil {
return err
}
in, err := userBody(cmd)
if err != nil {
return err
}
switch {
case setPassword:
pw, err := readNewPassword()
if err != nil {
return err
}
in.Password = &pw
case clearPassword:
empty := ""
in.Password = &empty
}
if in == (api.UserInput{}) {
return fmt.Errorf("nothing to change (see --help)")
}
var u api.User
if err := c.Do(ctx(), "PATCH", fmt.Sprintf("/users/%d", id), nil, in, &u); err != nil {
return err
}
return output(u, func(w io.Writer) { printUser(w, u) })
},
}
addUserFlags(update)
update.Flags().BoolVar(&disabled, "disabled", false, "disable the account (--disabled=false to enable it)")
update.Flags().StringVar(&rename, "rename", "", "new username")
update.Flags().BoolVar(&setPassword, "password", false, "set a new password (asks for it)")
update.Flags().BoolVar(&clearPassword, "no-password", false, "remove the password (tokens only)")
var yes bool
del := &cobra.Command{
Use: "delete USER",
Short: "Delete a user and revoke their tokens",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if !confirm("Delete user "+args[0]+"?", yes) {
return fmt.Errorf("canceled")
}
c, err := newClient()
if err != nil {
return err
}
id, err := userID(c, args[0])
if err != nil {
return err
}
if err := c.Do(ctx(), "DELETE", fmt.Sprintf("/users/%d", id), nil, nil, nil); err != nil {
return err
}
if !flagQuiet {
fmt.Println("deleted user", args[0])
}
return nil
},
}
del.Flags().BoolVarP(&yes, "yes", "y", false, "don't ask for confirmation")
cmd.AddCommand(list, show, create, update, del)
return cmd
}
func tokenCmd() *cobra.Command {
cmd := &cobra.Command{Use: "token", Aliases: []string{"tokens"}, Short: "Manage API tokens", Long: "Manage API tokens. A token has its user's permissions, or fewer when it has\nits own grants.\n\n" + grantHelp}
var user string
var all, revoked bool
list := &cobra.Command{
Use: "list",
Short: "List your tokens (--user or --all for others; admin)",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
path := "/me/tokens"
switch {
case all:
path = "/tokens"
case user != "":
id, err := userID(c, user)
if err != nil {
return err
}
path = fmt.Sprintf("/users/%d/tokens", id)
}
qv := q()
if revoked {
qv.Set("all", "1")
}
var tokens []api.Token
if err := c.Get(ctx(), path, qv, &tokens); err != nil {
return err
}
return output(tokens, func(w io.Writer) {
fmt.Fprintln(w, "ID\tUSER\tNAME\tPREFIX\tGRANTS\tEXPIRES\tLAST USED\tREVOKED")
for _, t := range tokens {
g := "(user's)"
if t.Grants != nil {
g = strings.Join(t.GrantStrings, "; ")
}
fmt.Fprintf(w, "%d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", t.ID, t.Username, t.Name, t.PublicID, g, fmtTime(t.ExpiresAt), fmtTime(t.LastUsedAt), fmtTime(t.RevokedAt))
}
})
},
}
list.Flags().StringVar(&user, "user", "", "tokens of this user")
list.Flags().BoolVar(&all, "all", false, "tokens of every user")
list.Flags().BoolVar(&revoked, "revoked", false, "include revoked tokens")
var role, expires string
var grants []string
var save bool
create := &cobra.Command{
Use: "create NAME",
Short: "Create a token; the secret is printed once",
Example: ` jarl token create laptop
jarl token create certbot --user certbot --role acme --expires 365d
jarl token create lab-ci --grant "records:write zones=lab.adbraun.lol"`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
in := api.TokenInput{Name: args[0], Role: role, ExpiresIn: expires}
if cmd.Flags().Changed("grant") {
in.GrantStrings = &grants
}
path := "/me/tokens"
if user != "" {
id, err := userID(c, user)
if err != nil {
return err
}
path = fmt.Sprintf("/users/%d/tokens", id)
}
var t api.Token
if err := c.Do(ctx(), "POST", path, nil, in, &t); err != nil {
return err
}
if save {
cfg, err := loadCLIConfig()
if err != nil {
return err
}
cfg.Token = t.Secret
if err := saveCLIConfig(cfg); err != nil {
return err
}
}
if flagQuiet {
fmt.Println(t.Secret)
return nil
}
return output(t, func(w io.Writer) {
fmt.Fprintf(w, "Token:\t%s\n", t.Secret)
fmt.Fprintf(w, "Name:\t%s (id %d, user %s)\n", t.Name, t.ID, t.Username)
if t.Grants != nil {
fmt.Fprintf(w, "Grants:\t%s\n", strings.Join(t.GrantStrings, "; "))
}
fmt.Fprintf(w, "Expires:\t%s\n", fmtTime(t.ExpiresAt))
if save {
fmt.Fprintf(w, "Saved to:\t%s\n", flagConfig)
} else {
fmt.Fprintln(w, "\nThe token is shown only once; store it now.")
}
})
},
}
create.Flags().StringVar(&user, "user", "", "create the token for this user (admin)")
create.Flags().StringVar(&role, "role", "", "restrict the token to a role: readonly, dns-editor, operator or acme")
create.Flags().StringArrayVar(&grants, "grant", nil, "restrict the token to these grants (repeatable)")
create.Flags().StringVar(&expires, "expires", "", "lifetime, e.g. 90d or 720h (default: never)")
create.Flags().BoolVar(&save, "save", false, "store the new token in the CLI configuration file")
revoke := &cobra.Command{
Use: "revoke ID",
Short: "Revoke a token (see 'token list' for IDs)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
if _, err := strconv.ParseInt(args[0], 10, 64); err != nil {
return fmt.Errorf("give the token's numeric ID (see 'jarl token list')")
}
if err := c.Do(ctx(), "DELETE", "/tokens/"+args[0], nil, nil, nil); err != nil {
return err
}
if !flagQuiet {
fmt.Println("revoked token", args[0])
}
return nil
},
}
cmd.AddCommand(list, create, revoke)
return cmd
}
// ---- audit and search
func auditCmd() *cobra.Command {
var user, action, outcome, objType, since, until, search string
var changeset int64
var limit int
cmd := &cobra.Command{
Use: "audit",
Short: "Show the audit log (logins, changes, users and tokens)",
Long: `Shows the audit log, newest first. Without the audit permission you only
see your own activity.
jarl audit --since 2026-10-01 --outcome failure
jarl audit --user certbot --limit 20
jarl audit --action login`,
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
qv := q("user", user, "action", action, "outcome", outcome, "object_type", objType, "since", since, "until", until, "q", search, "limit", strconv.Itoa(limit))
if changeset > 0 {
qv.Set("changeset", strconv.FormatInt(changeset, 10))
}
var events []struct {
ID int64 `json:"id"`
Time time.Time `json:"time"`
Username string `json:"username"`
Auth string `json:"auth"`
TokenName string `json:"token_name"`
IP string `json:"ip"`
Action string `json:"action"`
ObjectType string `json:"object_type"`
ObjectName string `json:"object_name"`
ChangesetID int64 `json:"changeset_id"`
Outcome string `json:"outcome"`
Message string `json:"message"`
}
if err := c.Get(ctx(), "/audit", qv, &events); err != nil {
return err
}
return output(events, func(w io.Writer) {
fmt.Fprintln(w, "TIME\tUSER\tVIA\tIP\tACTION\tOBJECT\tOUTCOME\tMESSAGE")
for _, e := range events {
via := e.Auth
if e.TokenName != "" {
via += ":" + e.TokenName
}
obj := e.ObjectName
if e.ChangesetID > 0 {
obj = strings.TrimSpace(fmt.Sprintf("%s (changeset %d)", obj, e.ChangesetID))
}
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", e.Time.Local().Format("2006-01-02 15:04:05"), e.Username, via, e.IP, e.Action, obj, e.Outcome, e.Message)
}
})
},
}
f := cmd.Flags()
f.StringVar(&user, "user", "", "only this user")
f.StringVar(&action, "action", "", "only this action (e.g. login, changeset.apply, token.create)")
f.StringVar(&outcome, "outcome", "", "success, failure or denied")
f.StringVar(&objType, "object-type", "", "only events about this kind of object (zone, user, token, ...)")
f.StringVar(&since, "since", "", "from this time (YYYY-MM-DD or RFC 3339)")
f.StringVar(&until, "until", "", "up to this time")
f.StringVar(&search, "search", "", "only events whose text contains this")
f.Int64Var(&changeset, "changeset", 0, "only events of this changeset")
f.IntVar(&limit, "limit", 50, "how many")
return cmd
}
func searchCmd() *cobra.Command {
var limit int
cmd := &cobra.Command{
Use: "search TEXT",
Short: "Find zones, records and ACLs by name, data or comment",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var hits []api.SearchResult
if err := c.Get(ctx(), "/search", q("q", args[0], "limit", strconv.Itoa(limit)), &hits); err != nil {
return err
}
return output(hits, func(w io.Writer) {
fmt.Fprintln(w, "KIND\tID\tMATCH\tWHERE")
for _, h := range hits {
fmt.Fprintf(w, "%s\t%d\t%s\t%s\n", h.Kind, h.ID, h.Label, h.Detail)
}
})
},
}
cmd.Flags().IntVar(&limit, "limit", 100, "maximum number of results")
return cmd
}
// ---- CLI configuration
func configCmd() *cobra.Command {
cmd := &cobra.Command{Use: "config", Short: "Show or change the CLI's own configuration file"}
keys := "server, token, insecure, ca-cert"
set := &cobra.Command{
Use: "set KEY [VALUE]",
Short: "Set " + keys + " (the token is read from the terminal when VALUE is left out)",
Example: ` jarl config set server https://ns1.adbraun.lol:8053
jarl config set token # paste it at the prompt, keeping it out of shell history`,
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadCLIConfig()
if err != nil {
return err
}
value := ""
if len(args) == 2 {
value = args[1]
} else if args[0] == "token" {
if value, err = readSecret("API token: "); err != nil {
return err
}
} else {
return fmt.Errorf("give a value for %s", args[0])
}
switch args[0] {
case "server":
u, err := url.Parse(value)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return fmt.Errorf("invalid server URL %q (use e.g. https://ns1.example.com:8053)", value)
}
cfg.Server = strings.TrimSuffix(value, "/")
case "token":
if !strings.HasPrefix(value, "jarl_") && !strings.HasPrefix(value, "@") {
return fmt.Errorf("that doesn't look like a Jarl token (they start with jarl_)")
}
cfg.Token = value
case "insecure":
b, err := strconv.ParseBool(value)
if err != nil {
return fmt.Errorf("insecure must be true or false")
}
cfg.Insecure = b
case "ca-cert", "ca_cert":
cfg.CACert = value
default:
return fmt.Errorf("unknown key %q (use %s)", args[0], keys)
}
if err := saveCLIConfig(cfg); err != nil {
return err
}
if !flagQuiet {
fmt.Printf("saved %s in %s\n", args[0], flagConfig)
}
return nil
},
}
show := &cobra.Command{
Use: "show",
Short: "Show the configuration (the token is masked)",
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadCLIConfig()
if err != nil {
return err
}
tok := cfg.Token
if len(tok) > 14 && !strings.HasPrefix(tok, "@") {
tok = tok[:14] + "..."
}
fmt.Printf("file: %s\nserver: %s\ntoken: %s\ninsecure: %v\nca-cert: %s\n", flagConfig, cfg.Server, tok, cfg.Insecure, cfg.CACert)
if v := os.Getenv("JARL_SERVER"); v != "" {
fmt.Printf("(JARL_SERVER overrides the server: %s)\n", v)
}
if os.Getenv("JARL_TOKEN") != "" {
fmt.Println("(JARL_TOKEN overrides the token)")
}
return nil
},
}
unset := &cobra.Command{
Use: "unset KEY",
Short: "Remove a setting",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := loadCLIConfig()
if err != nil {
return err
}
switch args[0] {
case "server":
cfg.Server = ""
case "token":
cfg.Token = ""
case "insecure":
cfg.Insecure = false
case "ca-cert", "ca_cert":
cfg.CACert = ""
default:
return fmt.Errorf("unknown key %q (use %s)", args[0], keys)
}
return saveCLIConfig(cfg)
},
}
cmd.AddCommand(set, show, unset)
return cmd
}
+408
View File
@@ -0,0 +1,408 @@
package main
import (
"encoding/json"
"fmt"
"io"
"os"
"strconv"
"strings"
"github.com/spf13/cobra"
"go.yaml.in/yaml/v3"
"jarl/internal/api"
"jarl/internal/client"
)
// batchFile is the format of 'jarl apply -f'.
type batchFile struct {
Description string `yaml:"description" json:"description"`
Changes []batchEntry `yaml:"changes" json:"changes"`
}
type batchEntry struct {
Add map[string]any `yaml:"add,omitempty" json:"add,omitempty"`
Delete map[string]any `yaml:"delete,omitempty" json:"delete,omitempty"`
Set map[string]any `yaml:"set,omitempty" json:"set,omitempty"`
Update map[string]any `yaml:"update,omitempty" json:"update,omitempty"`
// Any API operation: op, id, data.
Op string `yaml:"op,omitempty" json:"op,omitempty"`
ID int64 `yaml:"id,omitempty" json:"id,omitempty"`
Data map[string]any `yaml:"data,omitempty" json:"data,omitempty"`
}
func toInt64(v any) (int64, bool) {
switch n := v.(type) {
case int:
return int64(n), true
case int64:
return n, true
case float64:
return int64(n), true
case string:
i, err := strconv.ParseInt(n, 10, 64)
return i, err == nil
}
return 0, false
}
func rawJSON(v any) json.RawMessage {
b, _ := json.Marshal(v)
return b
}
// requests converts the file's entries into API change requests.
func (b *batchFile) requests() ([]api.ChangeRequest, error) {
var out []api.ChangeRequest
for i, e := range b.Changes {
n := 0
for _, set := range []bool{e.Add != nil, e.Delete != nil, e.Set != nil, e.Update != nil, e.Op != ""} {
if set {
n++
}
}
if n != 1 {
return nil, fmt.Errorf("change %d: use exactly one of add, delete, set, update or op", i+1)
}
switch {
case e.Add != nil:
out = append(out, api.ChangeRequest{Op: "record.create", Data: rawJSON(e.Add)})
case e.Delete != nil:
d := e.Delete
if id, ok := toInt64(d["id"]); ok {
delete(d, "id")
out = append(out, api.ChangeRequest{Op: "record.delete", ID: id, Data: rawJSON(d)})
} else {
out = append(out, api.ChangeRequest{Op: "record.delete", Data: rawJSON(d)})
}
case e.Set != nil:
s := e.Set
switch d := s["data"].(type) {
case string:
s["data"] = []string{d}
case nil:
s["data"] = []string{}
}
out = append(out, api.ChangeRequest{Op: "rrset.replace", Data: rawJSON(s)})
case e.Update != nil:
u := e.Update
id, ok := toInt64(u["id"])
if !ok {
return nil, fmt.Errorf("change %d: update needs the record id", i+1)
}
delete(u, "id")
out = append(out, api.ChangeRequest{Op: "record.update", ID: id, Data: rawJSON(u)})
default:
var data json.RawMessage
if e.Data != nil {
data = rawJSON(e.Data)
}
out = append(out, api.ChangeRequest{Op: e.Op, ID: e.ID, Data: data})
}
}
return out, nil
}
// submitBatch applies requests as one changeset, or stages them into the
// changeset given with --changeset.
func submitBatch(c *client.Client, description string, reqs []api.ChangeRequest) error {
var resp api.MutationResponse
if c.Changeset > 0 {
if err := c.Do(ctx(), "POST", fmt.Sprintf("/changesets/%d/ops", c.Changeset), nil, map[string]any{"ops": reqs}, &resp); err != nil {
return err
}
return report(&resp)
}
if err := c.Do(ctx(), "POST", "/apply", nil, api.BatchRequest{Description: description, Ops: reqs, DryRun: c.DryRun, Force: c.Force}, &resp); err != nil {
return err
}
return report(&resp)
}
func applyCmd() *cobra.Command {
var file, desc string
cmd := &cobra.Command{
Use: "apply -f FILE",
Short: "Apply a batch of changes from a YAML or JSON file, all or nothing",
Long: `Applies the changes in FILE ('-' for standard input) as one changeset: they
are validated together and either all are applied or none.
description: move the web server
changes:
- add: {zone: example.com, name: www2, type: A, data: 192.0.2.20, ttl: 300, ptr: true}
- delete: {zone: example.com, name: www, type: A} # every A record of www
- delete: {zone: example.com, name: old, type: CNAME, data: www} # just this record
- delete: {id: 1234}
- set: {zone: example.com, name: api, type: A, data: [192.0.2.30, 192.0.2.31], ttl: 60}
- update: {id: 1235, data: 192.0.2.40}
- op: zone.create # any API operation
data: {name: lab.example.com, nameservers: [ns1.example.com.]}
Records name zones by name (add "view: NAME" when the zone exists in several
views). With --changeset the changes are staged instead; with --dry-run they
are only validated.`,
RunE: func(cmd *cobra.Command, args []string) error {
if file == "" {
return fmt.Errorf("-f FILE is required")
}
var data []byte
var err error
if file == "-" {
data, err = io.ReadAll(os.Stdin)
} else {
data, err = os.ReadFile(file)
}
if err != nil {
return err
}
var b batchFile
if err := yaml.Unmarshal(data, &b); err != nil {
return fmt.Errorf("%s: %w", file, err)
}
if desc != "" {
b.Description = desc
}
reqs, err := b.requests()
if err != nil {
return err
}
if len(reqs) == 0 {
return fmt.Errorf("%s has no changes", file)
}
c, err := newClient()
if err != nil {
return err
}
return submitBatch(c, b.Description, reqs)
},
}
cmd.Flags().StringVarP(&file, "file", "f", "", "file with the changes ('-' for standard input)")
cmd.Flags().StringVar(&desc, "description", "", "description for the history")
return cmd
}
func changesetCmd() *cobra.Command {
cmd := &cobra.Command{Use: "changeset", Aliases: []string{"cs"}, Short: "Stage changes and apply them together"}
var status string
var mine bool
list := &cobra.Command{
Use: "list",
Short: "List changesets (open ones by default)",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
qv := q("status", status)
if mine {
qv.Set("mine", "1")
}
var list []api.Changeset
if err := c.Get(ctx(), "/changesets", qv, &list); err != nil {
return err
}
return output(list, func(w io.Writer) {
fmt.Fprintln(w, "ID\tSTATUS\tUSER\tVIA\tOPS\tDESCRIPTION")
for _, cs := range list {
fmt.Fprintf(w, "%d\t%s\t%s\t%s\t%d\t%s\n", cs.ID, cs.Status, cs.Username, cs.Via, len(cs.Ops), cs.Description)
}
})
},
}
list.Flags().StringVar(&status, "status", "open", "open, applied or discarded (empty for all)")
list.Flags().BoolVar(&mine, "mine", false, "only my changesets")
create := &cobra.Command{
Use: "create [DESCRIPTION]",
Short: "Start a changeset; prints its ID",
Example: ` export JARL_CHANGESET=$(jarl changeset create "move web servers" -q)
jarl record add example.com www2 A 192.0.2.20
jarl record delete example.com www A
jarl changeset diff $JARL_CHANGESET
jarl changeset apply $JARL_CHANGESET`,
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var cs api.Changeset
if err := c.Do(ctx(), "POST", "/changesets", nil, map[string]any{"description": strings.Join(args, " ")}, &cs); err != nil {
return err
}
if flagQuiet {
fmt.Println(cs.ID)
return nil
}
fmt.Printf("created changeset %d\nstage changes with --changeset %d (or export JARL_CHANGESET=%d)\n", cs.ID, cs.ID, cs.ID)
return nil
},
}
show := &cobra.Command{
Use: "show ID",
Short: "Show a changeset's operations",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var cs api.Changeset
if err := c.Get(ctx(), "/changesets/"+args[0], nil, &cs); err != nil {
return err
}
return output(cs, func(w io.Writer) {
fmt.Fprintf(w, "Changeset:\t%d (%s)\nDescription:\t%s\nCreated:\t%s by %s via %s\n", cs.ID, cs.Status, cs.Description, cs.CreatedAt.Format("2006-01-02 15:04"), cs.Username, cs.Via)
if cs.AppliedAt != nil {
fmt.Fprintf(w, "Applied:\t%s by %s\n", cs.AppliedAt.Format("2006-01-02 15:04"), cs.AppliedBy)
}
fmt.Fprintln(w, "\n#\tOPERATION")
for _, op := range cs.Ops {
fmt.Fprintf(w, "%d\t%s\n", op.Seq, op.Summary)
}
if cs.Diff != "" {
w.(interface{ Flush() error }).Flush()
fmt.Println()
fmt.Print(cs.Diff)
}
})
},
}
diff := &cobra.Command{
Use: "diff ID",
Short: "Validate an open changeset and show what applying it would change",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var raw json.RawMessage
if err := c.Get(ctx(), "/changesets/"+args[0]+"/preview", nil, &raw); err != nil {
return err
}
if flagOutput != "table" {
var v any
json.Unmarshal(raw, &v)
return output(v, nil)
}
r := client.ParseResult(raw)
for _, op := range r.Ops {
fmt.Printf("#%d %s\n", op.Seq, op.Summary)
}
if r.Error != nil {
fmt.Println("error:", r.Error.Message)
}
printProblems(os.Stdout, r.Problems)
printCheck(os.Stdout, r.Check)
for _, w := range r.Warnings {
fmt.Println("warning:", w)
}
fmt.Println()
fmt.Print(r.Diff)
if r.Valid {
fmt.Println("\nvalid: apply with 'jarl changeset apply " + args[0] + "'")
return nil
}
return fmt.Errorf("the changeset can't be applied as it is")
},
}
apply := &cobra.Command{
Use: "apply ID",
Short: "Apply an open changeset",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var resp api.MutationResponse
if err := c.Do(ctx(), "POST", "/changesets/"+args[0]+"/apply", nil, map[string]any{"force": c.Force, "dry_run": c.DryRun}, &resp); err != nil {
return err
}
return report(&resp)
},
}
discard := &cobra.Command{
Use: "discard ID",
Short: "Throw away an open changeset",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
if err := c.Do(ctx(), "POST", "/changesets/"+args[0]+"/discard", nil, nil, nil); err != nil {
return err
}
if !flagQuiet {
fmt.Println("discarded changeset", args[0])
}
return nil
},
}
remove := &cobra.Command{
Use: "remove ID SEQ",
Short: "Remove one operation from an open changeset",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
return c.Do(ctx(), "DELETE", "/changesets/"+args[0]+"/ops/"+args[1], nil, nil, nil)
},
}
revert := &cobra.Command{
Use: "revert ID",
Short: "Create a changeset that undoes an applied changeset (review it, then apply)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var cs api.Changeset
if err := c.Do(ctx(), "POST", "/changesets/"+args[0]+"/revert", nil, nil, &cs); err != nil {
return err
}
if flagQuiet {
fmt.Println(cs.ID)
return nil
}
fmt.Printf("created changeset %d with %d operations; review with 'jarl changeset diff %d', apply with 'jarl changeset apply %d'\n", cs.ID, len(cs.Ops), cs.ID, cs.ID)
return nil
},
}
cmd.AddCommand(list, create, show, diff, apply, discard, remove, revert)
return cmd
}
func historyCmd() *cobra.Command {
var limit int
cmd := &cobra.Command{
Use: "history",
Short: "List applied changesets",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var list []api.Changeset
if err := c.Get(ctx(), "/changesets", q("status", "applied", "limit", fmt.Sprint(limit)), &list); err != nil {
return err
}
return output(list, func(w io.Writer) {
fmt.Fprintln(w, "ID\tAPPLIED\tBY\tVIA\tOPS\tDESCRIPTION")
for _, cs := range list {
at := ""
if cs.AppliedAt != nil {
at = cs.AppliedAt.Local().Format("2006-01-02 15:04")
}
fmt.Fprintf(w, "%d\t%s\t%s\t%s\t%d\t%s\n", cs.ID, at, cs.AppliedBy, cs.Via, len(cs.Ops), cs.Description)
}
})
},
}
cmd.Flags().IntVar(&limit, "limit", 30, "how many")
return cmd
}
+735
View File
@@ -0,0 +1,735 @@
package main
import (
"fmt"
"io"
"net/url"
"strings"
"github.com/spf13/cobra"
"jarl/internal/api"
"jarl/internal/model"
)
func viewCmd() *cobra.Command {
cmd := &cobra.Command{Use: "view", Aliases: []string{"views"}, Short: "Manage views"}
list := &cobra.Command{
Use: "list",
Short: "List views in match order",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var views []api.View
if err := c.Get(ctx(), "/views", nil, &views); err != nil {
return err
}
return output(views, func(w io.Writer) {
fmt.Fprintln(w, "#\tID\tVIEW\tMATCH-CLIENTS\tMATCH-DESTINATIONS\tZONES")
for i, v := range views {
fmt.Fprintf(w, "%d\t%d\t%s\t%s\t%s\t%d\n", i+1, v.ID, v.Name, orAny(v.MatchClients), orAny(v.MatchDestinations), v.Zones)
}
})
},
}
var clients, dests []string
var recursiveOnly, comment string
var adopt, cascade, yes bool
viewBody := func(cmd *cobra.Command) map[string]any {
body := map[string]any{}
f := cmd.Flags()
if f.Changed("match-clients") {
body["match_clients"] = clients
}
if f.Changed("match-destinations") {
body["match_destinations"] = dests
}
if f.Changed("recursive-only") {
switch recursiveOnly {
case "yes", "true":
body["match_recursive_only"] = true
case "no", "false":
body["match_recursive_only"] = false
default:
body["match_recursive_only"] = nil
}
}
if f.Changed("comment") {
body["comment"] = comment
}
return body
}
addViewFlags := func(c *cobra.Command) {
c.Flags().StringSliceVar(&clients, "match-clients", nil, "match-clients elements (comma separated or repeated)")
c.Flags().StringSliceVar(&dests, "match-destinations", nil, "match-destinations elements")
c.Flags().StringVar(&recursiveOnly, "recursive-only", "", "match-recursive-only: yes, no or default")
c.Flags().StringVar(&comment, "comment", "", "comment")
}
create := &cobra.Command{
Use: "create NAME",
Short: "Create a view (added after the existing views)",
Example: ` jarl view create internal --match-clients 192.168.0.0/16,localhost --adopt-zones
jarl view create external --match-clients any`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
body := viewBody(cmd)
body["name"] = args[0]
if adopt {
body["adopt_zones"] = true
}
resp, err := c.Mutate(ctx(), "POST", "/views", nil, body)
if err != nil {
return err
}
return report(resp)
},
}
addViewFlags(create)
create.Flags().BoolVar(&adopt, "adopt-zones", false, "move zones that are not in a view into this one (required for the first view if zones exist)")
var rename string
update := &cobra.Command{
Use: "update VIEW",
Short: "Change a view",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
body := viewBody(cmd)
if rename != "" {
body["name"] = rename
}
resp, err := c.Mutate(ctx(), "PATCH", "/views/"+url.PathEscape(args[0]), nil, body)
if err != nil {
return err
}
return report(resp)
},
}
addViewFlags(update)
update.Flags().StringVar(&rename, "rename", "", "new name")
del := &cobra.Command{
Use: "delete VIEW",
Short: "Delete a view",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if cascade && !confirm("Delete view "+args[0]+" with all its zones?", yes) {
return fmt.Errorf("canceled")
}
c, err := newClient()
if err != nil {
return err
}
qv := q()
if cascade {
qv.Set("cascade", "1")
}
resp, err := c.Mutate(ctx(), "DELETE", "/views/"+url.PathEscape(args[0]), qv, nil)
if err != nil {
return err
}
return report(resp)
},
}
del.Flags().BoolVar(&cascade, "cascade", false, "also delete the view's zones")
del.Flags().BoolVarP(&yes, "yes", "y", false, "don't ask for confirmation")
order := &cobra.Command{
Use: "order VIEW...",
Short: "Set the order in which views are matched (list every view)",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var views []api.View
if err := c.Get(ctx(), "/views", nil, &views); err != nil {
return err
}
byName := map[string]int64{}
for _, v := range views {
byName[strings.ToLower(v.Name)] = v.ID
}
var ids []int64
for _, a := range args {
id, ok := byName[strings.ToLower(a)]
if !ok {
return fmt.Errorf("no view %q", a)
}
ids = append(ids, id)
}
resp, err := c.Mutate(ctx(), "POST", "/views/order", nil, map[string]any{"ids": ids})
if err != nil {
return err
}
return report(resp)
},
}
cmd.AddCommand(list, create, update, del, order)
return cmd
}
func orAny(list []string) string {
if len(list) == 0 {
return "any"
}
return strings.Join(list, "; ")
}
func aclCmd() *cobra.Command {
cmd := &cobra.Command{Use: "acl", Aliases: []string{"acls"}, Short: "Manage ACLs (named address match lists)"}
list := &cobra.Command{
Use: "list",
Short: "List ACLs",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var acls []api.ACL
if err := c.Get(ctx(), "/acls", nil, &acls); err != nil {
return err
}
return output(acls, func(w io.Writer) {
fmt.Fprintln(w, "ID\tACL\tELEMENTS\tUSED BY")
for _, a := range acls {
fmt.Fprintf(w, "%d\t%s\t%s\t%s\n", a.ID, a.Name, strings.Join(a.Elements, "; "), strings.Join(a.UsedBy, ", "))
}
})
},
}
var comment, rename string
var add, remove []string
create := &cobra.Command{
Use: "create NAME ELEMENT...",
Short: "Create an ACL",
Example: ` jarl acl create homelab 192.168.1.0/24 10.10.0.0/16 localhost`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
body := map[string]any{"name": args[0], "elements": args[1:], "comment": comment}
resp, err := c.Mutate(ctx(), "POST", "/acls", nil, body)
if err != nil {
return err
}
return report(resp)
},
}
create.Flags().StringVar(&comment, "comment", "", "comment")
var set []string
update := &cobra.Command{
Use: "update ACL",
Short: "Change an ACL (--add/--remove elements, --set all elements, --rename)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var cur api.ACL
if err := c.Get(ctx(), "/acls/"+url.PathEscape(args[0]), nil, &cur); err != nil {
return err
}
body := map[string]any{}
elems := cur.Elements
if cmd.Flags().Changed("set") {
elems = set
}
for _, a := range add {
elems = append(elems, a)
}
if len(remove) > 0 {
drop := map[string]bool{}
for _, r := range remove {
drop[r] = true
}
var kept []string
for _, e := range elems {
if !drop[e] {
kept = append(kept, e)
}
}
elems = kept
}
if elems == nil {
elems = []string{}
}
if cmd.Flags().Changed("set") || len(add) > 0 || len(remove) > 0 {
body["elements"] = elems
}
if rename != "" {
body["name"] = rename
}
if cmd.Flags().Changed("comment") {
body["comment"] = comment
}
if len(body) == 0 {
return fmt.Errorf("nothing to change (see --help)")
}
resp, err := c.Mutate(ctx(), "PATCH", "/acls/"+url.PathEscape(args[0]), nil, body)
if err != nil {
return err
}
return report(resp)
},
}
update.Flags().StringSliceVar(&add, "add", nil, "add elements")
update.Flags().StringSliceVar(&remove, "remove", nil, "remove elements (exact text)")
update.Flags().StringSliceVar(&set, "set", nil, "replace all elements")
update.Flags().StringVar(&rename, "rename", "", "new name (references are updated)")
update.Flags().StringVar(&comment, "comment", "", "comment")
del := &cobra.Command{
Use: "delete ACL",
Short: "Delete an ACL (refused while it is in use)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
resp, err := c.Mutate(ctx(), "DELETE", "/acls/"+url.PathEscape(args[0]), nil, nil)
if err != nil {
return err
}
return report(resp)
},
}
cmd.AddCommand(list, create, update, del)
return cmd
}
func tsigCmd() *cobra.Command {
cmd := &cobra.Command{Use: "tsig", Aliases: []string{"key", "keys"}, Short: "Manage TSIG keys"}
list := &cobra.Command{
Use: "list",
Short: "List TSIG keys",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var keys []api.TSIGKey
if err := c.Get(ctx(), "/tsig-keys", nil, &keys); err != nil {
return err
}
return output(keys, func(w io.Writer) {
fmt.Fprintln(w, "ID\tKEY\tALGORITHM\tUSED BY")
for _, k := range keys {
fmt.Fprintf(w, "%d\t%s\t%s\t%s\n", k.ID, k.Name, k.Algorithm, strings.Join(k.UsedBy, ", "))
}
})
},
}
var secret, algorithm, comment string
var named bool
show := &cobra.Command{
Use: "show KEY",
Short: "Show a key and its secret",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var k api.TSIGKey
if err := c.Get(ctx(), "/tsig-keys/"+url.PathEscape(args[0]), q("secret", "1"), &k); err != nil {
return err
}
if named {
fmt.Printf("key %q {\n\talgorithm %s;\n\tsecret %q;\n};\n", k.Name, k.Algorithm, k.Secret)
return nil
}
return output(k, func(w io.Writer) {
fmt.Fprintf(w, "Key:\t%s\nAlgorithm:\t%s\nSecret:\t%s\nUsed by:\t%s\n", k.Name, k.Algorithm, k.Secret, strings.Join(k.UsedBy, ", "))
})
},
}
show.Flags().BoolVar(&named, "named-conf", false, "print a key statement for another server's named.conf")
create := &cobra.Command{
Use: "create NAME",
Short: "Create a TSIG key (the secret is generated unless given)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
body := map[string]any{"name": args[0], "algorithm": algorithm, "comment": comment}
if secret != "" {
body["secret"] = secret
}
resp, err := c.Mutate(ctx(), "POST", "/tsig-keys", nil, body)
if err != nil {
return err
}
if err := report(resp); err != nil {
return err
}
if resp.Applied && flagOutput == "table" {
var k api.TSIGKey
if jsonUnmarshal(resp.Object, &k) == nil && k.Secret != "" {
fmt.Printf("secret: %s\n", k.Secret)
}
}
return nil
},
}
create.Flags().StringVar(&algorithm, "algorithm", "hmac-sha256", "algorithm")
create.Flags().StringVar(&secret, "secret", "", "base64 secret (default: generated)")
create.Flags().StringVar(&comment, "comment", "", "comment")
rotate := &cobra.Command{
Use: "rotate KEY",
Short: "Give a key a new random secret (or --secret)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
if secret == "" {
var k api.TSIGKey
if err := c.Get(ctx(), "/tsig-keys/"+url.PathEscape(args[0]), nil, &k); err != nil {
return err
}
secret = randomSecret(k.Algorithm)
}
resp, err := c.Mutate(ctx(), "PATCH", "/tsig-keys/"+url.PathEscape(args[0]), nil, map[string]any{"secret": secret})
if err != nil {
return err
}
if err := report(resp); err != nil {
return err
}
fmt.Printf("new secret: %s\n", secret)
return nil
},
}
rotate.Flags().StringVar(&secret, "secret", "", "the new secret (default: generated)")
del := &cobra.Command{
Use: "delete KEY",
Short: "Delete a key (refused while it is in use)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
resp, err := c.Mutate(ctx(), "DELETE", "/tsig-keys/"+url.PathEscape(args[0]), nil, nil)
if err != nil {
return err
}
return report(resp)
},
}
cmd.AddCommand(list, show, create, rotate, del)
return cmd
}
func optionCmd() *cobra.Command {
cmd := &cobra.Command{Use: "option", Aliases: []string{"options", "opt"}, Short: "Manage named options (server, view, zone, top-level)"}
var view, zone, zoneView string
var toplevel bool
scopeArgs := func(c *cobra.Command) {
c.Flags().StringVar(&view, "view", "", "options of this view")
c.Flags().StringVar(&zone, "zone", "", "options of this zone")
c.Flags().StringVar(&zoneView, "zone-view", "", "view of --zone")
c.Flags().BoolVar(&toplevel, "toplevel", false, "top-level statements (logging, controls, ...)")
}
scope := func() (string, int64, error) {
c, err := newClient()
if err != nil {
return "", 0, err
}
switch {
case zone != "":
id, err := resolveZoneID(c, zone, zoneView)
return model.ScopeZone, id, err
case view != "":
var v api.View
if err := c.Get(ctx(), "/views/"+url.PathEscape(view), nil, &v); err != nil {
return "", 0, err
}
return model.ScopeView, v.ID, nil
case toplevel:
return model.ScopeTopLevel, 0, nil
}
return model.ScopeOptions, 0, nil
}
list := &cobra.Command{
Use: "list",
Short: "List options (server options by default)",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
qv := q()
if view != "" || zone != "" || toplevel || !cmd.Flags().Changed("all") {
sc, id, err := scope()
if err != nil {
return err
}
qv = q("scope", sc, "scope_id", fmt.Sprint(id))
}
if all {
qv = q()
}
var opts []api.Option
if err := c.Get(ctx(), "/options", qv, &opts); err != nil {
return err
}
return output(opts, func(w io.Writer) {
fmt.Fprintln(w, "ID\tWHERE\tOPTION\tVALUE")
for _, o := range opts {
fmt.Fprintf(w, "%d\t%s\t%s\t%s\n", o.ID, o.Where, o.Name, o.Value)
}
})
},
}
scopeArgs(list)
list.Flags().BoolVar(&all, "all", false, "options of every scope")
var comment string
set := &cobra.Command{
Use: "set NAME [VALUE...]",
Short: "Set an option (replaces an existing option of the same name)",
Long: `Set an option; VALUE is named.conf syntax without the trailing semicolon.
jarl option set recursion no
jarl option set allow-recursion '{ homelab; localhost; }'
jarl option set forwarders '{ 1.1.1.1; 9.9.9.9; }'
jarl option set allow-transfer '{ key xfer; }' --zone example.com
jarl option set logging '{ channel q { file "/var/log/named/q.log"; }; category queries { q; }; }' --toplevel`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
sc, id, err := scope()
if err != nil {
return err
}
value := strings.Join(args[1:], " ")
var opts []api.Option
if err := c.Get(ctx(), "/options", q("scope", sc, "scope_id", fmt.Sprint(id)), &opts); err != nil {
return err
}
body := map[string]any{"value": value}
if cmd.Flags().Changed("comment") {
body["comment"] = comment
}
for _, o := range opts {
if o.Name == strings.ToLower(args[0]) && !multiple {
resp, err := c.Mutate(ctx(), "PATCH", fmt.Sprintf("/options/%d", o.ID), nil, body)
if err != nil {
return err
}
return report(resp)
}
}
body["scope"], body["scope_id"], body["name"] = sc, id, args[0]
resp, err := c.Mutate(ctx(), "POST", "/options", nil, body)
if err != nil {
return err
}
return report(resp)
},
}
scopeArgs(set)
set.Flags().StringVar(&comment, "comment", "", "comment")
set.Flags().BoolVar(&multiple, "add", false, "add another instance instead of replacing (for options that may occur several times)")
unset := &cobra.Command{
Use: "unset NAME | unset --id ID",
Short: "Remove an option (BIND's default applies again)",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
if optID > 0 {
resp, err := c.Mutate(ctx(), "DELETE", fmt.Sprintf("/options/%d", optID), nil, nil)
if err != nil {
return err
}
return report(resp)
}
if len(args) != 1 {
return fmt.Errorf("give the option name or --id")
}
sc, id, err := scope()
if err != nil {
return err
}
var opts []api.Option
if err := c.Get(ctx(), "/options", q("scope", sc, "scope_id", fmt.Sprint(id)), &opts); err != nil {
return err
}
var matches []api.Option
for _, o := range opts {
if o.Name == strings.ToLower(args[0]) {
matches = append(matches, o)
}
}
switch len(matches) {
case 0:
return fmt.Errorf("option %s is not set here", args[0])
case 1:
default:
return fmt.Errorf("option %s is set %d times; remove one with --id", args[0], len(matches))
}
resp, err := c.Mutate(ctx(), "DELETE", fmt.Sprintf("/options/%d", matches[0].ID), nil, nil)
if err != nil {
return err
}
return report(resp)
},
}
scopeArgs(unset)
unset.Flags().Int64Var(&optID, "id", 0, "remove the option with this ID")
describe := &cobra.Command{
Use: "describe [NAME]",
Short: "Describe options from the BIND 9.20 catalog",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
cs := "options"
switch {
case toplevel:
cs = "toplevel"
case view != "":
cs = "view"
case zone != "":
cs = "zone:" + zoneType
}
var stmts []struct {
Name string `json:"name"`
Grammar string `json:"grammar"`
Kind string `json:"kind"`
Status string `json:"status"`
Description string `json:"description"`
}
if err := c.Get(ctx(), "/catalog/options", q("scope", cs), &stmts); err != nil {
return err
}
for _, s := range stmts {
if len(args) == 1 && s.Name != args[0] {
continue
}
if len(args) == 0 {
fmt.Printf("%-32s %s\n", s.Name, s.Description)
continue
}
fmt.Printf("%s (%s)%s\n %s\n\n%s\n", s.Name, s.Kind, statusText(s.Status), s.Description, s.Grammar)
return nil
}
if len(args) == 1 {
return fmt.Errorf("%s is not an option in scope %s", args[0], cs)
}
return nil
},
}
scopeArgs(describe)
describe.Flags().StringVar(&zoneType, "zone-type", "primary", "with --zone: the zone type")
cmd.AddCommand(list, set, unset, describe)
return cmd
}
var (
all bool
multiple bool
optID int64
zoneType string
)
func statusText(s string) string {
if s == "" {
return ""
}
return " [" + s + "]"
}
func settingsCmd() *cobra.Command {
cmd := &cobra.Command{Use: "settings", Short: "Show or change Jarl's defaults for new zones"}
show := &cobra.Command{
Use: "show",
Short: "Show settings",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var s model.Settings
if err := c.Get(ctx(), "/settings", nil, &s); err != nil {
return err
}
return output(s, func(w io.Writer) {
fmt.Fprintf(w, "Name servers:\t%s\nContact:\t%s\nDefault TTL:\t%d\nRefresh/retry/expire:\t%d/%d/%d\nNegative TTL:\t%d\nSerial policy:\t%s\n",
strings.Join(s.Nameservers, ", "), s.RName, s.DefaultTTL, s.Refresh, s.Retry, s.Expire, s.NegativeTTL, s.SerialPolicy)
})
},
}
var ns []string
var contact, policy string
var ttl, refresh, retry, expire, neg uint32
set := &cobra.Command{
Use: "set",
Short: "Change settings",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
body := map[string]any{}
f := cmd.Flags()
if f.Changed("ns") {
body["nameservers"] = ns
}
if f.Changed("contact") {
body["rname"] = contact
}
if f.Changed("serial-policy") {
body["serial_policy"] = policy
}
for name, v := range map[string]uint32{"ttl": ttl, "refresh": refresh, "retry": retry, "expire": expire, "negative-ttl": neg} {
if f.Changed(name) {
key := map[string]string{"ttl": "default_ttl", "negative-ttl": "negative_ttl"}[name]
if key == "" {
key = name
}
body[key] = v
}
}
if len(body) == 0 {
return fmt.Errorf("nothing to change (see --help)")
}
resp, err := c.Mutate(ctx(), "PATCH", "/settings", nil, body)
if err != nil {
return err
}
return report(resp)
},
}
set.Flags().StringSliceVar(&ns, "ns", nil, "default name servers")
set.Flags().StringVar(&contact, "contact", "", "default SOA contact")
set.Flags().StringVar(&policy, "serial-policy", "", "date, increment or unixtime")
set.Flags().Uint32Var(&ttl, "ttl", 0, "default TTL")
set.Flags().Uint32Var(&refresh, "refresh", 0, "SOA refresh")
set.Flags().Uint32Var(&retry, "retry", 0, "SOA retry")
set.Flags().Uint32Var(&expire, "expire", 0, "SOA expire")
set.Flags().Uint32Var(&neg, "negative-ttl", 0, "SOA minimum")
cmd.AddCommand(show, set)
return cmd
}
+382
View File
@@ -0,0 +1,382 @@
// Command jarl is the command line client for Jarl. It talks to jarld's
// REST API with an API token.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"text/tabwriter"
"github.com/spf13/cobra"
"go.yaml.in/yaml/v3"
"jarl/internal/api"
"jarl/internal/client"
"jarl/internal/version"
)
func main() {
root := rootCmd()
if err := root.Execute(); err != nil {
printError(err)
os.Exit(exitCode(err))
}
}
// Global flags.
var (
flagServer string
flagToken string
flagConfig string
flagChangeset int64
flagDryRun bool
flagForce bool
flagOutput string
flagInsecure bool
flagCACert string
flagQuiet bool
)
// cliConfig is ~/.config/jarl/config.yaml.
type cliConfig struct {
Server string `yaml:"server"`
Token string `yaml:"token"`
Insecure bool `yaml:"insecure,omitempty"`
CACert string `yaml:"ca_cert,omitempty"`
}
func defaultConfigPath() string {
if p := os.Getenv("JARL_CLI_CONFIG"); p != "" {
return p
}
dir, err := os.UserConfigDir()
if err != nil {
dir = filepath.Join(os.Getenv("HOME"), ".config")
}
return filepath.Join(dir, "jarl", "config.yaml")
}
func loadCLIConfig() (*cliConfig, error) {
c := &cliConfig{}
b, err := os.ReadFile(flagConfig)
if errors.Is(err, os.ErrNotExist) {
return c, nil
}
if err != nil {
return nil, err
}
return c, yaml.Unmarshal(b, c)
}
func saveCLIConfig(c *cliConfig) error {
if err := os.MkdirAll(filepath.Dir(flagConfig), 0o700); err != nil {
return err
}
b, err := yaml.Marshal(c)
if err != nil {
return err
}
return os.WriteFile(flagConfig, b, 0o600)
}
func newClient() (*client.Client, error) {
cfg, err := loadCLIConfig()
if err != nil {
return nil, fmt.Errorf("reading %s: %w", flagConfig, err)
}
server := firstNonEmpty(flagServer, os.Getenv("JARL_SERVER"), cfg.Server)
token := firstNonEmpty(flagToken, os.Getenv("JARL_TOKEN"), cfg.Token)
if token == "" {
return nil, fmt.Errorf("no API token: use --token, JARL_TOKEN or 'jarl config set token'")
}
if strings.HasPrefix(token, "@") {
b, err := os.ReadFile(token[1:])
if err != nil {
return nil, fmt.Errorf("reading token file: %w", err)
}
token = strings.TrimSpace(string(b))
}
c, err := client.New(client.Options{Server: server, Token: token, Insecure: flagInsecure || cfg.Insecure, CACert: firstNonEmpty(flagCACert, cfg.CACert)})
if err != nil {
return nil, err
}
c.Changeset = flagChangeset
if c.Changeset == 0 {
if v := os.Getenv("JARL_CHANGESET"); v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid JARL_CHANGESET %q", v)
}
c.Changeset = n
}
}
c.DryRun, c.Force = flagDryRun, flagForce
return c, nil
}
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if v != "" {
return v
}
}
return ""
}
func rootCmd() *cobra.Command {
root := &cobra.Command{
Use: "jarl",
Short: "Command line client for Jarl, the BIND manager",
Long: `jarl manages a BIND server through Jarl's API.
Every command that changes the configuration is applied at once, as a
single changeset that is validated, checked with named-checkconf and loaded
into named. To batch several changes, create a changeset and pass
--changeset ID (or set JARL_CHANGESET), then apply it; or describe the
changes in a file and run 'jarl apply -f FILE'.
Configure the server and token once:
jarl config set server https://dns.example.com:8053
jarl config set token (paste the token at the prompt)
Exit codes: 0 ok, 1 error, 3 not authenticated or not allowed, 4 not found,
5 conflict, 6 invalid or rejected by validation, 7 server or BIND error.`,
SilenceUsage: true,
SilenceErrors: true,
Version: version.Version,
}
pf := root.PersistentFlags()
pf.StringVar(&flagServer, "server", "", "Jarl server URL (env JARL_SERVER)")
pf.StringVar(&flagToken, "token", "", "API token, or @FILE to read it from a file (env JARL_TOKEN)")
pf.StringVar(&flagConfig, "config", defaultConfigPath(), "CLI configuration file")
pf.Int64VarP(&flagChangeset, "changeset", "C", 0, "stage changes into this changeset instead of applying them (env JARL_CHANGESET)")
pf.BoolVarP(&flagDryRun, "dry-run", "n", false, "validate and show the changes without applying them")
pf.BoolVar(&flagForce, "force", false, "overwrite BIND files that were changed outside Jarl")
pf.StringVarP(&flagOutput, "output", "o", "table", "output format: table, json or yaml")
pf.BoolVar(&flagInsecure, "insecure", false, "don't verify the server's TLS certificate")
pf.StringVar(&flagCACert, "ca-cert", "", "PEM file with a CA to trust for the server's certificate")
pf.BoolVarP(&flagQuiet, "quiet", "q", false, "only print errors (and IDs where useful)")
root.AddGroup(&cobra.Group{ID: "dns", Title: "DNS commands:"}, &cobra.Group{ID: "changes", Title: "Changes:"}, &cobra.Group{ID: "admin", Title: "Administration:"})
add := func(group string, cmds ...*cobra.Command) {
for _, c := range cmds {
c.GroupID = group
root.AddCommand(c)
}
}
add("dns", zoneCmd(), recordCmd(), viewCmd(), aclCmd(), tsigCmd(), optionCmd(), settingsCmd(), acmeCmd(), searchCmd())
add("changes", applyCmd(), changesetCmd(), historyCmd())
add("admin", statusCmd(), whoamiCmd(), userCmd(), tokenCmd(), auditCmd(), checkCmd(), resyncCmd(), configCmd())
return root
}
// ctx returns the context for API calls. The HTTP client's timeout bounds
// each request.
func ctx() context.Context { return context.Background() }
// ---- output
func output(v any, table func(w io.Writer)) error {
switch flagOutput {
case "json":
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(v)
case "yaml":
// Round-trip through JSON so field names match the API.
b, err := json.Marshal(v)
if err != nil {
return err
}
var x any
if err := json.Unmarshal(b, &x); err != nil {
return err
}
return yaml.NewEncoder(os.Stdout).Encode(x)
case "table", "":
if table == nil {
return output(v, nil)
}
tw := tabwriter.NewWriter(os.Stdout, 2, 4, 2, ' ', 0)
table(tw)
return tw.Flush()
}
return fmt.Errorf("unknown output format %q (use table, json or yaml)", flagOutput)
}
func dot(name string) string {
if name == "." || name == "" {
return "."
}
return strings.TrimSuffix(name, ".")
}
// where describes the zone and view a problem is about.
func where(p client.Problem) string {
if p.Zone == "" {
return ""
}
s := " [zone " + dot(p.Zone)
if p.View != "" {
s += ", view " + p.View
}
return s + "]"
}
func printProblems(w io.Writer, ps []client.Problem) {
for _, p := range ps {
fmt.Fprintf(w, " %s: %s%s\n", p.Severity, p.Message, where(p))
}
}
func printCheck(w io.Writer, ms []client.CheckMessage) {
for _, m := range ms {
if m.Error {
obj := ""
if m.Object != "" {
obj = " [" + m.Object + "]"
}
fmt.Fprintf(w, " named-checkconf: %s%s\n", m.Text, obj)
}
}
}
func printError(err error) {
var ce *client.Error
if errors.As(err, &ce) {
// The message often repeats the first problem; print it once.
head, ps := ce.Info.Message, ce.Problems()
for i, p := range ps {
if p.Message == head {
head += where(p)
ps = append(ps[:i:i], ps[i+1:]...)
break
}
if strings.HasPrefix(head, p.Message+" (and ") {
head = fmt.Sprintf("the change was rejected (%d problems):", len(ps))
break
}
}
fmt.Fprintln(os.Stderr, "error:", head)
printProblems(os.Stderr, ps)
printCheck(os.Stderr, ce.Check())
if r := client.ParseResult(ce.Info.Result); r != nil && r.Diff != "" && flagDryRun {
fmt.Fprint(os.Stderr, r.Diff)
}
return
}
fmt.Fprintln(os.Stderr, "error:", err)
}
// exitCode maps errors to exit codes for scripts: 1 other errors, 3 not
// authenticated or not allowed, 4 not found, 5 conflict, 6 invalid
// request or rejected by validation, 7 server error.
func exitCode(err error) int {
var ce *client.Error
if errors.As(err, &ce) {
switch {
case ce.Status == 401 || ce.Status == 403:
return 3
case ce.Status == 404:
return 4
case ce.Status == 409:
return 5
case ce.Status == 400 || ce.Status == 422:
return 6
case ce.Status >= 500:
return 7
}
}
return 1
}
// report prints the outcome of a change.
func report(resp *api.MutationResponse) error {
if flagOutput == "json" || flagOutput == "yaml" {
return output(resp, nil)
}
w := os.Stdout
r := client.ParseResult(resp.Result)
switch {
case resp.Staged:
if !flagQuiet {
for _, op := range resp.Added {
fmt.Fprintf(w, "staged #%d: %s\n", op.Seq, op.Summary)
}
fmt.Fprintf(w, "(changeset %d: review with 'jarl changeset diff %d', apply with 'jarl changeset apply %d')\n", resp.ChangesetID, resp.ChangesetID, resp.ChangesetID)
}
case resp.DryRun && r != nil:
for _, op := range r.Ops {
fmt.Fprintf(w, "would %s\n", op.Summary)
}
if len(r.Problems) > 0 {
fmt.Fprintln(w, "problems:")
printProblems(w, r.Problems)
}
if r.Diff != "" {
fmt.Fprint(w, r.Diff)
} else {
fmt.Fprintln(w, "(no file changes)")
}
fmt.Fprintln(w, "dry run: nothing was changed")
case resp.Applied && r != nil:
if flagQuiet {
break
}
for _, op := range r.Ops {
fmt.Fprintf(w, "%s\n", op.Summary)
}
for _, s := range r.Serials {
v := ""
if s.View != "" {
v = " [" + s.View + "]"
}
fmt.Fprintf(w, "zone %s%s serial %d -> %d\n", dot(s.Zone), v, s.Old, s.New)
}
fmt.Fprintf(w, "applied (changeset %d)\n", r.ChangesetID)
}
for _, warn := range resp.Warnings {
fmt.Fprintln(os.Stderr, "warning:", warn)
}
if r != nil && !resp.Applied && !resp.Staged && !resp.DryRun {
return fmt.Errorf("not applied")
}
return nil
}
func q(kv ...string) url.Values {
v := url.Values{}
for i := 0; i+1 < len(kv); i += 2 {
if kv[i+1] != "" {
v.Set(kv[i], kv[i+1])
}
}
return v
}
// zonePath returns the API path for a zone given by name or ID.
func zonePath(zone, view string) (string, url.Values) {
z := strings.TrimSuffix(zone, ".")
if zone == "." {
z = "root"
}
return "/zones/" + url.PathEscape(z), q("view", view)
}
func confirm(prompt string, yes bool) bool {
if yes || flagDryRun || flagChangeset > 0 {
return true
}
fmt.Fprintf(os.Stderr, "%s [y/N] ", prompt)
var answer string
fmt.Scanln(&answer)
return strings.EqualFold(answer, "y") || strings.EqualFold(answer, "yes")
}
+104
View File
@@ -0,0 +1,104 @@
package main
import (
"encoding/json"
"testing"
"go.yaml.in/yaml/v3"
)
func TestBatchFile(t *testing.T) {
src := `
description: test
changes:
- add: {zone: example.com, name: www, type: A, data: 192.0.2.1, ptr: true}
- delete: {zone: example.com, name: old, type: A}
- delete: {id: 12}
- set: {zone: example.com, name: api, type: A, data: 192.0.2.5}
- set: {zone: example.com, name: gone, type: TXT}
- update: {id: 13, data: 192.0.2.9}
- op: zone.create
data: {name: lab.example.com}
`
var b batchFile
if err := yaml.Unmarshal([]byte(src), &b); err != nil {
t.Fatal(err)
}
reqs, err := b.requests()
if err != nil {
t.Fatal(err)
}
want := []struct {
op string
id int64
data string
}{
{"record.create", 0, `{"data":"192.0.2.1","name":"www","ptr":true,"type":"A","zone":"example.com"}`},
{"record.delete", 0, `{"name":"old","type":"A","zone":"example.com"}`},
{"record.delete", 12, `{}`},
{"rrset.replace", 0, `{"data":["192.0.2.5"],"name":"api","type":"A","zone":"example.com"}`},
{"rrset.replace", 0, `{"data":[],"name":"gone","type":"TXT","zone":"example.com"}`},
{"record.update", 13, `{"data":"192.0.2.9"}`},
{"zone.create", 0, `{"name":"lab.example.com"}`},
}
if len(reqs) != len(want) {
t.Fatalf("got %d requests, want %d", len(reqs), len(want))
}
for i, w := range want {
r := reqs[i]
// Compare data as parsed JSON so key order doesn't matter.
var got, exp any
json.Unmarshal(r.Data, &got)
json.Unmarshal([]byte(w.data), &exp)
gb, _ := json.Marshal(got)
eb, _ := json.Marshal(exp)
if r.Op != w.op || r.ID != w.id || string(gb) != string(eb) {
t.Errorf("request %d = %s %d %s, want %s %d %s", i, r.Op, r.ID, gb, w.op, w.id, eb)
}
}
}
func TestBatchFileErrors(t *testing.T) {
for _, src := range []string{
"changes: [{add: {name: a}, delete: {name: b}}]", // two actions in one entry
"changes: [{}]", // no action
"changes: [{update: {data: x}}]", // update without id
} {
var b batchFile
if err := yaml.Unmarshal([]byte(src), &b); err != nil {
t.Fatal(err)
}
if _, err := b.requests(); err == nil {
t.Errorf("%s: expected an error", src)
}
}
}
func TestChallengeName(t *testing.T) {
for _, tc := range []struct {
domain string
exact bool
want string
}{
{"example.com", false, "_acme-challenge.example.com."},
{"*.example.com", false, "_acme-challenge.example.com."},
{"WWW.Example.com.", false, "_acme-challenge.www.example.com."},
{"_acme-challenge.www.example.com", false, "_acme-challenge.www.example.com."}, // acme.sh passes the full name
{"www.acme.example.com", true, "www.acme.example.com."},
} {
o := &acmeOptions{exact: tc.exact}
got, err := o.challengeName(tc.domain)
if err != nil || got != tc.want {
t.Errorf("challengeName(%q, exact=%v) = %q, %v; want %q", tc.domain, tc.exact, got, err, tc.want)
}
}
if _, err := (&acmeOptions{}).challengeName(" "); err == nil {
t.Error("empty domain accepted")
}
}
func TestListValue(t *testing.T) {
if got := listValue([]string{"192.0.2.1", " 192.0.2.2; ", "key xfer"}); got != "{ 192.0.2.1; 192.0.2.2; key xfer; }" {
t.Errorf("listValue = %q", got)
}
}
+614
View File
@@ -0,0 +1,614 @@
package main
import (
"encoding/json"
"fmt"
"io"
"net/url"
"os"
"strconv"
"strings"
"github.com/spf13/cobra"
"jarl/internal/api"
"jarl/internal/client"
)
func zoneCmd() *cobra.Command {
cmd := &cobra.Command{Use: "zone", Aliases: []string{"zones"}, Short: "Manage zones"}
var view, typ string
list := &cobra.Command{
Use: "list",
Short: "List zones",
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var zones []api.Zone
if err := c.Get(ctx(), "/zones", q("view", view, "type", typ), &zones); err != nil {
return err
}
return output(zones, func(w io.Writer) {
fmt.Fprintln(w, "ID\tZONE\tVIEW\tTYPE\tRECORDS\tSERIAL")
for _, z := range zones {
serial, recs := "", ""
if z.Type == "primary" {
serial, recs = fmt.Sprint(z.SOA.Serial), fmt.Sprint(z.Records)
}
fmt.Fprintf(w, "%d\t%s\t%s\t%s\t%s\t%s\n", z.ID, z.Display, z.View, z.Type, recs, serial)
}
})
},
}
list.Flags().StringVar(&view, "view", "", "only zones in this view")
list.Flags().StringVar(&typ, "type", "", "only zones of this type")
show := &cobra.Command{
Use: "show ZONE",
Short: "Show a zone",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
path, qv := zonePath(args[0], view)
var z api.Zone
if err := c.Get(ctx(), path, qv, &z); err != nil {
return err
}
return output(z, func(w io.Writer) {
fmt.Fprintf(w, "Zone:\t%s (id %d)\n", z.Display, z.ID)
if z.View != "" {
fmt.Fprintf(w, "View:\t%s\n", z.View)
}
fmt.Fprintf(w, "Type:\t%s\n", z.Type)
if z.Type == "primary" {
fmt.Fprintf(w, "Serial:\t%d\n", z.SOA.Serial)
fmt.Fprintf(w, "SOA:\t%s %s refresh %d retry %d expire %d minimum %d\n", z.SOA.MName, z.SOA.RName, z.SOA.Refresh, z.SOA.Retry, z.SOA.Expire, z.SOA.Minimum)
fmt.Fprintf(w, "Default TTL:\t%d\n", z.DefaultTTL)
fmt.Fprintf(w, "Records:\t%d\n", z.Records)
}
if z.InView != "" {
fmt.Fprintf(w, "In view:\t%s\n", z.InView)
}
if z.ZoneFile != "" {
fmt.Fprintf(w, "File:\t%s\n", z.ZoneFile)
}
if z.Comment != "" {
fmt.Fprintf(w, "Comment:\t%s\n", z.Comment)
}
})
},
}
show.Flags().StringVar(&view, "view", "", "view of the zone (when the name exists in several views)")
var ns, records, primaries, forwarders, opts []string
var contact, comment, cloneFrom, file, inView, forward string
var ttl uint32
create := &cobra.Command{
Use: "create NAME",
Short: "Create a zone",
Long: `Create a zone. NAME may be a network (192.168.1.0/24, 2001:db8::/48) to
create its reverse zone.
jarl zone create example.com --ns ns1.example.com. --record "ns1 A 192.0.2.1"
jarl zone create 192.168.1.0/24
jarl zone create partner.example --type secondary --primary 192.0.2.53
jarl zone create consul --type forward --forwarder "127.0.0.1 port 8600"
jarl zone create example.com --view external --clone-from example.com --clone-view internal`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
body := map[string]any{"name": args[0], "type": typ}
if view != "" {
body["view"] = view
}
if len(ns) > 0 {
body["nameservers"] = ns
}
if contact != "" {
body["soa"] = map[string]any{"rname": contact}
}
if ttl > 0 {
body["default_ttl"] = ttl
}
if comment != "" {
body["comment"] = comment
}
if file != "" {
body["file"] = file
}
if inView != "" {
body["in_view"] = inView
}
var recs []map[string]any
for _, r := range records {
f := strings.Fields(r)
if len(f) < 3 {
return fmt.Errorf("--record %q: use \"NAME TYPE DATA\"", r)
}
recs = append(recs, map[string]any{"name": f[0], "type": f[1], "data": strings.Join(f[2:], " ")})
}
if len(recs) > 0 {
body["records"] = recs
}
var zopts []map[string]string
if len(primaries) > 0 {
zopts = append(zopts, map[string]string{"name": "primaries", "value": listValue(primaries)})
}
if len(forwarders) > 0 || typ == "forward" {
zopts = append(zopts, map[string]string{"name": "forwarders", "value": listValue(forwarders)})
zopts = append(zopts, map[string]string{"name": "forward", "value": forward})
}
for _, o := range opts {
n, v, _ := strings.Cut(strings.TrimSpace(o), " ")
zopts = append(zopts, map[string]string{"name": n, "value": v})
}
if len(zopts) > 0 {
body["options"] = zopts
}
if cloneFrom != "" {
id, err := resolveZoneID(c, cloneFrom, cloneView)
if err != nil {
return err
}
body["clone_from"] = id
}
resp, err := c.Mutate(ctx(), "POST", "/zones", nil, body)
if err != nil {
return err
}
return report(resp)
},
}
create.Flags().StringVar(&view, "view", "", "create the zone in this view")
create.Flags().StringVar(&typ, "type", "primary", "zone type: primary, secondary, forward, stub, static-stub, mirror, hint, redirect, in-view")
create.Flags().StringSliceVar(&ns, "ns", nil, "name server (repeatable; default: the configured defaults)")
create.Flags().StringArrayVar(&records, "record", nil, `initial record "NAME TYPE DATA" (repeatable), e.g. glue for in-zone name servers`)
create.Flags().StringVar(&contact, "contact", "", "SOA contact email (default: the configured default)")
create.Flags().Uint32Var(&ttl, "ttl", 0, "default TTL")
create.Flags().StringArrayVar(&primaries, "primary", nil, `primary server for secondary/stub zones, e.g. "192.0.2.53 key xfer" (repeatable)`)
create.Flags().StringArrayVar(&forwarders, "forwarder", nil, `forwarder for forward zones, e.g. "192.0.2.1 port 5353" (repeatable)`)
create.Flags().StringVar(&forward, "forward", "only", "forward mode for forward zones: only or first")
create.Flags().StringArrayVar(&opts, "option", nil, `zone option "NAME VALUE" (repeatable), e.g. "allow-transfer { key xfer; }"`)
create.Flags().StringVar(&cloneFrom, "clone-from", "", "copy records from this zone (same name, other view)")
create.Flags().StringVar(&cloneView, "clone-view", "", "view of --clone-from")
create.Flags().StringVar(&file, "file", "", "zone file (hint and redirect zones)")
create.Flags().StringVar(&inView, "in-view", "", "for in-view zones: the view to share the zone from")
create.Flags().StringVar(&comment, "comment", "", "comment")
var refresh, retry, expire, minimum, serial uint32
var mname, policy, moveView string
update := &cobra.Command{
Use: "update ZONE",
Short: "Change a zone's settings (SOA, TTL, view, comment)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
body := map[string]any{}
soa := map[string]any{}
f := cmd.Flags()
if f.Changed("mname") {
soa["mname"] = mname
}
if f.Changed("contact") {
soa["rname"] = contact
}
for name, v := range map[string]uint32{"refresh": refresh, "retry": retry, "expire": expire, "minimum": minimum, "serial": serial} {
if f.Changed(name) {
soa[name] = v
}
}
if len(soa) > 0 {
body["soa"] = soa
}
if f.Changed("ttl") {
body["default_ttl"] = ttl
}
if f.Changed("serial-policy") {
body["serial_policy"] = policy
}
if f.Changed("comment") {
body["comment"] = comment
}
if f.Changed("move-to-view") {
body["view"] = moveView
}
if f.Changed("file") {
body["file"] = file
}
if len(body) == 0 {
return fmt.Errorf("nothing to change (see --help)")
}
path, qv := zonePath(args[0], view)
resp, err := c.Mutate(ctx(), "PATCH", path, qv, body)
if err != nil {
return err
}
return report(resp)
},
}
update.Flags().StringVar(&view, "view", "", "view of the zone")
update.Flags().StringVar(&mname, "mname", "", "SOA primary name server")
update.Flags().StringVar(&contact, "contact", "", "SOA contact email")
update.Flags().Uint32Var(&refresh, "refresh", 0, "SOA refresh")
update.Flags().Uint32Var(&retry, "retry", 0, "SOA retry")
update.Flags().Uint32Var(&expire, "expire", 0, "SOA expire")
update.Flags().Uint32Var(&minimum, "minimum", 0, "SOA minimum (negative caching TTL)")
update.Flags().Uint32Var(&serial, "serial", 0, "set the serial explicitly")
update.Flags().Uint32Var(&ttl, "ttl", 0, "default TTL")
update.Flags().StringVar(&policy, "serial-policy", "", "serial policy: date, increment or unixtime")
update.Flags().StringVar(&comment, "comment", "", "comment")
update.Flags().StringVar(&moveView, "move-to-view", "", "move the zone to this view")
update.Flags().StringVar(&file, "file", "", "zone file (secondary, hint and redirect zones)")
var yes bool
del := &cobra.Command{
Use: "delete ZONE",
Short: "Delete a zone and its records",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if !confirm("Delete zone "+args[0]+" and all its records?", yes) {
return fmt.Errorf("canceled")
}
c, err := newClient()
if err != nil {
return err
}
path, qv := zonePath(args[0], view)
resp, err := c.Mutate(ctx(), "DELETE", path, qv, nil)
if err != nil {
return err
}
return report(resp)
},
}
del.Flags().StringVar(&view, "view", "", "view of the zone")
del.Flags().BoolVarP(&yes, "yes", "y", false, "don't ask for confirmation")
fileCmd := &cobra.Command{
Use: "file ZONE",
Short: "Print the zone file Jarl generates",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
path, qv := zonePath(args[0], view)
var text string
if err := c.Get(ctx(), path+"/file", qv, &text); err != nil {
return err
}
fmt.Print(text)
return nil
},
}
fileCmd.Flags().StringVar(&view, "view", "", "view of the zone")
var replace, useSOA bool
importCmd := &cobra.Command{
Use: "import ZONE FILE",
Short: "Import records from a zone file ('-' reads standard input)",
Long: `Adds the records of a zone file to a zone. With --replace the zone is made
equal to the file: records not in the file are deleted.`,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
var data []byte
if args[1] == "-" {
data, err = io.ReadAll(os.Stdin)
} else {
data, err = os.ReadFile(args[1])
}
if err != nil {
return err
}
mode := "merge"
if replace {
mode = "replace"
}
path, qv := zonePath(args[0], view)
resp, err := c.Mutate(ctx(), "POST", path+"/import", qv, map[string]any{"text": string(data), "mode": mode, "use_soa": useSOA, "dry_run": flagDryRun})
if err != nil {
return err
}
if len(resp.Object) > 0 && !flagQuiet {
var o struct {
Skipped []string `json:"skipped"`
}
if jsonUnmarshal(resp.Object, &o) == nil {
for _, s := range o.Skipped {
fmt.Fprintln(os.Stderr, "skipped:", s)
}
}
}
return report(resp)
},
}
importCmd.Flags().StringVar(&view, "view", "", "view of the zone")
importCmd.Flags().BoolVar(&replace, "replace", false, "delete records that are not in the file")
importCmd.Flags().BoolVar(&useSOA, "use-soa", false, "also take SOA timers and $TTL from the file")
cmd.AddCommand(list, show, create, update, del, fileCmd, importCmd)
return cmd
}
var cloneView string
func listValue(items []string) string {
var parts []string
for _, it := range items {
it = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(it), ";"))
if it != "" {
parts = append(parts, it+";")
}
}
return "{ " + strings.Join(parts, " ") + " }"
}
// resolveZoneID looks up a zone's ID by name (or ID) and view.
func resolveZoneID(c *client.Client, zone, view string) (int64, error) {
path, qv := zonePath(zone, view)
var z api.Zone
if err := c.Get(ctx(), path, qv, &z); err != nil {
return 0, err
}
return z.ID, nil
}
func urlPathEscape(s string) string { return url.PathEscape(s) }
func jsonUnmarshal(b []byte, v any) error { return json.Unmarshal(b, v) }
// ---- records
func recordCmd() *cobra.Command {
cmd := &cobra.Command{Use: "record", Aliases: []string{"records", "rr"}, Short: "Manage records in primary zones"}
var view, name, typ, search, comment, ttlArg string
var ptr, missingOK, yes bool
var id int64
list := &cobra.Command{
Use: "list ZONE",
Short: "List records",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
path, qv := zonePath(args[0], view)
for k, v := range q("name", name, "type", strings.ToUpper(typ), "q", search) {
qv[k] = v
}
var recs []api.Record
if err := c.Get(ctx(), path+"/records", qv, &recs); err != nil {
return err
}
return output(recs, func(w io.Writer) {
fmt.Fprintln(w, "ID\tNAME\tTTL\tTYPE\tDATA\tCOMMENT")
for _, r := range recs {
ttl := fmt.Sprint(r.EffectiveTTL)
if r.TTL == nil {
ttl += "*"
}
fmt.Fprintf(w, "%d\t%s\t%s\t%s\t%s\t%s\n", r.ID, r.RelativeName, ttl, r.Type, r.Data, r.Comment)
}
})
},
}
list.Flags().StringVar(&view, "view", "", "view of the zone")
list.Flags().StringVar(&name, "name", "", "only this name")
list.Flags().StringVarP(&typ, "type", "t", "", "only this type")
list.Flags().StringVar(&search, "search", "", "only records whose name, data or comment contains this")
add := &cobra.Command{
Use: "add ZONE NAME TYPE DATA...",
Short: "Add a record",
Long: `Add a record. NAME is relative to the zone ("@" for the apex) unless it ends
with a dot. DATA is in zone file format; TXT data is plain text (quoting
and splitting are automatic).
jarl record add example.com www A 192.0.2.10 --ttl 300 --ptr
jarl record add example.com @ MX 10 mail
jarl record add example.com @ TXT "v=spf1 mx -all"
jarl record add example.com _sip._tcp SRV 0 5 5060 sip`,
Args: cobra.MinimumNArgs(4),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
body := map[string]any{"name": args[1], "type": args[2], "data": strings.Join(args[3:], " ")}
if err := setTTL(body, ttlArg); err != nil {
return err
}
if comment != "" {
body["comment"] = comment
}
if ptr {
body["ptr"] = true
}
path, qv := zonePath(args[0], view)
resp, err := c.Mutate(ctx(), "POST", path+"/records", qv, body)
if err != nil {
return err
}
return report(resp)
},
}
add.Flags().StringVar(&view, "view", "", "view of the zone")
add.Flags().StringVar(&ttlArg, "ttl", "", "TTL in seconds (default: the RRset's or the zone's)")
add.Flags().StringVar(&comment, "comment", "", "comment")
add.Flags().BoolVar(&ptr, "ptr", false, "also add the PTR record (A/AAAA)")
var data string
update := &cobra.Command{
Use: "update ID",
Short: "Change a record (see 'record list' for IDs)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
body := map[string]any{}
f := cmd.Flags()
if f.Changed("name") {
body["name"] = name
}
if f.Changed("type") {
body["type"] = typ
}
if f.Changed("data") {
body["data"] = data
}
if f.Changed("comment") {
body["comment"] = comment
}
if f.Changed("ttl") {
if err := setTTL(body, ttlArg); err != nil {
return err
}
}
if ptr {
body["ptr"] = true
}
if len(body) == 0 {
return fmt.Errorf("nothing to change (see --help)")
}
resp, err := c.Mutate(ctx(), "PATCH", "/records/"+args[0], nil, body)
if err != nil {
return err
}
return report(resp)
},
}
update.Flags().StringVar(&name, "name", "", "new name")
update.Flags().StringVarP(&typ, "type", "t", "", "new type (needs --data)")
update.Flags().StringVar(&data, "data", "", "new data")
update.Flags().StringVar(&ttlArg, "ttl", "", `new TTL, or "default" for the zone default`)
update.Flags().StringVar(&comment, "comment", "", "new comment")
update.Flags().BoolVar(&ptr, "ptr", false, "move the PTR record along (A/AAAA)")
del := &cobra.Command{
Use: "delete ZONE NAME TYPE [DATA...] | delete --id ID",
Short: "Delete records",
Long: `Delete records by name and type (all of them, or only the one with DATA),
or one record by ID.
jarl record delete example.com www A # all A records of www
jarl record delete example.com www A 192.0.2.10 # just this one
jarl record delete --id 1234`,
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
if id > 0 {
qv := q()
if ptr {
qv.Set("ptr", "1")
}
resp, err := c.Mutate(ctx(), "DELETE", "/records/"+strconv.FormatInt(id, 10), qv, nil)
if err != nil {
return err
}
return report(resp)
}
if len(args) < 3 {
return fmt.Errorf("give ZONE NAME TYPE [DATA], or --id")
}
if len(args) == 3 && !confirm(fmt.Sprintf("Delete all %s records of %s?", strings.ToUpper(args[2]), args[1]), yes) {
return fmt.Errorf("canceled")
}
path, qv := zonePath(args[0], view)
qv.Set("name", args[1])
qv.Set("type", args[2])
if len(args) > 3 {
qv.Set("data", strings.Join(args[3:], " "))
}
if missingOK {
qv.Set("missing_ok", "1")
}
if ptr {
qv.Set("ptr", "1")
}
resp, err := c.Mutate(ctx(), "DELETE", path+"/records", qv, nil)
if err != nil {
return err
}
return report(resp)
},
}
del.Flags().StringVar(&view, "view", "", "view of the zone")
del.Flags().Int64Var(&id, "id", 0, "delete the record with this ID")
del.Flags().BoolVar(&missingOK, "missing-ok", false, "succeed when nothing matches")
del.Flags().BoolVar(&ptr, "ptr", false, "also delete the matching PTR record (A/AAAA)")
del.Flags().BoolVarP(&yes, "yes", "y", false, "don't ask before deleting a whole RRset")
set := &cobra.Command{
Use: "set ZONE NAME TYPE DATA [DATA...]",
Short: "Make NAME/TYPE have exactly these records (each DATA argument is one record)",
Long: `Replaces the whole RRset. Each DATA argument is one record; quote data with
spaces.
jarl record set example.com api A 192.0.2.30 192.0.2.31 --ttl 60
jarl record set example.com @ MX "10 mail1" "20 mail2"`,
Args: cobra.MinimumNArgs(4),
RunE: func(cmd *cobra.Command, args []string) error {
c, err := newClient()
if err != nil {
return err
}
body := map[string]any{"data": args[3:]}
if err := setTTL(body, ttlArg); err != nil {
return err
}
if comment != "" {
body["comment"] = comment
}
path, qv := zonePath(args[0], view)
resp, err := c.Mutate(ctx(), "PUT", path+"/rrsets/"+urlPathEscape(args[1])+"/"+urlPathEscape(args[2]), qv, body)
if err != nil {
return err
}
return report(resp)
},
}
set.Flags().StringVar(&view, "view", "", "view of the zone")
set.Flags().StringVar(&ttlArg, "ttl", "", "TTL for the RRset")
set.Flags().StringVar(&comment, "comment", "", "comment for new records")
cmd.AddCommand(list, add, update, del, set)
return cmd
}
func setTTL(body map[string]any, ttl string) error {
switch ttl {
case "":
case "default", "zone", "inherit":
body["ttl"] = nil
default:
n, err := strconv.ParseUint(ttl, 10, 32)
if err != nil {
return fmt.Errorf("invalid TTL %q", ttl)
}
body["ttl"] = n
}
return nil
}
+408
View File
@@ -0,0 +1,408 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"syscall"
"github.com/spf13/cobra"
"jarl/internal/config"
"jarl/internal/engine"
"jarl/internal/render"
"jarl/internal/validate"
"jarl/internal/version"
)
// dirOwner restores file ownership after commands run as root.
type dirOwner struct {
uid, gid int
active bool
}
func newDirOwner(dir string) *dirOwner {
o := &dirOwner{}
if os.Geteuid() != 0 {
return o
}
fi, err := os.Stat(dir)
if err != nil {
return o
}
if st, ok := fi.Sys().(*syscall.Stat_t); ok && st.Uid != 0 {
o.uid, o.gid, o.active = int(st.Uid), int(st.Gid), true
}
return o
}
// fix gives root-owned files under dirs to the daemon's user (keeping
// their group, which matters for named).
func (o *dirOwner) fix(dirs ...string) {
if !o.active {
return
}
for _, d := range dirs {
filepath.WalkDir(d, func(path string, de fs.DirEntry, err error) error {
if err != nil {
return nil
}
info, err := de.Info()
if err != nil {
return nil
}
if st, ok := info.Sys().(*syscall.Stat_t); ok && st.Uid == 0 {
gid := int(st.Gid)
if path == d || strings.HasSuffix(path, ".db") || strings.Contains(path, ".db-") {
gid = o.gid
}
os.Lchown(path, o.uid, gid)
}
return nil
})
}
}
func printJSON(v any) {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
enc.Encode(v)
}
func printProblems(ps []validate.Problem) {
for _, p := range ps {
fmt.Println(" " + p.String())
}
}
func printResult(res *engine.Result) {
if res == nil {
return
}
if len(res.Problems) > 0 {
fmt.Println("Problems:")
printProblems(res.Problems)
}
for _, m := range res.Check {
if m.Error {
obj := ""
if m.Object != "" {
obj = " [" + m.Object + "]"
}
fmt.Printf(" named-checkconf: %s%s\n", m.Text, obj)
}
}
for _, w := range res.Warnings {
fmt.Println("warning:", w)
}
for _, d := range res.Drift {
fmt.Printf("drift: %s (%s)\n", d.Path, d.Reason)
}
}
func importCmd() *cobra.Command {
var from string
var dryRun, asJSON bool
cmd := &cobra.Command{
Use: "import",
Short: "Import the existing BIND configuration into Jarl",
Long: `Reads named.conf (following includes) and all primary zone files into
Jarl. Key files used by rndc (rndc.key) stay as include statements.
If the imported configuration is valid it is applied right away: Jarl
writes its own files (bind.config_dir, bind.zone_dir), but named keeps
running on the old configuration until you run 'jarld adopt'. If there
are problems, the import is kept as an open changeset that you can fix in
the web UI or with the CLI.`,
RunE: func(cmd *cobra.Command, args []string) error {
a, err := openApp(true)
if err != nil {
return err
}
defer a.close()
ctx := context.Background()
if from == "" {
from = a.cfg.BIND.MainConfig
}
p, err := a.localPrincipal(ctx, "")
if err != nil {
return err
}
res, err := a.eng.Import(ctx, from, p, dryRun)
if err != nil {
return err
}
if asJSON {
printJSON(res)
return nil
}
rep := res.Report
fmt.Printf("Read %s:\n", from)
fmt.Printf(" %d views, %d zones, %d records, %d ACLs, %d TSIG keys, %d options\n",
rep.Counts["views"], rep.Counts["zones"], rep.Counts["records"], rep.Counts["acls"], rep.Counts["tsig_keys"], rep.Counts["options"])
for _, z := range rep.Zones {
view := ""
if z.View != "" {
view = " [view " + z.View + "]"
}
extra := ""
if z.Skipped > 0 {
extra = fmt.Sprintf(", %d skipped", z.Skipped)
}
fmt.Printf(" zone %-35s %-10s %4d records%s\n", z.Name+view, z.Type, z.Records, extra)
}
for _, k := range rep.Kept {
fmt.Printf(" kept as include: %s\n", k)
}
for _, w := range rep.Warnings {
fmt.Println("warning:", w)
}
if len(rep.Skipped) > 0 {
fmt.Println("Not imported:")
for _, s := range rep.Skipped {
fmt.Println(" " + s)
}
}
if dryRun {
fmt.Printf("\nDry run: %d operations would be applied; nothing was changed.\n", len(res.Changeset.Ops))
return nil
}
if !res.Applied {
fmt.Printf("\nThe import is saved as changeset #%d but was NOT applied:\n", res.Changeset.ID)
if res.Result != nil && res.Result.Error != nil {
fmt.Println(" " + res.Result.Error.Message)
}
printResult(res.Result)
fmt.Println("\nFix the problems (web UI: Changes, or 'jarl changeset show " + fmt.Sprint(res.Changeset.ID) + "'), apply the changeset, then run 'jarld adopt'.")
return nil
}
printResult(res.Result)
fmt.Printf("\nImported and applied as changeset #%d. Jarl's files are in %s and %s.\n", res.Result.ChangesetID, a.cfg.BIND.ConfigDir, a.cfg.BIND.ZoneDir)
fmt.Println("named still uses the old configuration. Review Jarl's files, then switch named over with:")
fmt.Println("\n sudo jarld adopt")
return nil
},
}
cmd.Flags().StringVar(&from, "from", "", "named.conf to import (default: bind.main_config)")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "only show what would be imported")
cmd.Flags().BoolVar(&asJSON, "json", false, "print the result as JSON")
return cmd
}
func adoptCmd() *cobra.Command {
return &cobra.Command{
Use: "adopt",
Short: "Switch named over to Jarl's configuration (run as root)",
Long: `Makes named load Jarl's configuration:
1. bumps the serial of every primary zone,
2. saves bind.main_config (e.g. /etc/bind/named.conf) as
named.conf.pre-jarl-<date> and replaces it with a single include of
Jarl's named.conf,
3. runs named-checkconf, rndc reconfig and reloads every zone,
4. checks that named serves every zone from Jarl's files.
If anything fails the previous named.conf is restored. Writing
named.conf needs root.`,
RunE: func(cmd *cobra.Command, args []string) error {
a, err := openApp(true)
if err != nil {
return err
}
defer a.close()
ctx := context.Background()
p, err := a.localPrincipal(ctx, "")
if err != nil {
return err
}
res, err := a.eng.Adopt(ctx, p)
if err != nil {
if ee, ok := engine.AsError(err); ok && len(ee.Problems) > 0 {
fmt.Println("Problems:")
printProblems(ee.Problems)
}
return err
}
if res.Already {
fmt.Printf("named already loads Jarl's configuration (%s includes %s).\n", res.MainConfig, filepath.Join(a.cfg.BIND.ConfigDir, "named.conf"))
return nil
}
fmt.Printf("named now loads Jarl's configuration.\n %s includes %s\n previous configuration saved as %s\n", res.MainConfig, filepath.Join(a.cfg.BIND.ConfigDir, "named.conf"), res.Backup)
for _, s := range res.Serials {
fmt.Printf(" zone %s serial %d -> %d\n", strings.TrimSuffix(s.Zone, "."), s.Old, s.New)
}
fmt.Println("\nFrom now on, change DNS only through Jarl. To go back: restore the saved file and run 'rndc reconfig'.")
return nil
},
}
}
func checkCmd() *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "check",
Short: "Validate the current configuration and run named-checkconf on it",
RunE: func(cmd *cobra.Command, args []string) error {
a, err := openApp(true)
if err != nil {
return err
}
defer a.close()
res, err := a.eng.CheckCurrent(context.Background())
if err != nil {
return err
}
if asJSON {
printJSON(res)
} else {
printResult(res)
if res.Diff != "" {
fmt.Println("Files on disk differ from the configuration; 'jarld resync' rewrites them:")
fmt.Print(res.Diff)
}
}
if !res.Valid {
return fmt.Errorf("the configuration has errors")
}
if !asJSON {
fmt.Println("OK: the configuration is valid and named-checkconf accepts it.")
}
return nil
},
}
cmd.Flags().BoolVar(&asJSON, "json", false, "print the result as JSON")
return cmd
}
func renderCmd() *cobra.Command {
var out string
cmd := &cobra.Command{
Use: "render",
Short: "Write the generated configuration to a directory (for inspection)",
RunE: func(cmd *cobra.Command, args []string) error {
if out == "" {
return fmt.Errorf("--out is required")
}
a, err := openApp(true)
if err != nil {
return err
}
defer a.store.Close()
st, err := a.store.LoadState(context.Background())
if err != nil {
return err
}
paths := render.Paths{ConfigDir: filepath.Join(out, "config"), ZoneDir: filepath.Join(out, "zones"), CacheDir: filepath.Join(out, "cache")}
o := render.Render(st, paths)
for _, f := range o.Files {
if err := os.MkdirAll(filepath.Dir(f.Path), 0o750); err != nil {
return err
}
if err := os.WriteFile(f.Path, f.Content, 0o640); err != nil {
return err
}
fmt.Println(f.Path)
}
return nil
},
}
cmd.Flags().StringVarP(&out, "out", "o", "", "output directory")
return cmd
}
func resyncCmd() *cobra.Command {
var force, dryRun bool
cmd := &cobra.Command{
Use: "resync",
Short: "Rewrite all generated files from the database and reload named",
RunE: func(cmd *cobra.Command, args []string) error {
a, err := openApp(true)
if err != nil {
return err
}
defer a.close()
ctx := context.Background()
p, err := a.localPrincipal(ctx, "")
if err != nil {
return err
}
res, err := a.eng.Resync(ctx, p, engine.ApplyOptions{Force: force, DryRun: dryRun})
printResult(res)
if err != nil {
return err
}
if res.Diff != "" {
fmt.Print(res.Diff)
}
if dryRun {
fmt.Printf("Dry run: %d files would be written.\n", len(res.Files))
} else {
fmt.Printf("%d files written; named reloaded: %v\n", len(res.Files), res.Reloaded)
}
return nil
},
}
cmd.Flags().BoolVar(&force, "force", false, "overwrite files changed outside Jarl")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "only show what would change")
return cmd
}
func backupCmd() *cobra.Command {
return &cobra.Command{
Use: "backup FILE",
Short: "Write a consistent copy of the database to FILE (safe while jarld runs)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
a, err := openApp(true)
if err != nil {
return err
}
defer a.close()
if _, err := os.Stat(args[0]); err == nil {
return fmt.Errorf("%s already exists", args[0])
}
if err := a.store.Backup(context.Background(), args[0]); err != nil {
return err
}
os.Chmod(args[0], 0o600)
fmt.Println("Database copied to", args[0])
return nil
},
}
}
func configCmd() *cobra.Command {
var example bool
cmd := &cobra.Command{
Use: "config",
Short: "Show the effective configuration (or an example file)",
RunE: func(cmd *cobra.Command, args []string) error {
if example {
fmt.Print(config.Example)
return nil
}
cfg, err := config.Load(configPath, true)
if err != nil {
return err
}
printJSON(cfg)
return nil
},
}
cmd.Flags().BoolVar(&example, "example", false, "print a commented example configuration file")
return cmd
}
func versionCmd() *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Print the version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("jarld", version.Version)
},
}
}
+502
View File
@@ -0,0 +1,502 @@
// Command jarld is the Jarl daemon: it serves the web UI and the REST API
// and writes BIND's configuration. It also has administrative subcommands
// for setting up and migrating a server.
package main
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"log/slog"
"net"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/spf13/cobra"
"golang.org/x/term"
"jarl/internal/auth"
"jarl/internal/bind"
"jarl/internal/config"
"jarl/internal/engine"
"jarl/internal/model"
"jarl/internal/render"
"jarl/internal/server"
"jarl/internal/store"
"jarl/internal/version"
"jarl/internal/web"
)
func main() {
if err := rootCmd().Execute(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
var configPath string
func rootCmd() *cobra.Command {
root := &cobra.Command{
Use: "jarld",
Short: "Jarl: manage BIND (named) through a web UI, a REST API and a CLI",
SilenceUsage: true,
SilenceErrors: true,
Version: version.Version,
}
def := os.Getenv("JARL_CONFIG")
if def == "" {
def = config.DefaultPath
}
root.PersistentFlags().StringVarP(&configPath, "config", "c", def, "configuration file")
root.AddCommand(serveCmd(), initCmd(), userCmd(), importCmd(), adoptCmd(), checkCmd(), renderCmd(), resyncCmd(), backupCmd(), configCmd(), versionCmd())
return root
}
// app holds what most commands need.
type app struct {
cfg *config.Config
log *slog.Logger
store *store.Store
eng *engine.Engine
owner *dirOwner
}
func newLogger(cfg *config.Config, w io.Writer) *slog.Logger {
var level slog.Level
switch strings.ToLower(cfg.Log.Level) {
case "debug":
level = slog.LevelDebug
case "warn", "warning":
level = slog.LevelWarn
case "error":
level = slog.LevelError
default:
level = slog.LevelInfo
}
opts := &slog.HandlerOptions{Level: level}
if cfg.Log.Format == "json" {
return slog.New(slog.NewJSONHandler(w, opts))
}
// systemd's journal adds timestamps.
if os.Getenv("JOURNAL_STREAM") != "" {
opts.ReplaceAttr = func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
}
}
return slog.New(slog.NewTextHandler(w, opts))
}
func openApp(allowMissingConfig bool) (*app, error) {
cfg, err := config.Load(configPath, allowMissingConfig)
if err != nil {
return nil, fmt.Errorf("loading configuration: %w", err)
}
log := newLogger(cfg, os.Stderr)
owner := newDirOwner(filepath.Dir(cfg.Database))
if err := os.MkdirAll(filepath.Dir(cfg.Database), 0o750); err != nil {
return nil, err
}
st, err := store.Open(cfg.Database)
if err != nil {
return nil, fmt.Errorf("opening database %s: %w", cfg.Database, err)
}
tools := &bind.Tools{NamedCheckConf: cfg.BIND.NamedCheckConf, NamedCheckZone: cfg.BIND.NamedCheckZone, RNDC: cfg.BIND.RNDC, RNDCArgs: cfg.BIND.RNDCArgs}
eng := engine.New(st, tools, engine.Config{
Paths: render.Paths{ConfigDir: cfg.BIND.ConfigDir, ZoneDir: cfg.BIND.ZoneDir, CacheDir: cfg.BIND.CacheDir},
MainConfig: cfg.BIND.MainConfig,
StagingDir: cfg.StagingDir,
FileGroup: cfg.BIND.FileGroup,
ReloadTimeout: time.Duration(cfg.BIND.ReloadTimeout),
NoReload: cfg.BIND.NoReload,
}, log)
return &app{cfg: cfg, log: log, store: st, eng: eng, owner: owner}, nil
}
func (a *app) close() {
a.store.Close()
// Commands run as root must not leave root-owned files where the
// daemon (running as its own user) needs to write.
a.owner.fix(filepath.Dir(a.cfg.Database), a.cfg.StagingDir, a.cfg.BIND.ConfigDir, a.cfg.BIND.ZoneDir, a.cfg.BIND.CacheDir)
}
// localPrincipal is used for administrative commands run on the server.
func (a *app) localPrincipal(ctx context.Context, username string) (*auth.Principal, error) {
if username == "" {
username = os.Getenv("SUDO_USER")
}
if username != "" {
if u, err := a.store.GetUserByName(ctx, username); err == nil {
if !u.Admin {
return nil, fmt.Errorf("user %s is not an administrator", username)
}
return &auth.Principal{User: u, Method: "local"}, nil
}
}
// Fall back to the first administrator, or a synthetic one.
users, err := a.store.ListUsers(ctx)
if err != nil {
return nil, err
}
for _, u := range users {
if u.Admin && !u.Disabled {
return &auth.Principal{User: &model.User{ID: u.ID, Username: u.Username + " (local)", Admin: true}, Method: "local"}, nil
}
}
return &auth.Principal{User: &model.User{Username: "local", Admin: true}, Method: "local"}, nil
}
// ---- serve
func serveCmd() *cobra.Command {
return &cobra.Command{
Use: "serve",
Short: "Run the daemon (web UI and API)",
RunE: func(cmd *cobra.Command, args []string) error {
a, err := openApp(true)
if err != nil {
return err
}
defer a.close()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if users, err := a.store.ListUsers(ctx); err == nil && len(users) == 0 {
a.log.Warn("there are no users yet; create an administrator with 'jarld init' or 'jarld user add --admin NAME'")
}
if ok, err := a.eng.Adopted(); err == nil && !ok {
a.log.Warn("named does not load Jarl's configuration yet; changes are written but named is not reloaded until 'jarld adopt' runs", "main_config", a.cfg.BIND.MainConfig)
}
srv := server.New(server.Config{
Listen: a.cfg.Listen, TLSCertFile: a.cfg.TLS.CertFile, TLSKeyFile: a.cfg.TLS.KeyFile,
TrustedProxies: a.cfg.Proxies(), SessionLifetime: time.Duration(a.cfg.Session.Lifetime),
SessionIdle: time.Duration(a.cfg.Session.IdleTimeout), CookieSecure: a.cfg.Session.CookieSecure,
Version: version.Version,
}, a.eng, a.log, web.FS())
hup := make(chan os.Signal, 1)
signal.Notify(hup, syscall.SIGHUP)
go func() {
for range hup {
sdNotify("RELOADING=1")
srv.ReloadTLS()
sdNotify("READY=1")
}
}()
go auditRetention(ctx, a)
a.log.Info("jarld starting", "version", version.Version, "database", a.cfg.Database, "bind_config", a.cfg.BIND.ConfigDir)
err = srv.Serve(ctx, func() { sdNotify("READY=1\nSTATUS=serving") })
sdNotify("STOPPING=1")
a.log.Info("jarld stopped")
return err
},
}
}
func auditRetention(ctx context.Context, a *app) {
if a.cfg.Audit.RetentionDays <= 0 {
return
}
t := time.NewTicker(6 * time.Hour)
defer t.Stop()
for {
before := time.Now().Add(-time.Duration(a.cfg.Audit.RetentionDays) * 24 * time.Hour)
if n, err := a.store.PruneAudit(ctx, before); err != nil {
a.log.Warn("pruning audit log failed", "err", err)
} else if n > 0 {
a.log.Info("pruned audit log", "events", n)
}
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}
// sdNotify tells systemd about state changes (Type=notify).
func sdNotify(state string) {
sock := os.Getenv("NOTIFY_SOCKET")
if sock == "" {
return
}
addr := &net.UnixAddr{Name: sock, Net: "unixgram"}
if strings.HasPrefix(sock, "@") {
addr.Name = "\x00" + sock[1:]
}
c, err := net.DialUnix("unixgram", nil, addr)
if err != nil {
return
}
defer c.Close()
c.Write([]byte(state))
}
// ---- init and users
func readPassword(prompt string, fromStdin bool) (string, error) {
if fromStdin || !term.IsTerminal(int(os.Stdin.Fd())) {
line, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
return "", err
}
return strings.TrimRight(line, "\r\n"), nil
}
fmt.Fprint(os.Stderr, prompt)
b, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Fprintln(os.Stderr)
if err != nil {
return "", err
}
fmt.Fprint(os.Stderr, "Repeat: ")
b2, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Fprintln(os.Stderr)
if err != nil {
return "", err
}
if string(b) != string(b2) {
return "", errors.New("passwords don't match")
}
return string(b), nil
}
func createToken(ctx context.Context, a *app, u *model.User, name string) (string, error) {
secret, pid, hash := auth.NewToken()
if err := a.store.CreateToken(ctx, &model.Token{UserID: u.ID, Name: name, PublicID: pid, SecretHash: hash}); err != nil {
return "", err
}
return secret, nil
}
func initCmd() *cobra.Command {
var username string
var stdin, withToken bool
var nameservers []string
var rname string
cmd := &cobra.Command{
Use: "init",
Short: "Create the database, the first administrator and default server options",
Long: `Creates Jarl's database with a first administrator account.
Jarl starts empty. Either import your existing BIND configuration with
'jarld import', or build one from scratch in the web UI.`,
RunE: func(cmd *cobra.Command, args []string) error {
a, err := openApp(true)
if err != nil {
return err
}
defer a.close()
ctx := context.Background()
users, err := a.store.ListUsers(ctx)
if err != nil {
return err
}
if len(users) > 0 {
return fmt.Errorf("Jarl is already initialized (%d users); use 'jarld user add' to add users", len(users))
}
pw, err := readPassword("Password for "+username+": ", stdin)
if err != nil {
return err
}
hash, err := auth.HashPassword(pw)
if err != nil {
return err
}
u := &model.User{Username: username, PasswordHash: hash, Admin: true, Comment: "created by jarld init"}
if err := a.store.CreateUser(ctx, u); err != nil {
return err
}
p := &auth.Principal{User: u, Method: "local"}
set := engine.SettingsInput{}
if len(nameservers) > 0 {
set.Nameservers = &nameservers
}
if rname != "" {
set.RName = &rname
}
if set.Nameservers != nil || set.RName != nil {
if _, err := a.eng.Submit(ctx, []engine.Request{engine.NewRequest(engine.OpSettingsUpdate, 0, set)}, p, "cli", "initial settings", engine.ApplyOptions{NoReload: true}); err != nil {
return err
}
}
a.eng.Audit(ctx, p, "system.init", "user", u.ID, u.Username, "success", "")
fmt.Printf("Created administrator %q in %s.\n", u.Username, a.cfg.Database)
if withToken {
tok, err := createToken(ctx, a, u, "cli")
if err != nil {
return err
}
fmt.Printf("\nAPI token for the CLI (shown only once):\n\n %s\n\n", tok)
}
fmt.Println("\nNext steps:")
fmt.Println(" 1. Import your current BIND configuration: sudo -u jarl jarld import")
fmt.Println(" 2. Switch named over to Jarl: sudo jarld adopt")
fmt.Println(" 3. Start the daemon: sudo systemctl enable --now jarl")
return nil
},
}
cmd.Flags().StringVarP(&username, "user", "u", "admin", "administrator username")
cmd.Flags().BoolVar(&stdin, "password-stdin", false, "read the password from standard input")
cmd.Flags().BoolVar(&withToken, "token", false, "also create an API token for the CLI")
cmd.Flags().StringSliceVar(&nameservers, "nameservers", nil, "default name servers for new zones (e.g. ns1.example.com.)")
cmd.Flags().StringVar(&rname, "contact", "", "default SOA contact for new zones (e.g. hostmaster@example.com)")
return cmd
}
func userCmd() *cobra.Command {
cmd := &cobra.Command{Use: "user", Short: "Manage users locally (for bootstrapping and recovery)"}
var admin, stdin, withToken, service bool
var grants []string
add := &cobra.Command{
Use: "add NAME",
Short: "Create a user",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
a, err := openApp(true)
if err != nil {
return err
}
defer a.close()
ctx := context.Background()
u := &model.User{Username: args[0], Admin: admin}
for _, g := range grants {
gr, err := auth.ParseGrant(g)
if err != nil {
return fmt.Errorf("grant %q: %w", g, err)
}
u.Grants = append(u.Grants, gr)
}
if !service {
pw, err := readPassword("Password for "+u.Username+": ", stdin)
if err != nil {
return err
}
if u.PasswordHash, err = auth.HashPassword(pw); err != nil {
return err
}
}
if err := a.store.CreateUser(ctx, u); err != nil {
return err
}
a.eng.Audit(ctx, &auth.Principal{User: &model.User{Username: "local"}, Method: "local"}, "user.create", "user", u.ID, u.Username, "success", "jarld user add")
fmt.Printf("Created user %s.\n", u.Username)
if withToken {
tok, err := createToken(ctx, a, u, "cli")
if err != nil {
return err
}
fmt.Printf("API token (shown only once): %s\n", tok)
}
return nil
},
}
add.Flags().BoolVar(&admin, "admin", false, "make the user an administrator")
add.Flags().BoolVar(&stdin, "password-stdin", false, "read the password from standard input")
add.Flags().BoolVar(&withToken, "token", false, "also create an API token")
add.Flags().BoolVar(&service, "service", false, "service account without password (API tokens only)")
add.Flags().StringArrayVar(&grants, "grant", nil, `permission, e.g. "records:write zones=example.com" (repeatable)`)
passwd := &cobra.Command{
Use: "passwd NAME",
Short: "Set a user's password (and enable the account)",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
a, err := openApp(true)
if err != nil {
return err
}
defer a.close()
ctx := context.Background()
u, err := a.store.GetUserByName(ctx, args[0])
if err != nil {
return fmt.Errorf("user %s: %w", args[0], err)
}
pw, err := readPassword("New password for "+u.Username+": ", stdin)
if err != nil {
return err
}
if u.PasswordHash, err = auth.HashPassword(pw); err != nil {
return err
}
u.Disabled = false
if err := a.store.UpdateUser(ctx, u); err != nil {
return err
}
a.store.DeleteUserSessions(ctx, u.ID, "")
a.eng.Audit(ctx, &auth.Principal{User: &model.User{Username: "local"}, Method: "local"}, "user.password", "user", u.ID, u.Username, "success", "jarld user passwd")
fmt.Printf("Password of %s changed.\n", u.Username)
return nil
},
}
passwd.Flags().BoolVar(&stdin, "password-stdin", false, "read the password from standard input")
token := &cobra.Command{
Use: "token NAME [TOKEN-NAME]",
Short: "Create an API token for a user",
Args: cobra.RangeArgs(1, 2),
RunE: func(cmd *cobra.Command, args []string) error {
a, err := openApp(true)
if err != nil {
return err
}
defer a.close()
ctx := context.Background()
u, err := a.store.GetUserByName(ctx, args[0])
if err != nil {
return fmt.Errorf("user %s: %w", args[0], err)
}
name := "cli"
if len(args) > 1 {
name = args[1]
}
tok, err := createToken(ctx, a, u, name)
if err != nil {
return err
}
fmt.Println(tok)
return nil
},
}
list := &cobra.Command{
Use: "list",
Short: "List users",
RunE: func(cmd *cobra.Command, args []string) error {
a, err := openApp(true)
if err != nil {
return err
}
defer a.close()
users, err := a.store.ListUsers(context.Background())
if err != nil {
return err
}
for _, u := range users {
flags := []string{}
if u.Admin {
flags = append(flags, "admin")
}
if u.Disabled {
flags = append(flags, "disabled")
}
if !u.HasPassword {
flags = append(flags, "no password")
}
var gs []string
for _, g := range u.Grants {
gs = append(gs, auth.FormatGrant(g))
}
fmt.Printf("%-20s %-25s %s\n", u.Username, strings.Join(flags, ","), strings.Join(gs, "; "))
}
return nil
},
}
cmd.AddCommand(add, passwd, token, list)
return cmd
}