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:
commit
bd6b8778e4
122 files changed
+29217
No files matched your search
@@ -0,0 +1,144 @@
|
||||
// Package auth handles passwords, API tokens, sessions and permissions.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base32"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// Argon2id parameters (OWASP recommendation: m=19 MiB, t=2, p=1).
|
||||
const (
|
||||
argonTime = 2
|
||||
argonMemory = 19 * 1024
|
||||
argonThreads = 1
|
||||
argonKeyLen = 32
|
||||
saltLen = 16
|
||||
)
|
||||
|
||||
// MinPasswordLength is the shortest accepted password.
|
||||
const MinPasswordLength = 8
|
||||
|
||||
// HashPassword returns an argon2id hash in PHC string format.
|
||||
func HashPassword(password string) (string, error) {
|
||||
if len(password) < MinPasswordLength {
|
||||
return "", fmt.Errorf("password must be at least %d characters", MinPasswordLength)
|
||||
}
|
||||
salt := make([]byte, saltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, argonMemory, argonTime, argonThreads,
|
||||
base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(key)), nil
|
||||
}
|
||||
|
||||
// dummyHash is verified against when a user doesn't exist, so a login
|
||||
// attempt takes the same time whether or not the username is valid.
|
||||
var dummyHash, _ = HashPassword("not-a-real-password")
|
||||
|
||||
// CheckPassword reports whether password matches hash. An empty hash
|
||||
// never matches (the time spent is the same).
|
||||
func CheckPassword(hash, password string) bool {
|
||||
if hash == "" {
|
||||
hash = dummyHash
|
||||
password = "\x00" + password
|
||||
}
|
||||
parts := strings.Split(hash, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false
|
||||
}
|
||||
var m, t uint32
|
||||
var p uint8
|
||||
for _, kv := range strings.Split(parts[3], ",") {
|
||||
k, v, _ := strings.Cut(kv, "=")
|
||||
n, err := strconv.ParseUint(v, 10, 32)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
switch k {
|
||||
case "m":
|
||||
m = uint32(n)
|
||||
case "t":
|
||||
t = uint32(n)
|
||||
case "p":
|
||||
p = uint8(n)
|
||||
}
|
||||
}
|
||||
salt, err1 := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
want, err2 := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err1 != nil || err2 != nil || m == 0 || t == 0 || p == 0 {
|
||||
return false
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, t, m, p, uint32(len(want)))
|
||||
return subtle.ConstantTimeCompare(got, want) == 1
|
||||
}
|
||||
|
||||
var b32 = base32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567").WithPadding(base32.NoPadding)
|
||||
|
||||
func randomString(nbytes int) string {
|
||||
b := make([]byte, nbytes)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return b32.EncodeToString(b)
|
||||
}
|
||||
|
||||
// TokenPrefix starts every Jarl API token, which makes leaked tokens easy
|
||||
// to recognize (and to find with secret scanners).
|
||||
const TokenPrefix = "jarl_"
|
||||
|
||||
// NewToken generates a token: the full secret string to give to the user,
|
||||
// its public ID (stored in clear) and the hash of the secret part.
|
||||
func NewToken() (token, publicID, secretHash string) {
|
||||
publicID = randomString(10) // 16 chars
|
||||
secret := randomString(20) // 32 chars
|
||||
return TokenPrefix + publicID + "_" + secret, publicID, HashSecret(secret)
|
||||
}
|
||||
|
||||
// ParseToken splits a token into its public ID and secret.
|
||||
func ParseToken(token string) (publicID, secret string, err error) {
|
||||
rest, ok := strings.CutPrefix(strings.TrimSpace(token), TokenPrefix)
|
||||
if !ok {
|
||||
return "", "", errors.New("not a Jarl token")
|
||||
}
|
||||
publicID, secret, ok = strings.Cut(rest, "_")
|
||||
if !ok || len(publicID) != 16 || len(secret) != 32 {
|
||||
return "", "", errors.New("malformed token")
|
||||
}
|
||||
return publicID, secret, nil
|
||||
}
|
||||
|
||||
// HashSecret hashes a high-entropy secret (tokens, session IDs).
|
||||
func HashSecret(secret string) string {
|
||||
h := sha256.Sum256([]byte(secret))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
// CheckSecret compares a secret with a stored hash in constant time.
|
||||
func CheckSecret(secret, hash string) bool {
|
||||
return subtle.ConstantTimeCompare([]byte(HashSecret(secret)), []byte(hash)) == 1
|
||||
}
|
||||
|
||||
// NewSessionID returns a new session ID and CSRF token.
|
||||
func NewSessionID() (id, csrf string) {
|
||||
return randomString(32), randomString(32)
|
||||
}
|
||||
|
||||
// GenerateTSIGSecret returns a random base64 secret of n bytes.
|
||||
func GenerateTSIGSecret(n int) string {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"jarl/internal/model"
|
||||
)
|
||||
|
||||
func TestPasswords(t *testing.T) {
|
||||
h, err := HashPassword("correct horse battery")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(h, "$argon2id$v=19$m=19456,t=2,p=1$") {
|
||||
t.Errorf("hash format %q", h)
|
||||
}
|
||||
if !CheckPassword(h, "correct horse battery") || CheckPassword(h, "wrong horse battery") {
|
||||
t.Error("CheckPassword wrong")
|
||||
}
|
||||
if CheckPassword("", "anything") || CheckPassword("garbage", "x") {
|
||||
t.Error("bad hash accepted")
|
||||
}
|
||||
if _, err := HashPassword("short"); err == nil {
|
||||
t.Error("short password accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokens(t *testing.T) {
|
||||
tok, pid, hash := NewToken()
|
||||
if !strings.HasPrefix(tok, "jarl_") || len(tok) != len("jarl_")+16+1+32 {
|
||||
t.Fatalf("token %q", tok)
|
||||
}
|
||||
p, secret, err := ParseToken(tok)
|
||||
if err != nil || p != pid || !CheckSecret(secret, hash) {
|
||||
t.Fatalf("ParseToken: %v %v", p, err)
|
||||
}
|
||||
if CheckSecret(secret+"x", hash) {
|
||||
t.Error("wrong secret accepted")
|
||||
}
|
||||
for _, bad := range []string{"", "abc", "jarl_short_x", "Bearer " + tok} {
|
||||
if _, _, err := ParseToken(bad); err == nil {
|
||||
t.Errorf("ParseToken(%q) accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseGrant(t *testing.T) {
|
||||
g, err := ParseGrant("records:write zones=Example.COM. names=_acme-challenge.* types=txt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if g.Zones[0] != "example.com" || g.Types[0] != "TXT" || g.Names[0] != "_acme-challenge.*" {
|
||||
t.Errorf("grant = %+v", g)
|
||||
}
|
||||
if FormatGrant(g) != "records:write zones=example.com names=_acme-challenge.* types=TXT" {
|
||||
t.Errorf("FormatGrant = %q", FormatGrant(g))
|
||||
}
|
||||
for _, bad := range []string{"", "records", "records:admin", "bogus:read", "acls:write names=x", "records:read color=red", "options:read zones=x"} {
|
||||
if _, err := ParseGrant(bad); err == nil {
|
||||
t.Errorf("ParseGrant(%q) accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPermissions(t *testing.T) {
|
||||
acme, _ := ParseGrant("records:write zones=example.com names=_acme-challenge.* types=TXT")
|
||||
reader, _ := ParseGrant("*:read")
|
||||
u := &model.User{Username: "bot", Grants: []model.Grant{acme, reader}}
|
||||
p := &Principal{User: u}
|
||||
allow := []Action{
|
||||
{Resource: ResRecords, Write: true, Zone: "example.com.", Name: "_acme-challenge.www.example.com.", Type: "TXT"},
|
||||
{Resource: ResRecords, Write: true, Zone: "example.com.", Name: "_acme-challenge.example.com.", Type: "txt"},
|
||||
{Resource: ResRecords, Zone: "other.org.", Name: "www.other.org.", Type: "A"},
|
||||
{Resource: ResACLs},
|
||||
}
|
||||
deny := []Action{
|
||||
{Resource: ResRecords, Write: true, Zone: "example.com.", Name: "www.example.com.", Type: "TXT"},
|
||||
{Resource: ResRecords, Write: true, Zone: "example.com.", Name: "_acme-challenge.example.com.", Type: "A"},
|
||||
{Resource: ResRecords, Write: true, Zone: "other.org.", Name: "_acme-challenge.other.org.", Type: "TXT"},
|
||||
{Resource: ResZones, Write: true, Zone: "example.com."},
|
||||
{Resource: ResACLs, Write: true},
|
||||
}
|
||||
for _, a := range allow {
|
||||
if !p.Can(a) {
|
||||
t.Errorf("denied %s", a)
|
||||
}
|
||||
}
|
||||
for _, a := range deny {
|
||||
if p.Can(a) {
|
||||
t.Errorf("allowed %s", a)
|
||||
}
|
||||
}
|
||||
// A token narrows its user's permissions; it can't widen them.
|
||||
tp := &Principal{User: u, Token: &model.Token{Grants: []model.Grant{acme}}}
|
||||
if tp.Can(Action{Resource: ResACLs}) {
|
||||
t.Error("token restriction ignored")
|
||||
}
|
||||
if !tp.Can(allow[0]) {
|
||||
t.Error("token denied allowed action")
|
||||
}
|
||||
wide := &Principal{User: u, Token: &model.Token{Grants: []model.Grant{{Resource: ResAll, Access: Write}}}}
|
||||
if wide.Can(Action{Resource: ResACLs, Write: true}) {
|
||||
t.Error("token widened user's permissions")
|
||||
}
|
||||
// Admins can do everything, but not through restricted tokens.
|
||||
admin := &model.User{Username: "root", Admin: true}
|
||||
if !(&Principal{User: admin}).IsAdmin() || (&Principal{User: admin, Token: &model.Token{Grants: []model.Grant{reader}}}).IsAdmin() {
|
||||
t.Error("admin via restricted token")
|
||||
}
|
||||
if (&Principal{User: &model.User{Admin: true, Disabled: true}}).Can(Action{Resource: ResACLs}) {
|
||||
t.Error("disabled user allowed")
|
||||
}
|
||||
// View filters, with "_default" for zones outside views.
|
||||
vg, _ := ParseGrant("zones:write views=external")
|
||||
vp := &Principal{User: &model.User{Grants: []model.Grant{vg}}}
|
||||
if !vp.Can(Action{Resource: ResZones, Write: true, Zone: "example.com.", View: "external"}) || vp.Can(Action{Resource: ResZones, Write: true, Zone: "example.com.", View: "internal"}) || vp.Can(Action{Resource: ResZones, Write: true, Zone: "example.com."}) {
|
||||
t.Error("view filter wrong")
|
||||
}
|
||||
// CanSeeZone with a filtered records grant.
|
||||
sp := &Principal{User: &model.User{Grants: []model.Grant{acme}}}
|
||||
if !sp.CanSeeZone("example.com.", "") || sp.CanSeeZone("other.org.", "") {
|
||||
t.Error("CanSeeZone wrong")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoleTemplatesValid(t *testing.T) {
|
||||
for name, gs := range RoleTemplates {
|
||||
for _, g := range gs {
|
||||
gg := g
|
||||
if err := ValidateGrant(&gg); err != nil {
|
||||
t.Errorf("template %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"jarl/internal/model"
|
||||
)
|
||||
|
||||
// Resources that grants apply to.
|
||||
const (
|
||||
ResZones = "zones" // zone definitions and zone options
|
||||
ResRecords = "records" // records in zones
|
||||
ResViews = "views" // views and view options
|
||||
ResACLs = "acls"
|
||||
ResTSIG = "tsig" // TSIG keys
|
||||
ResOptions = "options" // server options, top-level statements, settings
|
||||
ResAudit = "audit" // audit log and everyone's changesets
|
||||
ResAll = "*"
|
||||
)
|
||||
|
||||
// Resources lists the resources in display order.
|
||||
var Resources = []string{ResZones, ResRecords, ResViews, ResACLs, ResTSIG, ResOptions, ResAudit}
|
||||
|
||||
// Access levels.
|
||||
const (
|
||||
Read = "read"
|
||||
Write = "write"
|
||||
)
|
||||
|
||||
// DefaultViewName is used for matching view filters against zones that
|
||||
// are not in a view.
|
||||
const DefaultViewName = "_default"
|
||||
|
||||
// ValidateGrant checks a grant and normalizes it.
|
||||
func ValidateGrant(g *model.Grant) error {
|
||||
g.Resource = strings.ToLower(strings.TrimSpace(g.Resource))
|
||||
g.Access = strings.ToLower(strings.TrimSpace(g.Access))
|
||||
ok := g.Resource == ResAll
|
||||
for _, r := range Resources {
|
||||
ok = ok || g.Resource == r
|
||||
}
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown resource %q (use one of %s or *)", g.Resource, strings.Join(Resources, ", "))
|
||||
}
|
||||
if g.Access != Read && g.Access != Write {
|
||||
return fmt.Errorf("access must be read or write, not %q", g.Access)
|
||||
}
|
||||
norm := func(list []string, lower bool, trimDot bool) []string {
|
||||
var out []string
|
||||
for _, s := range list {
|
||||
s = strings.TrimSpace(s)
|
||||
if lower {
|
||||
s = strings.ToLower(s)
|
||||
}
|
||||
if trimDot && s != "." {
|
||||
s = strings.TrimSuffix(s, ".")
|
||||
}
|
||||
if s != "" {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
g.Zones = norm(g.Zones, true, true)
|
||||
g.Views = norm(g.Views, false, false)
|
||||
g.Names = norm(g.Names, true, true)
|
||||
g.Types = norm(g.Types, false, false)
|
||||
for i, t := range g.Types {
|
||||
g.Types[i] = strings.ToUpper(t)
|
||||
}
|
||||
if (len(g.Names) > 0 || len(g.Types) > 0) && g.Resource != ResRecords {
|
||||
return fmt.Errorf("names and types filters only apply to the records resource")
|
||||
}
|
||||
if (len(g.Zones) > 0 || len(g.Views) > 0) && g.Resource != ResRecords && g.Resource != ResZones && g.Resource != ResViews {
|
||||
return fmt.Errorf("zone and view filters only apply to the zones, records and views resources")
|
||||
}
|
||||
for _, p := range append(append(append([]string{}, g.Zones...), g.Names...), g.Views...) {
|
||||
if strings.ContainsAny(p, " \t\n") {
|
||||
return fmt.Errorf("invalid pattern %q", p)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseGrant parses the compact grant syntax used by the CLI and docs:
|
||||
//
|
||||
// resource:access [zones=a,b] [views=x] [names=pattern] [types=TXT,CNAME]
|
||||
//
|
||||
// For example "records:write zones=example.com names=_acme-challenge.* types=TXT".
|
||||
func ParseGrant(s string) (model.Grant, error) {
|
||||
var g model.Grant
|
||||
fields := strings.Fields(s)
|
||||
if len(fields) == 0 {
|
||||
return g, fmt.Errorf("empty grant")
|
||||
}
|
||||
res, acc, ok := strings.Cut(fields[0], ":")
|
||||
if !ok {
|
||||
return g, fmt.Errorf("grant %q must start with resource:access, e.g. records:write", s)
|
||||
}
|
||||
g.Resource, g.Access = res, acc
|
||||
for _, f := range fields[1:] {
|
||||
k, v, ok := strings.Cut(f, "=")
|
||||
if !ok || v == "" {
|
||||
return g, fmt.Errorf("invalid filter %q (use key=value)", f)
|
||||
}
|
||||
vals := strings.Split(v, ",")
|
||||
switch strings.ToLower(k) {
|
||||
case "zone", "zones":
|
||||
g.Zones = append(g.Zones, vals...)
|
||||
case "view", "views":
|
||||
g.Views = append(g.Views, vals...)
|
||||
case "name", "names":
|
||||
g.Names = append(g.Names, vals...)
|
||||
case "type", "types":
|
||||
g.Types = append(g.Types, vals...)
|
||||
default:
|
||||
return g, fmt.Errorf("unknown filter %q (use zones, views, names or types)", k)
|
||||
}
|
||||
}
|
||||
return g, ValidateGrant(&g)
|
||||
}
|
||||
|
||||
// FormatGrant returns the compact form of a grant.
|
||||
func FormatGrant(g model.Grant) string {
|
||||
parts := []string{g.Resource + ":" + g.Access}
|
||||
add := func(k string, vals []string) {
|
||||
if len(vals) > 0 {
|
||||
parts = append(parts, k+"="+strings.Join(vals, ","))
|
||||
}
|
||||
}
|
||||
add("zones", g.Zones)
|
||||
add("views", g.Views)
|
||||
add("names", g.Names)
|
||||
add("types", g.Types)
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
// Action is something a principal wants to do.
|
||||
type Action struct {
|
||||
Resource string
|
||||
Write bool
|
||||
Zone string // zone FQDN (zones, records)
|
||||
View string // view name ("" for zones without a view)
|
||||
Name string // record owner FQDN (records)
|
||||
Type string // record type (records)
|
||||
}
|
||||
|
||||
func (a Action) String() string {
|
||||
acc := Read
|
||||
if a.Write {
|
||||
acc = Write
|
||||
}
|
||||
s := a.Resource + ":" + acc
|
||||
if a.Zone != "" {
|
||||
s += " zone " + strings.TrimSuffix(a.Zone, ".")
|
||||
}
|
||||
if a.View != "" {
|
||||
s += " view " + a.View
|
||||
}
|
||||
if a.Name != "" {
|
||||
s += " name " + strings.TrimSuffix(a.Name, ".")
|
||||
}
|
||||
if a.Type != "" {
|
||||
s += " type " + a.Type
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
var globCache sync.Map // pattern -> *regexp.Regexp
|
||||
|
||||
func globMatch(pattern, s string) bool {
|
||||
if pattern == "*" {
|
||||
return true
|
||||
}
|
||||
if !strings.ContainsAny(pattern, "*?") {
|
||||
return pattern == s
|
||||
}
|
||||
v, ok := globCache.Load(pattern)
|
||||
if !ok {
|
||||
var sb strings.Builder
|
||||
sb.WriteString("^")
|
||||
for _, c := range pattern {
|
||||
switch c {
|
||||
case '*':
|
||||
sb.WriteString(".*")
|
||||
case '?':
|
||||
sb.WriteString(".")
|
||||
default:
|
||||
sb.WriteString(regexp.QuoteMeta(string(c)))
|
||||
}
|
||||
}
|
||||
sb.WriteString("$")
|
||||
v, _ = globCache.LoadOrStore(pattern, regexp.MustCompile(sb.String()))
|
||||
}
|
||||
return v.(*regexp.Regexp).MatchString(s)
|
||||
}
|
||||
|
||||
func matchAny(patterns []string, s string, fold bool) bool {
|
||||
if len(patterns) == 0 {
|
||||
return true
|
||||
}
|
||||
if fold {
|
||||
s = strings.ToLower(s)
|
||||
}
|
||||
for _, p := range patterns {
|
||||
if globMatch(p, s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func trimName(n string) string {
|
||||
if n == "." {
|
||||
return n
|
||||
}
|
||||
return strings.TrimSuffix(strings.ToLower(n), ".")
|
||||
}
|
||||
|
||||
// GrantAllows reports whether g allows action a.
|
||||
func GrantAllows(g model.Grant, a Action) bool {
|
||||
if g.Resource != ResAll && g.Resource != a.Resource {
|
||||
return false
|
||||
}
|
||||
if a.Write && g.Access != Write {
|
||||
return false
|
||||
}
|
||||
if a.Zone != "" && !matchAny(g.Zones, trimName(a.Zone), true) {
|
||||
return false
|
||||
}
|
||||
view := a.View
|
||||
if view == "" {
|
||||
view = DefaultViewName
|
||||
}
|
||||
if (a.Zone != "" || a.Resource == ResViews) && !matchAny(g.Views, view, false) {
|
||||
return false
|
||||
}
|
||||
if a.Name != "" && !matchAny(g.Names, trimName(a.Name), true) {
|
||||
return false
|
||||
}
|
||||
if a.Type != "" && len(g.Types) > 0 {
|
||||
found := false
|
||||
for _, t := range g.Types {
|
||||
if strings.EqualFold(t, a.Type) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// GrantsAllow reports whether any grant allows a.
|
||||
func GrantsAllow(gs []model.Grant, a Action) bool {
|
||||
for _, g := range gs {
|
||||
if GrantAllows(g, a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Principal is an authenticated identity.
|
||||
type Principal struct {
|
||||
User *model.User
|
||||
Token *model.Token // nil for sessions and local CLI use
|
||||
Method string // session, token, local
|
||||
IP string
|
||||
Agent string
|
||||
}
|
||||
|
||||
// System is the principal used for internal operations.
|
||||
var System = &Principal{User: &model.User{ID: 0, Username: "system", Admin: true}, Method: "local"}
|
||||
|
||||
// Name returns a display name for the principal.
|
||||
func (p *Principal) Name() string {
|
||||
if p == nil || p.User == nil {
|
||||
return ""
|
||||
}
|
||||
return p.User.Username
|
||||
}
|
||||
|
||||
// IsAdmin reports whether the principal has admin rights. Admin rights
|
||||
// are never available through a restricted token.
|
||||
func (p *Principal) IsAdmin() bool {
|
||||
if p == nil || p.User == nil || !p.User.Admin {
|
||||
return false
|
||||
}
|
||||
return p.Token == nil || p.Token.Grants == nil
|
||||
}
|
||||
|
||||
// Can reports whether the principal may perform a.
|
||||
func (p *Principal) Can(a Action) bool {
|
||||
if p == nil || p.User == nil || p.User.Disabled {
|
||||
return false
|
||||
}
|
||||
userOK := p.User.Admin || GrantsAllow(p.User.Grants, a)
|
||||
if !userOK {
|
||||
return false
|
||||
}
|
||||
if p.Token != nil && p.Token.Grants != nil {
|
||||
return GrantsAllow(p.Token.Grants, a)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// CanSeeZone reports whether the principal may see that a zone exists:
|
||||
// any read access to the zone definition or to some of its records.
|
||||
func (p *Principal) CanSeeZone(zone, view string) bool {
|
||||
if p.Can(Action{Resource: ResZones, Zone: zone, View: view}) {
|
||||
return true
|
||||
}
|
||||
// Records access with name/type filters still reveals the zone.
|
||||
check := func(gs []model.Grant) bool {
|
||||
for _, g := range gs {
|
||||
if g.Resource != ResAll && g.Resource != ResRecords && g.Resource != ResZones {
|
||||
continue
|
||||
}
|
||||
ng := g
|
||||
ng.Names, ng.Types = nil, nil
|
||||
if GrantAllows(ng, Action{Resource: g.Resource, Zone: zone, View: view}) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
if p.User == nil || p.User.Disabled {
|
||||
return false
|
||||
}
|
||||
if !p.User.Admin && !check(p.User.Grants) {
|
||||
return false
|
||||
}
|
||||
if p.Token != nil && p.Token.Grants != nil {
|
||||
return check(p.Token.Grants)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Summary describes effective permissions for display.
|
||||
func (p *Principal) Summary() []string {
|
||||
if p.IsAdmin() {
|
||||
return []string{"admin (everything)"}
|
||||
}
|
||||
var out []string
|
||||
gs := p.User.Grants
|
||||
if p.User.Admin {
|
||||
gs = []model.Grant{{Resource: ResAll, Access: Write}}
|
||||
}
|
||||
for _, g := range gs {
|
||||
out = append(out, FormatGrant(g))
|
||||
}
|
||||
if p.Token != nil && p.Token.Grants != nil {
|
||||
var tg []string
|
||||
for _, g := range p.Token.Grants {
|
||||
tg = append(tg, FormatGrant(g))
|
||||
}
|
||||
out = append(out, "restricted by token to: "+strings.Join(tg, "; "))
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// RoleTemplates are ready-made grant sets offered in the UI and CLI.
|
||||
var RoleTemplates = map[string][]model.Grant{
|
||||
"readonly": {{Resource: ResAll, Access: Read}},
|
||||
"dns-editor": {
|
||||
{Resource: ResZones, Access: Write},
|
||||
{Resource: ResRecords, Access: Write},
|
||||
{Resource: ResViews, Access: Read},
|
||||
{Resource: ResACLs, Access: Read},
|
||||
{Resource: ResOptions, Access: Read},
|
||||
},
|
||||
"operator": {{Resource: ResAll, Access: Write}},
|
||||
"acme": {{Resource: ResRecords, Access: Write, Names: []string{"_acme-challenge.*"}, Types: []string{"TXT"}}},
|
||||
}
|
||||
Reference in new issue
Block a user